Technical Deep Dive into Webhooks in PHP

Utpatrick
3 min readAug 29, 2024

--

Webhooks are a powerful tool in web development, allowing your application to receive real-time data from external services. This article explores how webhooks work under the hood, how to handle them effectively in PHP, and best practices for ensuring security and reliability.

Understanding the Basics

A webhook is an HTTP request sent from one server (provider) to another (receiver) when a specific event occurs. The provider sends data related to the event, usually in JSON format, to a predefined URL on your server.

The Webhook Workflow:

  1. Event Trigger: An action occurs on the provider’s platform (e.g., payment completion, user signup).
  2. Webhook Request: The provider sends an HTTP POST request to your specified URL, containing event data.
  3. Response: Your server processes the data and responds with an HTTP status code (e.g., 200 OK).

Setting Up the Webhook Receiver in PHP

1. Create a PHP Endpoint:

This endpoint will be the URL where the provider sends the webhook data. Here’s an example:

<?php
// webhook.php

// Read the raw POST data
$payload = file_get_contents('php://input');

// Decode the JSON payload
$data = json_decode($payload, true);

// Check for the desired event type
if (isset($data['event']) && $data['event'] === 'payment.success') {

// Access specific data from the payload
$paymentId = $data['data']['id'];
$amount = $data['data']['amount'];
$currency = $data['data']['currency'];
$status = $data['data']['status'];

// Process the data (e.g., update database, send email)
// Example: Log to a file
file_put_contents('webhook_log.txt', "Payment ID: $paymentId, Amount: $amount $currency, Status: $status\n", FILE_APPEND);

// Respond with success
http_response_code(200);
echo json_encode(['status' => 'success', 'message' => 'Webhook received']);
} else {
// Respond with error for invalid event
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'Invalid event']);
}
?>

2. Configure the Webhook URL with the Provider:

  • Locate the webhook settings section in the provider’s dashboard.
  • Enter the URL of your webhook.php script (e.g., https://yourdomain.com/webhook.php).
  • Specify the events you want to receive notifications for (e.g., payment success, order created).

3. Test the Webhook:

Most providers offer ways to test webhooks by simulating events. This helps ensure your endpoint functions correctly.

Handling Webhooks Securely

Security is paramount when dealing with webhooks, as they involve sensitive data and direct server communication. Here are key practices:

1. Verify the Webhook Signature:

Many providers include a signature in the request headers to verify its legitimacy. Here’s an example of signature verification:

<?php
// webhook.php

$secret = 'your-secret-key';

// Get the raw POST data
$payload = file_get_contents('php://input');

// Retrieve the signature from headers
$headers = getallheaders();
$signature = $headers['X-Signature'] ?? '';

// Generate the expected signature
$expectedSignature = hash_hmac('sha256', $payload, $secret);

// Compare the signatures
if (hash_equals($expectedSignature, $signature)) {
// Request is verified, process the webhook
$data = json_decode($payload, true);
// ... (process data)
} else {
// Invalid signature, reject the request
http_response_code(403);
echo json_encode(['status' => 'error', 'message' => 'Invalid signature']);
}
?>

2. Handle Idempotency:

Webhooks might be sent multiple times for the same event. Use a unique identifier (e.g., payment ID) to ensure actions are only performed once. Store this identifier in your database and check if the event has already been processed.

3. Respond Quickly:

Providers typically expect a response within a few seconds. If processing takes longer, acknowledge the request first and handle it asynchronously

--

--