Sample PHP Script: Generate Signature

Creation date: 6/12/2022 9:44 AM    Updated: 1/24/2023 11:50 AM
This code shows a PHP example of how to generate a signature for API requests. The $token, $username, and data parameter array values must be passed to the script.

 
<?php
 
# Used in creating hashes for Angelfish API requests.
$token = 'TOKEN';
 
# The Angelfish user account name.
$username = 'USERNAME';
 
# Create a hash that contains ALL parameters needed for the request.
$to_sign = array(
  'dimensions' => 'source',
  'metrics' =>; 'visits',
  'ids' =>; '1234'
);
 
# Add the Angelfish user account that's requesting the data to the request.
$to_sign['username'] = $username;
 
# Sign the data and attach the signature to the POST content
$post_request_data['signature'] = SignData($to_sign, $token);
 
# Now use $post_request_data in your request...
echo $post_request_data['signature'];
 
# Signs the given data with the specified token and returns the hash.
function SignData($data, $token) {

  # Sort the data array by key...
  ksort($data);
 
  # And then flatten it into a string to use in the signing process.
  foreach ($data as $key =>; $value) {
    $to_sign .= $key . "=" . $value;
  }
 
  # Return the hash for the flattened, stringified data with all trailing equal signs removed
  return rtrim(base64_encode(hash_hmac('md5', $to_sign, $token, true)), "=");
}
 
?>