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

Did this page help you?