π 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):
- You create an endpoint (e.g.,
webhook.php) to listen for data. - A service (like Stripe, GitHub, Razorpay, etc.) is configured to send data to this endpoint when a specific event occurs.
- PHP script processes the request (e.g., store in DB, send email, etc.)
β Advantages of Webhooks
| Advantage | Description |
|---|---|
| π Real-time updates | No need to poll the API repeatedly. Instant notifications. |
| π Efficient | Saves bandwidth & resources compared to polling. |
| π Event-driven architecture | Automate workflows like sending emails, updating DB, etc. |
| π¦ Lightweight integration | Only a simple HTTP endpoint is needed. |
| π° Cost-effective | Reduces API requests and infrastructure usage. |
π Use Cases of Webhooks
| Use Case | Description |
|---|---|
| π³ Payment Gateway | Notify backend when payment is successful (Razorpay, Stripe, PayPal). |
| π E-commerce Order Updates | Trigger order processing or shipping once an order is placed. |
| π¦ Inventory Sync | Update stock levels in real-time from supplier systems. |
| π§Ύ Invoice Generation | Auto-generate invoices when payment is received. |
| π GitHub Integration | Trigger CI/CD pipelines when code is pushed. |
| π§βπΌ CRM Update | Automatically update lead status based on form submissions or events. |
| π¬ Chatbot Integration | Trigger 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_tallySalesListtable 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
feedbackstable.
// 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
| Practice | Reason |
|---|---|
| β Signature Verification | Prevent fake requests |
| β IP Whitelisting | Allow only known systems to send data |
| β Authentication Token | Use bearer token or secret key in headers |
| β Log All Webhook Events | For debugging and replay if needed |
β Summary of Your Projectβs Webhook Integration Ideas
| Use Case | Trigger Source | Your App Action |
|---|---|---|
| Sales invoice added | ERP or billing software | Insert into pbi_tallySalesList |
| Stock updated | Warehouse system | Update product_inventory |
| Distributor submits feedback | Google Form via Zapier | Save into feedbacks table |
| Target not met | Cronjob / scheduled check | Send webhook to Slack/email/alert |
| Payment received | Razorpay/Stripe webhook | Confirm 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
| Item | Description |
|---|---|
| Language | PHP |
| Use | Receive real-time event data from external services |
| Benefits | Efficient, real-time, simple to integrate |
| Use Cases | Payment processing, order updates, CRM sync, GitHub hooks |
| Real Example | Razorpay, 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
$data = json_decode(file_get_contents(“php://input”), true);
POST data:$data = json_decode(file_get_contents(“php://input”), true);
How do I test my webhook in PHP?
How do I secure a webhook?
β
Use HMAC signature verification
β Add secret tokens in headers
β Validate IP addresses
β Check for replay attacks using timestamps
β 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
}
{
“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
Less secure
Limited payload size
How can I debug webhook issues?
β
Log all incoming requests (
β Check headers and payloads
β Validate signature manually
β Use
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
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).
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.
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
Add
Check if
event_id already exists in DB before insertingAdd
UNIQUE index on event_idCan I disable or pause webhooks?
Yes. Most platforms (e.g., GitHub, Stripe, PayPal) allow:
Disabling individual webhooks
Setting webhook status to inactive
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.
