Coding Notes

Authorize.Net PHP Webhook Signature Key Check

To help prevent abuse from unwanted requests here’s a sample code for checking the signature key of a webhook from the payment gateway service provider Authorize.Net. The code grabs the “HTTP_X_ANET_SIGNATURE” key from the HTTP header and uses hash_hmac to generate the signature and hash_equals to compare the signatures.

The $secret signature key can be obtained in the Authorize.Net Merchant Interface, at Account > Settings > Security Settings > General Security Settings > API Credentials and Keys.

<?php

$secret = 'Signature Key';

if (isset($_SERVER['HTTP_X_ANET_SIGNATURE'])) {
    $json = file_get_contents('php://input');
    
    if ($json !== false) {
        if (hash_equals(strtolower($_SERVER['HTTP_X_ANET_SIGNATURE']), 
            'sha512=' . hash_hmac('sha512', $json, $secret))
        ) {
            $data = json_decode($json, false);
            
            // Authorize.Net Event Type
            if ($data->eventType == 'net.authorize.customer.paymentProfile.updated') {
                $customerProfileId = $data->payload->customerProfileId;
                // Customer payment profile updated
                // Do something.
                echo $customerProfileId;
            }
        }
    }
}

You can find more webhook event types at https://developer.authorize.net/

1 thought on “Authorize.Net PHP Webhook Signature Key Check”

  1. authorization is always failed from the webhook event notification. Using the webhook inbox test webhook, it works. don’t know what all thins to be included
    This is my code
    if (isset($this->header[‘x-anet-signature’])) {
    $json = Json::encode($this->body);

    if ($json) {
    //To check the header and signature is true
    if (hash_equals(strtolower($this->header[‘x-anet-signature’]),
    ‘sha512=’ . hash_hmac(‘sha512′,$json, $secret))
    ) {
    //Code
    }else{
    yii::info($json,’webhookhNotifications’);
    throw new \yii\web\ServerErrorHttpException(‘Authentication failed in Webhook’);
    return false;

    }
    }
    }

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.