How to build a Webhook system using PHP in 5 minutes
What are the Webhooks?
A webhook is a way for one application or service to provide real-time data or notifications to another application or service.
It allows one system to send data to another system as soon as a certain event or trigger occurs, without the need for the receiving system to repeatedly poll for updates.
Here's how a webhook typically works:
Event Occurs: In the context of webhooks, an "event" could be anything from a new order being placed on an e-commerce website to a new comment being posted on a social media platform. It's a significant occurrence that the sender wants to notify other systems about.
Notification: Instead of having the recipient system continuously check (poll) for these events, the sending system will make a POST request to a predefined URL (webhook endpoint) on the recipient system as soon as the event occurs. This POST request contains relevant data about the event, often in a structured format like JSON or XML.
Webhook Listener: The recipient system, which hosts the webhook endpoint, has a script that listens for incoming POST requests at that URL. This script processes the data received in the request and takes appropriate actions based on the event.
Real-Time Response: After processing the data, the recipient system can optionally send a response back to the sending system. This response can indicate that the data was successfully received and processed.
Webhooks are commonly used for various purposes, such as:
Integration: Connecting different services to allow them to communicate and share data. For example, notifying a CRM system when a new lead signs up on a website.
Notifications: Sending immediate notifications to users or administrators when specific events occur, like sending an email when a payment is received.
Automation: Triggering actions automatically based on events, such as updating inventory levels when an order is placed.
Real-Time Updates: Keeping systems in sync by notifying them about changes, like updating a dashboard when new data is available.
Webhooks are an efficient way to achieve real-time communication between different systems without the need for constant polling.
Who is webhooks and where to use?
Many companies and services provide APIs that include webhook functionality as part of their offerings.
for examples
Payment Processors: Companies like Stripe, PayPal, and Square offer webhook support to notify your application about payment-related events.
E-commerce Platforms: E-commerce platforms like Shopify, WooCommerce, and Magento often provide webhook capabilities to notify you about order updates, new customers, and other events.
Messaging and Communication APIs: Services like Twilio, SendGrid, and Pusher offer webhooks to provide real-time notifications for SMS, email, and real-time messaging events.
Social Media Platforms: Social media APIs like Facebook Graph API and Twitter API offer webhooks to receive notifications about user interactions, new posts, and other social media activities.
Cloud Services: Cloud providers like AWS, Google Cloud, and Microsoft Azure provide webhook capabilities as part of their broader offerings to trigger actions based on various cloud events.
Web Services and APIs: Many web services, such as GitHub, Bitbucket, and Dropbox, offer webhooks to inform you about changes to repositories, files, and other resources.
IoT Platforms: Internet of Things (IoT) platforms like Particle and IoT cloud services often include webhook support to connect physical devices to web-based applications.
Webhooks Structure
A webhook structure refers to the format and content of the data that is sent from one system to another when a webhook event occurs.
Webhook data is typically sent as an HTTP POST request to a predefined URL (webhook endpoint) on the recipient system. The structure of the webhook payload depends on the service or system sending the webhook, but it usually follows a consistent format.
Here's a general outline of what a webhook payload structure might look like in JSON format:
A typical webhook payload has a structure similar, but however, there is no rule (a part the security of your enviroment):
event_type: This field indicates the type of event that occurred. It helps the recipient system identify what action to take based on the event.
data: This field holds the actual data related to the event. The structure of the data will vary depending on the event type. It might include information about a new order, a customer, a payment, or any other relevant details.
timestamp: The timestamp indicates when the event occurred. It helps in tracking the timing of the event.
source: This field provides information about the source of the webhook. It might include details like the name of the external service that triggered the webhook.
A webhook structure refers to the format and content of the data that is sent from one system to another when a webhook event occurs. Webhook data is typically sent as an HTTP POST request to a predefined URL (webhook endpoint) on the recipient system. The structure of the webhook payload depends on the service or system sending the webhook, but it usually follows a consistent format.
Here's a general outline of what a webhook payload structure might look like in JSON format:
{
"event_type": "order_created",
"data": { // Event-specific data },
"timestamp": "2023-08-10T12:34:56Z",
"source": { "system": "external_service",
"name": "Service Name" }
}
Webhooks listeners
A webhook listener is a piece of software or code that is set up to receive and process incoming webhook notifications.
When an external service or system wants to notify your application about a specific event, it sends an HTTP POST request containing data related to that event to a URL you've provided, known as the webhook endpoint.
The webhook listener is responsible for capturing and handling this incoming POST request.
Here's the webhook listener structure, in PHP used in the examples below:
Setting Up a Webhook Endpoint: In your application, you specify a URL (webhook endpoint) where you want to receive incoming webhook notifications. This URL is where the external service will send its POST requests.
Implementing the Listener: You create a script or code that listens for incoming POST requests at the webhook endpoint. This script will capture the data included in the POST request's payload.
Processing the Payload: Once the listener receives the POST request, it extracts the data (payload) from the request's body. The payload contains information about the event that occurred.
Taking Action: Based on the contents of the payload, the webhook listener performs actions in your application. This could involve updating your database, sending notifications, triggering processes, or any other desired actions.
Responding to the Request: After processing the payload, the webhook listener might send a response back to the external service. This response could indicate that the data was successfully received and processed.
Implementi the PHP listener:<?php // Original Answer header('Content-Type: application/json'); $request = file_get_contents('php://input'); $req_dump = print_r( $request, true ); $fp = file_put_contents( 'request.log', $req_dump ); // Updated Answer if($json = json_decode(file_get_contents("php://input"), true)){ $data = $json; } print_r($data); ?>
Implementing the Listener:
header('Content-Type: application/json');
This line sets the HTTP response header to indicate that the response content will be in JSON format.file_get_contents('php://input')
This retrieves the raw data from the incoming HTTP request's body using thephp://input
stream.
It's typically used when data isn't automatically parsed into variables like$_POST
.print_r($request, true)
Theprint_r
function is used to print a human-readable representation of the data. The second argumenttrue
specifies that the output should be returned as a string instead of being printed immediately.file_put_contents('request.log', $req_dump);
This line writes the data captured from the request to a log file named "request.log".json_decode($request, true)
:
This attempts to decode the JSON data in the$request
variable into an associative array. The second argument,true
, indicates that the JSON should be decoded as an associative array.if ($json = json_decode($request, true)) { ... }
:
This checks if the JSON decoding was successful. If successful, it assigns the decoded JSON data to the$json
variable.$data = $json;
If the JSON decoding was successful, this line assigns the decoded JSON data (stored in$json
) to the$data
variable.print_r($data);
This line prints the contents of the$data
variable, which should be the JSON data decoded into an associative array.
The purpose of this code is to receive an incoming JSON payload, log it to a file, attempt to decode it as JSON, and then print the decoded JSON data to the response.
Let’s call this page webhook.php and upload it to a PHP server, after:
<?PHP
$name = $_GET['name'];
$surname = $_GET['surname'];
$datetime = date("h:i:sa");
$curl_fetch_api = curl_init();
curl_setopt_array($curl_fetch_api, array(
CURLOPT_URL => "YOUR URL",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => '{
"properties": {
"name": "'.$name.'",
"surname": "'.$surname.'",
"datetime": "'.$datetime.'"
}
}',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
));
$hs_fetch_api = curl_exec($curl_fetch_api);
$obj_fetch_api = json_decode($hs_fetch_api, true);
var_dump($hs_fetch_api);
?>
The breakdown$name = $_GET['name'];
and $surname = $_GET['surname'];
: These lines retrieve values from the query parameters in the URL. They assume that the values are provided in the URL like http://example.com/script.php?name=John&surname=Doe
.
Note, in the example, we pass GET information just to demonstrate the data through by, but mainly data in webhooks uses POST data
$datetime = date("h:i:sa");
This line gets the current time using thedate
function and formats it as "hour:minute:second AM/PM".curl_init();
Initializes a cURL session for making an HTTP request.curl_setopt_array($curl_fetch_api, array(...));
:
Sets various cURL options for making an HTTP POST request. It includes the target URL, request payload (JSON), headers, and other settings.$hs_fetch_api = curl_exec($curl_fetch_api);
:
Executes the cURL request and stores the response in the$hs_fetch_api
variable.$obj_fetch_api = json_decode($hs_fetch_api, true);
:
Decodes the JSON response into an associative array usingjson_decode
. The decoded data is stored in the$obj_fetch_api
variable.var_dump($hs_fetch_api);
:
Prints the raw API response for debugging purposes. This will show the actual content of the HTTP response.curl_close($curl_fetch_api);
Closes the cURL session.
This code snippet is an example of how to use cURL to make an HTTP POST request with JSON data to a specified URL.
It sends data as a JSON payload to an API, retrieves the response, and then decodes and processes it.
Note that you should replace "YOUR URL"
with the actual URL you want to send the request to.
Responding to the Request:
Once data are sent to webhook.php, the host will answer with a Json ready to be read from your application:
string(417) "{ "properties": { "name": "gustavo", "surname": "defelice", "datetime": "02:03:59pm" } }Array ( [properties] => Array ( [name] => gustavo [surname] => defelice [datetime] => 02:03:59pm ) ) "
and the request log into server filled with the JSON
{
"properties": {
"name": "gustavo",
"surname": "defelice",
"datetime": "02:03:59pm"
}
}
Taking Action & Responding Request:
When a webhook listener receives an incoming webhook notification, it needs to take specific actions based on the event that triggered the webhook.
The actions you take depend on your application's requirements and the purpose of the webhook. Here's a more detailed explanation:
Event Identification: The payload of the webhook contains information about the event that occurred. This information is usually stored in fields like
event_type
ortype
. By examining this event type, your webhook listener can determine what kind of event has taken place.Processing Data: The webhook payload often includes data relevant to the event. For example, if the event is "order_created," the payload might include details about the new order. Your webhook listener should extract and process this data, which might involve updating your database, sending notifications, or triggering other workflows.
Business Logic: Based on the event type and the extracted data, your webhook listener should execute the necessary business logic. For instance, if it's a payment received event, you might update the customer's account balance or mark the order as paid.
Error Handling: While processing the webhook, you should also handle potential errors or exceptions gracefully. If something goes wrong during data processing, you might want to log the error, notify administrators, or take corrective actions.
Moreover, after your webhook listener has processed the incoming webhook payload and taken the appropriate actions, you might choose to send a response back to the external service that initiated the webhook.
Responding to the request is not always necessary, but it can provide confirmation that your system received and processed the data correctly. Here's how this works:
HTTP Response: After processing the webhook payload, your webhook listener can send an HTTP response to the external service. This response typically includes an HTTP status code that indicates the outcome of the processing. Common success codes include
200 OK
, while error codes might indicate issues like400 Bad Request
or500 Internal Server Error
.Response Content: In addition to the status code, you can include response content that provides additional information about the processing outcome.
This content could be a simple acknowledgement message, an error description, or any other relevant information.Asynchronous Processing: Keep in mind that webhook processing might be asynchronous. This means that the external service might not wait for your response and could continue its own operations. Therefore, the response you send might not be immediately processed by the external service.
Response Format: Just like with the request payload, the response you send back should follow the agreed-upon format if any is specified by the external service's documentation. This format might include expected fields like
status
,message
, or other relevant data.
In many cases, whether to send a response and what kind of response to send depends on the requirements of the external service. Some services require responses to ensure successful delivery, while others might not expect or rely on responses.
It's important to consult the documentation of the service sending the webhook to understand their expectations regarding responses.
Below is a video that will help you to build the application:
Support my work and help keep the insights coming by contributing just few dollars—your generosity fuels this publication!