HMAC Auth Sample Codes

Find below different samples codes already written to make life easy for you across various languages to calculate the signature digest.

<?php

$request_type = "GET";
$endpoint = "/api/baxipay/superagent/account/balance";
$request_date = "Thu, 19 Dec 2019 17:40:26 GMT";
$user_secret = "YOUR_USER_SECRET";
$json_payload = '{ "name":"tayo" }';
$encoded_payload_hash = "";


function calculate_digest($request_type="GET", $endpoint, $request_date, $user_secret, $json_payload="")
{
    // 1. CONVERT DATE TO UNIX TIMESTAMP
    $timestamp = strtotime($request_date);
    
    if(!empty($json_payload))
    {
        // 2. DO A SHA256 OF YOUR JSON PAYLOAD (IF AVAILABLE)
        $payload_hash = hash('sha256', $json_payload, $raw_output=TRUE);
        
        // 3. ENCODE THE PAYLOAD HASH WITH BASE-64
        $encoded_payload_hash = base64_encode($payload_hash);
    }else{
        $encoded_payload_hash = ""; // NO PAYLOAD
    }
    
    // 4. CREATE A SECURITY STRING FOR THIS REQUEST
    $signed_string = $request_type.$endpoint.$timestamp.$encoded_payload_hash;
    
    // 5. DO A UTF-8 ENCODE OF THE SECURITY STRING
    $encoded_signed_string = utf8_encode($signed_string);
    
    // 6. SIGN USING HMAC-SHA1: Key = USER_SECRET, Message = ENCODED SIGNED STRING
    $hash_signature = hash_hmac("sha1", $encoded_signed_string, $user_secret, $raw_output=TRUE);

    // 7. CONVERT HASH SIGNATURE TO BASE 64
    $final_signature = base64_encode($hash_signature);
    
    return $final_signature;
}