Goods & Services API documentation

Goods & Services API documentation
3. Authentication sample


Authentication to the API

1. Sample PERL client to generate HTTP headers

sub _gen_http_headers
{
    my $api_key = 'XXXXXXXXXX';
    my $api_secret = 'YYYYYYYYYY';

    use Digest::SHA qw(hmac_sha256_base64);
    my $nonce = time();
    my $hmac = hmac_sha256_base64($api_key, $nonce, $api_secret );

    #Digest::SHA does not pad base64 output
    while (length($hmac) % 4) {
        $hmac .= '=';
    }

    my $client = REST::Client->new(  );

    $client->addHeader('X-TransferTo-apikey', $api_key );
    $client->addHeader('X-TransferTo-nonce', $nonce );
    $client->addHeader('X-TransferTo-hmac', $hmac );

    return $client;
}

2. Sample PHP client to generate HTTP headers

<?php
$api_key = 'XXXXXXXXXXXX';
$api_secret = 'YYYYYYYYYYYY';
$nonce = time();
$host = 'https://gs-api.dtone.com/v1.1/';

$hmac = base64_encode(hash_hmac('sha256', $api_key.$nonce, $api_secret, true ));
echo "hmac : $hmac".PHP_EOL;

// set up the curl resource
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$host/ping");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "X-TransferTo-apikey: $api_key",
    "X-TransferTo-nonce: $nonce",
    "X-TransferTo-hmac: $hmac",
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// execute the request
$output = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// close curl resource to free up system resources
curl_close($ch);

3. Sample Ruby client to generate HTTP headers

require 'net/http'
require 'openssl'
require "base64"

apikey = 'XXXXXXXXXXXX';
apisecret = 'YYYYYYYYYYYY';
nonce = Time.now.strftime('%s').to_s

uri = URI('https://gs-api.dtone.com/v1.1/ping')


def sign( key, base_string )
  digest = OpenSSL::Digest::SHA256.new
  hmac = OpenSSL::HMAC.digest( digest, key, base_string  )
  hmac64 = Base64.encode64( hmac ).chomp.gsub( /\n/, '' )
  return hmac64
end#def

hmac = sign( apisecret, apikey + nonce )

req = Net::HTTP::Get.new(uri)
req['X-TransferTo-apikey'] = apikey
req['X-TransferTo-nonce'] = nonce
req['x-transferto-hmac'] = hmac

http = Net::HTTP.start(uri.hostname, uri.port,:use_ssl => true)
res = http.request(req)

print res.body

4. Sample Python client to generate HTTP headers

import requests
import time
import hashlib
import hmac
import base64


url = 'https://gs-api.dtone.com/v1.1/ping'
apikey = "XXXXXXXXXXXX"
apisecret = "YYYYYYYYYYYY"
nonce = int(time.time())

message = bytes(apikey + str(nonce) ).encode('utf-8')
secret = bytes(apisecret).encode('utf-8')

hmac = base64.b64encode(hmac.new(secret, message, digestmod=hashlib.sha256).digest())

headers = {}
headers['X-TransferTo-apikey'] = apikey
headers['X-TransferTo-nonce'] = nonce
headers['x-transferto-hmac'] = hmac
response = requests.get(url, headers=headers)

print response.content

5. Sample Node.js client to generate HTTP headers

var https = require('https');
var host = 'gs-api.dtone.com';
var path = '/v1.1/ping';
var apikey = "XXXXXXXXXXXX";
var apisecret = "YYYYYYYYYYYY";
var nonce = (new Date()).getTime();;
var crypto = require('crypto');
var hmac = crypto.createHmac('sha256', apisecret ).update(apikey + nonce ).digest('base64');

https.get({
        host: host,
        path: path,
        headers : {
            'X-TransferTo-apikey': apikey,
            'X-TransferTo-nonce': nonce,
            'x-transferto-hmac': hmac
        }
    }, function(response) {
        var str = '';
        response.on('data', function(d) {
            str += d;
        });
        response.on('end', function() {
            console.log( str );
        });
    });

6. Sample Scala client to generate HTTP headers

import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.HttpClientBuilder
import org.apache.http.util.EntityUtils
import org.apache.commons.codec.binary.Base64.encodeBase64
import javax.crypto.spec.SecretKeySpec
import javax.crypto.Mac

val url = "https://gs-api.dtone.com/v1.1/ping"
val apikey = "XXXXXXXXXXXX"
val apisecret = "YYYYYYYYYYYY"
val nonce = System.currentTimeMillis / 1000

val secret = new SecretKeySpec(apisecret.getBytes, "HmacSHA256")
val mac = Mac.getInstance("HmacSHA256")
mac.init(secret)

val message = apikey + nonce.toString
val hmac = mac.doFinal( message.getBytes )
val hmac_64 = new String( encodeBase64( hmac ) )

var request = new HttpGet(url);
request.addHeader("X-TransferTo-apikey", apikey)
request.addHeader("X-TransferTo-nonce", nonce.toString )
request.addHeader("X-TransferTo-hmac", hmac_64)

val client = HttpClientBuilder.create().build();
val response = client.execute(request);

println( EntityUtils.toString( response.getEntity ) )

7. Sample go client to generate HTTP headers

package main

import (
    "crypto/hmac"
    "crypto/sha256"
    "encoding/base64"
    "fmt"
    "io/ioutil"
    "net/http"
    "strconv"
    "time"
)

var url string = "https://gs-api.dtone.com/v1.1/ping"
var apikey string = "XXXXXXXXXXXX"
var secret string = "YYYYYYYYYYYY"
var nonce string = strconv.FormatInt(time.Now().Unix(), 10)

func main() {
    digest := hmac.New(sha256.New, []byte(secret))
    digest.Write([]byte(apikey + nonce))
    hmac := base64.StdEncoding.EncodeToString(digest.Sum(nil))

    request, err := http.NewRequest("GET", url, nil)
    request.Header.Add("X-TransferTo-apikey", apikey)
    request.Header.Add("X-TransferTo-nonce", nonce)
    request.Header.Add("X-TransferTo-hmac", hmac)

    client := &http.Client{}
    response, err := client.Do(request)
    if err != nil {
        fmt.Println("error:", err)
        return
    }

    content, err := ioutil.ReadAll(response.Body)
    if err != nil {
        fmt.Println("error:", err)
        return
    }
    fmt.Println(string(content))
}

8. Sample perl6 client to generate HTTP headers

use v6;
use HTTP::UserAgent;
use Digest::HMAC;
use Digest::SHA;
use Base64;

my $url = 'https://gs-api.dtone.com/v1.1/ping';
my $apikey = "XXXXXXXXXXXX";
my $apisecret = "YYYYYYYYYYYY";
my $nonce = time;

my $hmac = encode-base64(hmac($apisecret, $apikey~$nonce, &sha256), :str);
my $ua = HTTP::UserAgent.new;
my $req = HTTP::Request.new(
    :GET($url),
    :X-TransferTo-apikey($apikey),
    :X-TransferTo-nonce($nonce),
    :X-TransferTo-hmac($hmac),
);
my $res = $ua.request($req);

say $res.content;

9. Sample C# client to generate HTTP headers

using System;
using System.Security.Cryptography;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace ConsoleApplication
{
    public class Program
    {
        public static HttpRequestMessage GetHttpRequestMessage(
            string url, HttpMethod method = null, HttpContent content = null)
        {
            string api_key = "XXXXXXXXXXXX";
            string api_secret = "YYYYYYYYYY";

            int epoch = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
            string nonce = epoch.ToString();
            string message = api_key + nonce;

            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            byte [] keyByte = encoding.GetBytes( api_secret );
            HMACSHA256 hmac = new HMACSHA256(keyByte);
            byte [] messageBytes = encoding.GetBytes(message);
            byte [] hashmessage = hmac.ComputeHash(messageBytes);

            string hmac_base64 = Convert.ToBase64String(hashmessage);
            Console.WriteLine("Hash Base64 code is " + hmac_base64);
            if (method == null)
                method = HttpMethod.Get;
            HttpRequestMessage request = new HttpRequestMessage(method, url);
            request.Headers.Add("X-TransferTo-apikey", api_key);
            request.Headers.Add("X-TransferTo-nonce", nonce);
            request.Headers.Add("X-TransferTo-hmac", hmac_base64);
            if (content != null) {
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                request.Content = content;
            }
            return request;
        }
        public static async Task Ping()
        {
            using (var client = new HttpClient())
            {
                HttpRequestMessage request = GetHttpRequestMessage("https://gs-api.dtone.com/v1.1/ping");
                HttpResponseMessage response = await client.SendAsync(request);
                string result = await response.Content.ReadAsStringAsync();
                Console.WriteLine(result);
            }
        }
        public static void Main(string[] args)
        {
            Ping().Wait();
        }
    }
}