Getting started - Heyloyalty/api GitHub Wiki

Introduction

About the API

The API uses a RESTful principle, and supports the HTTP verbs GET, POST, PUT, PATCH and DELETE for managing resources. Please note that we are using the HTTPS protocol for securing your data.

The response body is always JSON format.

Obtaining an API key

You need a Heyloyalty account, if you don't have one you can create an account.

In your account under settings -> account information, is your API key and API secret.

Authentication

When issuing calls to the API, credentials must be provided using HTTP Basic Authentication, with username being the API-key, and the password being a request signature. (see below).

Every call to the API must also contain the HTTP header X-Request-Timestamp. The value should be a RFC 1123 representation of the current date/time.from datetime import datetime import hashlib

Request signature

The request signature is generated using the API Secret and the value of the X-Request-Timestamp header. It's important that the timestamp used to generate the signature is exactly the same as that sent in the header.

Example of how to generate a request signature:

$signature = base64_encode(hash_hmac('sha256', 'Fri, 24 May 2013 13:16:26 GMT', 'API_SECRET'));

Php client

One of our developers have made a phpclient

Header generation

The example shows how the headers are generated for the API server. The code snippet does not use any external libraries, which allows it to be used as php -f script.php for rapid generation of headers.

<?php
	
define('API_KEY', 'xxxxxxxx');
define('API_SECRET', 'xxxxxxxxxxxxxxxxxx');

$requestTimestamp = gmdate("D, d M Y H:i:s") . ' GMT';
$requestSignature = base64_encode(hash_hmac('sha256', $requestTimestamp, API_SECRET));

print "\r\n";
print "--- HTTP Headers ---\r\n";
print 'X-Request-Timestamp: ' . $requestTimestamp . "\r\n";
print 'Authorization: ' . 'Basic ' . base64_encode(API_KEY .':'. $requestSignature) . "\r\n";
print "\r\n";
print "\r\n";
exit(0);

Code example

This example shows how to get members from a list in PHP. It uses the Guzzle client version 7.5. Read the Guzzle documentation here.

<?php
	
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

define('API_KEY', 'xxxxxxxxxxxxxxxxxxx');
define('API_SECRET', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx');

$client = new Client([
    'base_uri' => 'https://api.heyloyalty.com/loyalty/v1/',
]);

$requestTimestamp = gmdate("D, d M Y H:i:s") . ' GMT';
$requestSignature = base64_encode(hash_hmac('sha256', $requestTimestamp, API_SECRET));

$response = $client->get('lists/1/members', [
    'headers' => [
        'X-Request-Timestamp' => $requestTimestamp,
    ],
    'auth' => [API_KEY, $requestSignature],
    RequestOptions::HTTP_ERRORS => false, // Disable throwing exceptions on HTTP errors
]);
$jsonResponse = json_decode($response->getBody(), true);

Note about .NET (C#)

To achieve access to our API with .NET, the following is an example which can grant you access.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Threading.Tasks;

namespace HLListsClient
{

    /**
     *  Heyloyalty api example
     *  Shows in c# how to authenticate and connect to Heyloyalty api.
     *  Uses Microsoft Aspnet WebApi client.
     *  Instal Aspnet Webapi client with package manager console by 
     *  running the code below.
     *  
     *  Install-Package Microsoft.AspNet.WebApi.Client
     * 
     */
    class Program
    {
        static void Main(string[] args)
        {
            //only block calls in console never in real ui
            RunAsync().Wait();
        }
        //create an asynchronous task
        static async Task RunAsync()
        {
            /**
             * Heyloyalty user api settings
             */
            var apiKey = ""; //input your apikey found on your Heyloyalty account
            var apiSecret = ""; //input your apisecret found on your Heyloyalty account
            var apiUrl = "https://api.heyloyalty.com/loyalty/v1/";

            /**
             * Heyloyalty partner api settings
             * Change isPartner to true to use the partner api
             */
            var isPartner = false;

            var partnerApiKey = ""; //this key needs to be given to you by Heyloyalty
            var partnerApiSecret = ""; //this secert needs to be given to you by Heyloyalty
            var partnerApiUrl = "reseller/";
             
            //if partner variable is set to true, use the partner api settings
            if(isPartner)
            {
                apiKey = partnerApiKey;
                apiSecret = partnerApiSecret;
                apiUrl = partnerApiUrl;
            }

            //Generate authentication headers:
            var timeStamp = DateTime.Now.ToString("R");
            var hmacsha256 = new HMACSHA256(System.Text.Encoding.UTF8.GetBytes(apiSecret));
            hmacsha256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(timeStamp.ToString()));
            var hashstring = BitConverter.ToString(hmacsha256.Hash).Replace("-", "").ToLower();
            var requestSignature = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(hashstring));
            var authorizationString = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(apiKey + ":" + requestSignature));

            var client = new HttpClient();
            client.DefaultRequestHeaders.Add("X-Request-Timestamp", timeStamp);
            client.DefaultRequestHeaders.Add("Authorization", "Basic " + authorizationString);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            // HTTP GET
            HttpResponseMessage response = await client.GetAsync(url+"lists");
            if (response.IsSuccessStatusCode)
            {
                //Heyloyalty are returning an json array.
                ArrayList list = await response.Content.ReadAsAsync<ArrayList>();
                
                /**
                 * Here we are writing out our first object, but could handle it the way you want.
                 */
                Console.WriteLine(list[0]);
            }    
        }
    }
}

Note about Python

This is the python equivalent to the php Request signature creation shown above

from datetime import datetime    
import hashlib
import hmac
import base64

now =  datetime.now() #current time
timestamp = now.strftime("%a, %d %b %Y %H:%M:%S GMT")  #RFC 1123 format
api_key = "------------" #replace with you API key from your account
secret_key = "---------------------" #replace with API secret from your account

byte_key = bytes(secret_key, 'UTF-8')
stamp = timestamp.encode()

hmac_value = hmac.new(byte_key, stamp, hashlib.sha256).hexdigest()
hmac_value = hmac_value.encode()
encoded = base64.b64encode(hmac_value)

print('api key: ' + api_key)
print("timestamp: " + timestamp)
print("encoded: " + encoded.decode())	 

Note about NodeJS

This example shows how to get members from a list in NodeJS. It uses the built-in crypto module to generate the authentication headers.

import { createHmac } from 'crypto';

const api_key = 'API_KEY'; // replace with you API key from your account
const secret_key = 'SECRET_KEY'; // replace with API secret from your account

const requestTimestamp = new Date().toUTCString();

const requestHashed = createHmac('sha256', secret_key).update(requestTimestamp).digest('hex');
const requestSignature = Buffer.from(requestHashed).toString('base64');

const authKey = Buffer.from(api_key + ':' + requestSignature).toString('base64');

const response = await fetch(`https://api.heyloyalty.com/loyalty/v1/lists/1/members`, {
  method: 'GET',
  headers: {
    Accept: 'application/json',
    'X-Request-Timestamp': requestTimestamp,
    Authorization: `Basic ${authKey}`
  }
});
⚠️ **GitHub.com Fallback** ⚠️