Verify Webhooks

We encrypt the body of the webhook message using the secret token you specify while creating webhook. You need the token to verify the signature you get when you receive the webhook.

Anchor uses HMAC-SHA1 to encrypt the body of the request, we send it as a signature header x-anchor-signature.

The signature is calculated by using Base64(HMAC_SHA1(requestbody,key="webhook token")).

// For Javascript:

const crypto = require('crypto');

const hash = Buffer.from(crypto.createHmac('sha1', '1234').update('{"hello": "world"}').digest('hex'),).toString('base64');

// For Java:

String secretToken= "13345";
String webhookPayload; //webhook payload received from anchor in http request
 Base64.getEncoder().encodeToString(
 new HmacUtils(HmacAlgorithms.HMAC_SHA_1,secretToken).hmacHex(webhookPayload).getBytes(StandardCharsets.UTF_8));

// For php

<?php
header('Content-Type: application/json');

$logFileName = 'anchor-webhook.log';

// Get the JSON data from the request
$jsonData = file_get_contents('php://input');

// Check if JSON data is received
if (!$jsonData)
{
    $response = array(
        'status' => 'error',
        'message' => 'No JSON data received!'
    );
    echo json_encode($response);
    return;
}

//Get webhook signature from header
$all_headers = getallheaders();
foreach ($all_headers as $name => $value)
{
    if ($name == 'x-anchor-signature')
    {
        $anchorSignature = $value;
        break;
    }
}

$secretKey = '1112'; // Secret key

// Perform HMAC-SHA1 encryption and encode to base64
$hmacSha1Hash = hash_hmac('sha1', $jsonData, $secretKey, false);

//base64 encode the hash
$base64EncodedHash = base64_encode($hmacSha1Hash);

//Check if the encoded signature matches that in the webhook request header
if ($anchorSignature != $base64EncodedHash)
{
    //disregard webhook message. It didn't originate from anchor
    $response = array(
        'status' => 'error',
        'message' => 'Invalid signature'
    );
    echo json_encode($response);
    return;
}

//Signature matches. So continue with business logic
error_log('Signatures match \n', 3, $logFileName);

$response = array(
    'status' => 'success',
    'message' => 'Webhook message received successfully!'
);
echo json_encode($response);

?>

When you get your webhook, do HMAC-SHA1 check, the result should be the same as what you have in x-anchor-signature. If is not the same, the request has been tampered with on its journey to you.