I am setting up a page for order.created webhook to post to on my website. The problem that I am running into is that the PHP code that is provided by Square to verify that the request came from Square is not working with the webhook that I set up in my Square Sandbox. Even when running the code below, the 403 response code is being returned when testing from the Square Sandbox.
If I remove the call to the isFromSquare method from my actual (not the test script posted below) PHP script, the request saves to the database as expected.
Please advise what I am missing or doing wrong.
Web page code
<?php
// The URL where event notifications are sent.
define("NOTIFICATION_URL", "https://rhtservices.net/api/test.php");
// The signature key defined for the subscription.
define("SIGNATURE_KEY", "_xRrk2tI9p6m429xcKxWFg");
// isFromSquare generates a signature from the url and body and compares it to the Square signature header.
function isFromSquare($signature, $body) {
$hash = hash_hmac("sha256", NOTIFICATION_URL.$body, SIGNATURE_KEY, true);
return base64_encode($hash) == $signature;
}
// Start a simple server for local testing.
// Different frameworks may provide the raw request body in other ways.
// INSTRUCTIONS
// 1. Run the server:
// php -S localhost:8000 server.php
// 2. Send the following request from a separate terminal:
// curl -vX POST localhost:8000 -d '{"hello":"world"}' -H "X-Square-HmacSha256-Signature: 2kRE5qRU2tR+tBGlDwMEw2avJ7QM4ikPYD/PJ3bd9Og="
$headers = apache_request_headers();
$signature = $headers["X-Square-HmacSha256-Signature"];
$body = '';
$handle = fopen('php://input', 'r');
while(!feof($handle)) {
$body .= fread($handle, 1024);
}
if (isFromSquare($signature, $body)) {
// Signature is valid. Return 200 OK.
http_response_code(200);
echo "Request body: $body\n";
} else {
// Signature is invalid. Return 403 Forbidden.
http_response_code(403);
}
return http_response_code();
?>
Endpoint details
PropertiesEnabled
NAME
ordercreated
URL
https://rhtservices.net/api/test.php
VERSION
2022-11-16
SIGNATURE KEY
_xRrk2tI9p6m429xcKxWFg
Hide