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.

# Perl API signing example.
# Copyright (c) 2014 Actual Metrics. All Rights Reserved.

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);

return $hmac->b64digest;
Was this article helpful?
0 out of 0 found this helpful


Article is closed for comments.