Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Setup Webhook Receiver with signature verification

Tags:

php

xero-api

I need to setup a PHP page for receiving Webhooks - I've done many of these in the past so that is not a problem, but the API I'm working with for this project requires that my webhook verifies the signature provided in the header.

As part of the validation request it will send the following:

HEADER:
 "x-xero-signature" : HASH_VALUE
PAYLOAD:
{
   "events": [],
   "lastEventSequence": 0,
   "firstEventSequence": 0,
   "entropy": "S0m3r4N0m3t3xt"
}

I've created a Webhook key (e.g. 'ABC123'), and as part of the validation request for this Webhook I must ensure that the payload which is hashed using HMACSHA256 with your webhook key and base64 encoded should match the signature in the header. This is a correctly signed payload. If the signature does not match the hashed payload it is an incorrectly signed payload.

To gain Intent to Receive validation, the receiving url must respond with status: 200 Ok for all correctly signed payloads and respond with status: 401 Unauthorized for all incorrectly signed payloads.

I'm a bit lost at this point as to how to go about this - the details for this setup can be found here:

https://developer.xero.com/documentation/getting-started/webhooks

like image 875
user982124 Avatar asked Nov 14 '17 12:11

user982124


1 Answers

To match the sent-in data with the validation hash in the header, you need to do the following things:

  1. Get the payload:
    $payload = file_get_contents("php://input");
  2. Generate a hash using the payload and your webhook key:
    $yourHash = base64_encode(hash_hmac('sha256', $payload, $yourWebhookKey));
  3. Check your hash against the one provided in the header:
    if ($yourHash === $_SERVER['x-xero-signature']) {}

You will have to check the $_SERVER array for the correct key if this does not work directly; it is probably all upper-case to begin with.

Edit: As noted by the OP, the correct variable is $_SERVER['HTTP_X_XERO_SIGNATURE']

like image 75
jeroen Avatar answered Oct 23 '22 16:10

jeroen