Code example for webhook handling

Check out the basic code example for webhook handling. Use it to quickstart with your webhookUrl endpoint if it supports PHP.

The code:

  • Receives a webhook

  • Responds with HTTP 200 OK call to confirm receiving a webhook

  • Parses webhook body and defines variables with its data

<?php 

// Get contents of webhook request
$requestBody = file_get_contents('php://input');
// your client_secret value on https://my.ecwid.com/#develop-apps page; NOT your 'secret_*' access token.
$client_secret = 'abcde123456789';

// Parse webhook data and reply with 200OK to Ecwid
$decodedBody = json_decode($requestBody, true);

$eventId = $decodedBody['eventId'];
$eventCreated = $decodedBody['eventCreated'];
$storeId = $decodedBody['storeId'];
$entityId = $decodedBody['entityId'];
$eventType = $decodedBody['eventType'];
$data = $decodedBody['data'];

http_response_code(200);

// (Optional) Filter out events you're not interested in.
// If you receive webhooks for events you don't need, email us to disable these events
// Our email: [email protected]
if ($eventType !== 'order.updated') {
    exit;
}

// Authenticate webhook signature to verify it came from Ecwid
if (!$signatureHeaderPresent) {
	echo 'Signature verification failed';
	exit;
}

if (!function_exists('getallheaders')) {
    function getallheaders()
    {
        foreach ($_SERVER as $name => $value) {
            if (substr($name, 0, 5) == 'HTTP_') {
                $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
            }
        }
        return $headers;
    }
}

foreach (getallheaders() as $name => $value) {
    if ($name == "X-Ecwid-Webhook-Signature") {
        $headerSignature = "$value";
      	$signatureHeaderPresent = true;
        
        $hmac_result = hash_hmac("sha256", "$eventCreated.$eventId", $client_secret, true);
        $generatedSignature = base64_encode($hmac_result);
        
        if ($generatedSignature !== $headerSignature) {
            echo 'Signature verification failed';
            exit;
        }
    }
}

// If the webhook was authenticated, get data from $decodedBody and handle the event
//
// Otherwise, email us and provide us with all details on the failed event 

?>

Last updated

Was this helpful?