HomePHPWebhook in PHP: Overview, Advantages, Use Cases & Real-World Example

Webhook in PHP: Overview, Advantages, Use Cases & Real-World Example

πŸ”„ What is a Webhook?

A webhook is a way for one application to send real-time data to another application via an HTTP POST request whenever a certain event occurs.

Unlike polling (where the system repeatedly asks for updates), webhooks push data to your application via an HTTP request (usually POST).

In PHP, you create a webhook receiver (endpoint) that accepts and processes the incoming request.


πŸ”§ How Webhook Works in PHP (Basic Flow):

  1. You create an endpoint (e.g., webhook.php) to listen for data.
  2. A service (like Stripe, GitHub, Razorpay, etc.) is configured to send data to this endpoint when a specific event occurs.
  3. PHP script processes the request (e.g., store in DB, send email, etc.)

βœ… Advantages of Webhooks

AdvantageDescription
πŸ”” Real-time updatesNo need to poll the API repeatedly. Instant notifications.
πŸš€ EfficientSaves bandwidth & resources compared to polling.
πŸ”„ Event-driven architectureAutomate workflows like sending emails, updating DB, etc.
πŸ“¦ Lightweight integrationOnly a simple HTTP endpoint is needed.
πŸ’° Cost-effectiveReduces API requests and infrastructure usage.

πŸ“Œ Use Cases of Webhooks

Use CaseDescription
πŸ’³ Payment GatewayNotify backend when payment is successful (Razorpay, Stripe, PayPal).
πŸ›’ E-commerce Order UpdatesTrigger order processing or shipping once an order is placed.
πŸ“¦ Inventory SyncUpdate stock levels in real-time from supplier systems.
🧾 Invoice GenerationAuto-generate invoices when payment is received.
πŸ›  GitHub IntegrationTrigger CI/CD pipelines when code is pushed.
πŸ§‘β€πŸ’Ό CRM UpdateAutomatically update lead status based on form submissions or events.
πŸ’¬ Chatbot IntegrationTrigger bot replies when user performs action on another platform.

🌍 Real-World Example: Razorpay Webhook in PHP

πŸ› Use Case: Razorpay notifies your app when a payment is successful.

πŸ”— Step 1: Create PHP Webhook Receiver (webhook.php)

<?php
// webhook.php

$input = @file_get_contents("php://input");
$data = json_decode($input, true);

// Optional: Verify Razorpay signature (for security)
$signature = $_SERVER['HTTP_X_RAZORPAY_SIGNATURE'];
$secret = "your_secret_key";

function verifySignature($data, $signature, $secret) {
    $generated = hash_hmac('sha256', $data, $secret);
    return hash_equals($generated, $signature);
}

if (verifySignature($input, $signature, $secret)) {
    // Process the event
    $event = $data['event'];

    if ($event == "payment.captured") {
        $payment_id = $data['payload']['payment']['entity']['id'];
        $amount = $data['payload']['payment']['entity']['amount'];

        // Store payment or trigger order processing
        file_put_contents("logs.txt", "Payment received: $payment_id - β‚Ή" . ($amount / 100));
    }
    http_response_code(200);
} else {
    // Invalid Signature
    http_response_code(403);
    echo "Signature verification failed.";
}

πŸ”” Webhook Use Cases for Your Project

🧾 1. Auto-update Sales Report from External ERP or Billing Software

  • Use Case: A third-party billing software (like Tally, Zoho, or a distributor app) sends a webhook to your app when a new order or sales invoice is created.
  • Your Action in PHP: Update pbi_tallySalesList table automatically.
// receive_sales_webhook.php
$input = json_decode(file_get_contents("php://input"), true);

if (!empty($input['orderNumber'])) {
    $partyName = addslashes($input['partyName']);
    $orderNumber = addslashes($input['orderNumber']);
    $voucherAmount = floatval($input['voucherAmount']);
    $orderDate = strtotime($input['orderDate']);

    $con = mysqli_connect("localhost", "root", "", "your_db");
    $sql = "INSERT INTO pbi_tallySalesList (partyName, orderNumber, tVoucherAmount, orderDate)
            VALUES ('$partyName', '$orderNumber', '$voucherAmount', '$orderDate')";
    mysqli_query($con, $sql);

    http_response_code(200);
    echo "Sales record received.";
} else {
    http_response_code(400);
    echo "Invalid webhook data.";
}

πŸ“¦ 2. Update Stock in Real-Time

  • Use Case: Warehouse system sends webhook when product stock is updated.
  • Your Action: Update inventory table so dashboard always shows current stock.
// webhook_stock_update.php
$data = json_decode(file_get_contents("php://input"), true);

