Sample Perl Script: Generate Signature

This code shows an example of how to generate a signature for API requests.  The $token, $username, and data parameter array values must be passed to the script.

#!/usr/bin/perl
#
# Perl API signing example.
 
use strict;
use warnings;
use Digest::HMAC_MD5;
 
my $username = 'USERNAME';
my $token = 'TOKEN';
 
# Create a hash of all parameters that will be sent as POST content
my %post_request_data = (
  dimensions => 'source',
  metrics    => 'visits',
  ids        => '1234',
  username => $username
);

# Sign the data and attach the signature to the POST content
$post_request_data{signature} = SignData(\%post_request_data, $token);
 
# Signs the given data with the specified token
sub SignData {
  my ($data, $token) = @_;
  return 0 unless ($data and ref $data eq 'HASH' and $token);
 
  # Extract and sort the data keys
  my @keys = sort(keys %{$data});
 
  # Concatenate everything
  my $to_sign = '';
  foreach my $key (@keys) {
    $to_sign .= "$key=$data->{$key}";
  }
 
  my $hmac = Digest::HMAC_MD5->new($token);
  $hmac->add($to_sign);
 
  return $hmac->b64digest;
}
Creation date: 6/12/2022 9:42 AM      Updated: 6/14/2022 4:59 PM