Authenticating on the API

Most interaction with the BVNK Payments API requires the use of the API keys you generated in the previous step.

If you've not already created your Hawk Auth ID and Hawk Auth Key you can go back to the previous step to retrieve these, as you won't be able to progress without them.

HAWK Authentication

It is best to read the guides available on the HAWK read me. The BVNK API uses SHA256 for calculating the HMAC.

HAWK optionally supports payload validation (POST/PUT data payload) as well as response payload validation, these are not enabled on the BVNK API so can be ignored.

Examples

private String getAuthorizationHeader(String requestUrl, String method) {
    // method can be POST, GET, DELETE, PUT

// time must be accurate
long timestamp = Math.round(System.currentTimeMillis() / 1000);

// this is a random unique string (duplicates within 15 minutes will be rejected)
String nonce = UUID.randomUUID().toString().substring(0, 8);

URI uri = new URI(requestUrl);
String path = uri.getPath(); // eg: /api/v1/pay
String query = uri.getRawQuery(); // x=y
String host = uri.getHost(); // host of the request URL
int port = uri.getPort() == -1 ? 443 : uri.getPort(); // Port 443 default for HTTPS

StringBuilder hawkHeader = new StringBuilder();
hawkHeader.append("hawk.1.header\n");
hawkHeader.append(timestamp);
hawkHeader.append("\n");
hawkHeader.append(nonce);
hawkHeader.append("\n");
hawkHeader.append(method);
hawkHeader.append("\n");
hawkHeader.append(path);
if (query != null) {
    hawkHeader.append("?");
    hawkHeader.append(query);
}
hawkHeader.append("\n");
hawkHeader.append(host);
hawkHeader.append("\n");
hawkHeader.append(port);
hawkHeader.append("\n");
// body
hawkHeader.append("\n");
// app data
hawkHeader.append("\n");

try {
    String mac = generateHash(hawkAuth.getApiSecret(), hawkHeader.toString());
    String authorization = "Hawk id=\"" + hawkAuth.getApiKey() + "\", ts=\"" + timestamp + "\", nonce=\"" + nonce + "\", mac=\"" + mac + "\"";

    // Now use 'authorization' variable as Authorization header in your request.

    return authorization;
} catch(Exception e) {
    throw new IOException(e);
}
}
private String generateHash(String key, String data) throws InvalidKeyException, NoSuchAlgorithmException {
    Mac sha256_HMAC = null;
    String result = null;
    byte[] byteKey = key.getBytes(StandardCharsets.UTF_8);

    final String HMAC_SHA256 = "HmacSHA256";
    sha256_HMAC = Mac.getInstance(HMAC_SHA256);

    SecretKeySpec keySpec = new SecretKeySpec(byteKey, HMAC_SHA256);
    sha256_HMAC.init(keySpec);
    byte[] mac_data = sha256_HMAC.doFinal(data.getBytes());

    return Base64.getEncoder().encodeToString(mac_data);
}
//Function to fetch the current system in ms. Important for the header generation !!!
        private static readonly DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        public static long CurrentTimeMillisecs()
        {
            return (long)(DateTime.UtcNow - Jan1st1970).TotalMilliseconds;
        }

//GET AUTHORIZATION STRING
        string getAuthorizationHeader(String requestUrl, String method)
        {
            Uri requestUri = new Uri(requestUrl);
            //PREPARE HEADER  
            //TIMESTAMP MUST BE /1000
            string timestamp = (CurrentTimeMillisecs()/1000).ToString();
                    //NONCE
            string nonce = Guid.NewGuid().ToString().Substring(0, 8);
                    //URI PATH
            string path = "/api/v1/pay/summary";
                    // URI HOST
            string host = "api.sandbox.bvnk.com";
                    // URI PORT
            string port = "443";

            StringBuilder hawkHeader = new StringBuilder();
            hawkHeader.Append("hawk.1.header\n");
            hawkHeader.Append(timestamp);
            hawkHeader.Append("\n");
            hawkHeader.Append(nonce);
            hawkHeader.Append("\n");
            hawkHeader.Append(method);
            hawkHeader.Append("\n");
            hawkHeader.Append(path);
            hawkHeader.Append("\n");
            hawkHeader.Append(host);
            hawkHeader.Append("\n");
            hawkHeader.Append(port);
            hawkHeader.Append("\n");
            // body
            hawkHeader.Append("\n");
            // app data
            hawkHeader.Append("\n");


            try {
                string apiKey = "YOUR HAWK AUTH KEY";
                string mac = hashFunction(apiKey, hawkHeader.ToString());
                string authorization =
                    "Hawk id=\"" + "YOUR HAWK ID"
                    + "\", ts=\"" + timestamp
                    + "\", nonce=\"" + nonce
                    + "\", mac=\"" + mac
                    + "\"";

                return authorization;

            }catch (Exception e){

                throw new IOException(e.ToString());
            }
            
        }
//HASH FUNCTION TO GENERATE MAC
//key = hawk auth key
//data = the concatenated header value returned by the header creation function 

        String hashFunction(String key, String data)
        {           
            byte[] secretKey = Encoding.UTF8.GetBytes(key);
            HMACSHA256 hmac = new HMACSHA256(secretKey);
            hmac.Initialize();
            byte[] bytes = Encoding.UTF8.GetBytes(data);
            byte[] rawHmac = hmac.ComputeHash(bytes);

            return Convert.ToBase64String(rawHmac);
        }
//REMEMBER TO IMPORT THE HAWK LIBRARY AND REFERENCE IT 
//PROPERLY IN THE DIRECTORY OF YOUR PROJECT ---> https://github.com/mozilla/hawk 
const Hawk = require('../lib');

//GET TIMESTAMP HELPER FUNCTION
function getTimestampInSeconds () {
    return Math.floor(Date.now() / 1000)
  }

//GENERATE RANDOM NONCE HELPER FUNCTION
var generateNonce = function(length) {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for(var i = 0; i < length; i++) {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    }
    return text;
}

//CREATE CREDENTIALS OBJECT
// id - YOUR HAWK AUTHENTICATION ID
// key - YOUR HAWK AUTHENTICATION KEY
// algorithm - ALWAYS SET VALUE TO sha256
// timestamp - USE getTimeStampInSeconds() HELPER FUNCTION TO ALWAYS GENERATE CURRENT TIMESTAMP
// nonce - USE generateNonce() HELPER FUNCTION TO ALWAYS GENERATE A DIFFERENT RANDOM NONCE
const credentials = {
    id: '0Wov5l4DCGUPBRNyJd2zbf03WLdoJ4fygreHVX1iuSGLIlfn8uH5S9QhR7OrF7id',
    key: 'ydk12BsV6Sa3EeVW82hDJoheivW8nMbPxfsP9OS8ADIG0CshRLJF3nTKwYyQZop6',
    algorithm: 'sha256',
    timestamp: getTimestampInSeconds(), 
    nonce: generateNonce(6)
};

//GENERATE THE HEADER AND RETURN THE VALUE
function generateHeader(){
const { header } = Hawk.client.header('https://api.sandbox.bvnk.com/api/v1/pay/summary', 'POST', {credentials});
return header
}
<?php

//Function to generate a random 6 char nonce for the header creation
function generateNonce($length = 6){
    $chars='1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM';
    $char_len = strlen($chars)-1;
    $output = '';
    while (strlen($output) < $length) {
        $output .= $chars[ rand(0, $char_len) ];
    }
    return $output;
}

//Function to generate the MAC signature 
function generateSignature($string, $key) {
    return base64_encode(
        hash_hmac(
            "sha256",
            $string,
            $key,
            true
        )
    );
}

//Function to generate the final Authorization header
function generateHeader(){
//HAWK Authentication ID
$authId = "0Wov5l4DCGUPBRNyJd2zbf03WLdoJ4fygreHVX1iuSGLIlfn8uH5S9QhR7OrF7id";
//Current time in ms
$xdate = time();
//HAWK Authentication Key
$authKey = "ydk12BsV6Sa3EeVW82hDJoheivW8nMbPxfsP9OS8ADIG0CshRLJF3nTKwYyQZop6";
//Nonce
$nonce = generateNonce();  

//Build the header
$hawkHeader = "hawk.1.header"."\n";
$hawkHeader .= $xdate;
$hawkHeader .= "\n";
$hawkHeader .= $nonce;
$hawkHeader .= "\n";
$hawkHeader .= "POST";
$hawkHeader .= "\n";
$hawkHeader .= "/api/v1/pay/summary";
$hawkHeader .= "\n";
$hawkHeader .= "api.sandbox.bvnk.com";
$hawkHeader .= "\n";
$hawkHeader .= "443";
$hawkHeader .= "\n";
$hawkHeader .= "\n";
$hawkHeader .= "\n";

//Generate the MAC
$signature = generateSignature($hawkHeader, $authKey);

//Build the final Authorization header
$header = "Hawk id=\"" .$authId."\"".","
    ." ts=\"".$xdate."\"".","
    ." nonce=\"".$nonce."\"".","
    ." mac=\"".$signature."\"";

return $header;
  
}
?>

What’s Next