if (isset($data['product_id'], $data['new_stock'])) {
    $productId = intval($data['product_id']);
    $stock = intval($data['new_stock']);

    $con = mysqli_connect("localhost", "root", "", "your_db");
    $update = "UPDATE product_inventory SET stock = $stock WHERE product_id = $productId";
    mysqli_query($con, $update);

    echo "Stock updated.";
} else {
    http_response_code(422);
    echo "Missing fields";
}

πŸ”„ 3. Webhook from Google Forms (via automation tool like Make/Zapier)

  • Use Case: When someone submits a Google Form (like distributor feedback), it sends data to your PHP app.
  • Your Action: Insert the feedback into feedbacks table.
// google_form_webhook.php
$input = json_decode(file_get_contents("php://input"), true);
$name = $input['name'] ?? '';
$feedback = $input['message'] ?? '';

$con = mysqli_connect("localhost", "root", "", "your_db");
mysqli_query($con, "INSERT INTO feedbacks (name, message) VALUES ('$name', '$feedback')");
echo "Thank you for your feedback!";

πŸ“§ 4. Send Email or Slack Notification When Target Missed

  • Use Case: If sales target not met, a backend cron script triggers a webhook to another internal system (email API or Slack bot).
  • PHP Code (Sender):
$data = ['zone' => 'North', 'target' => 100000, 'actual' => 54000];
$ch = curl_init("https://yourinternalapi.com/notify_target.php");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

πŸ”’ Security Tips for Webhooks

PracticeReason
βœ… Signature VerificationPrevent fake requests
βœ… IP WhitelistingAllow only known systems to send data
βœ… Authentication TokenUse bearer token or secret key in headers
βœ… Log All Webhook EventsFor debugging and replay if needed

βœ… Summary of Your Project’s Webhook Integration Ideas

Use CaseTrigger SourceYour App Action
Sales invoice addedERP or billing softwareInsert into pbi_tallySalesList
Stock updatedWarehouse systemUpdate product_inventory
Distributor submits feedbackGoogle Form via ZapierSave into feedbacks table
Target not metCronjob / scheduled checkSend webhook to Slack/email/alert
Payment receivedRazorpay/Stripe webhookConfirm order / send receipt

πŸ§ͺ Testing

  • Use Razorpay test mode or tools like Postman or Webhook.site to simulate events.

🧠 Best Practices

  • βœ… Always verify signature to avoid fake requests.
  • βœ… Log all incoming data for debugging.
  • βœ… Respond quickly (return HTTP 200 within 5 seconds).
  • βœ… Make webhook URL private or obfuscated (not guessable).

πŸ“š Summary

ItemDescription
LanguagePHP
UseReceive real-time event data from external services
BenefitsEfficient, real-time, simple to integrate
Use CasesPayment processing, order updates, CRM sync, GitHub hooks
Real ExampleRazorpay, Stripe, GitHub, PayPal, Twilio

What is a webhook?

A webhook is a way for one application to send real-time data to another application via an HTTP POST request whenever a certain event occurs.

How do I create a webhook in PHP?

You create a webhook endpoint (a PHP file) that listens for POST data:

$data = json_decode(file_get_contents(“php://input”), true);

How do I test my webhook in PHP?

Use tools like:

Webhook.site
RequestBin
Postman
Localhost with ngrok

How do I secure a webhook?

βœ… Use HMAC signature verification
βœ… Add secret tokens in headers
βœ… Validate IP addresses
βœ… Check for replay attacks using timestamps

What kind of data do webhooks send?

Usually JSON data. Example:

{
“event”: “order.created”,
“order_id”: “ORD123”,
“amount”: 1499
}

Can I use GET requests with webhooks?

Most webhook systems use POST requests. GET is not recommended due to:

Less secure
Limited payload size

How can I debug webhook issues?

βœ… Log all incoming requests (file_put_contents("log.txt", $input);)
βœ… Check headers and payloads
βœ… Validate signature manually
βœ… Use ngrok or webhook log history (e.g., Stripe dashboard)

What if my server is down? Will I miss the webhook?

Depends on the service:

Some retry automatically (e.g., Stripe, Razorpay)
Others may not retry, so store logs and send a manual resend request

Can webhooks be delayed?

Yes. Due to:

Network latency
Retry delays
Processing queue at sender’s end
Usually still near real-time (within seconds).

Is webhook one-way or two-way communication?

One-way: Sender ➜ Receiver
If you need a response, you must set up an API instead.

How can I handle duplicate webhooks?

Use unique event IDs or timestamps:

Check if event_id already exists in DB before inserting
Add UNIQUE index on event_id

Can I disable or pause webhooks?

Yes. Most platforms (e.g., GitHub, Stripe, PayPal) allow:

Disabling individual webhooks
Setting webhook status to inactive

Can I resend webhook events manually?

Yes. Many services (e.g., Stripe, GitHub) allow you to retry or replay failed events from their dashboard.

Share:Β 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *