Code samples

Java
C#
VB.NET
PHP
Ruby
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
class Main {
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException {
String secret = "Oe8TBDzg4tatdq2cL9ojeEj3U3oWSCSC5fqOHAqaKVg";
String method = "POST";
String body = "{\"amount\":\"100\"}";
String date = "2019-01-09T11:24:40+00:00";
String path = "/api/auth/test";
String contentType = "application/json";
// 5173e4d02d8a761679b0165b87d9ee5f
String bodyMD5 = body.isEmpty() ? "" : md5hex(body);
// POST\n5173e4d02d8a761679b0165b87d9ee5f\napplication/json\n2019-01-09T11:24:40+00:00\n/api/auth/test
String stringToSign = String.join("\n", method, bodyMD5, contentType, date, path);
// fVYzUdYqZO1ozBeP3KQHFp9/Kno=
String signature = hmac(stringToSign, secret);
System.out.println(signature);
}
private static String md5hex(String str) throws NoSuchAlgorithmException {
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] bytes = md5.digest(str.getBytes(StandardCharsets.UTF_8));
return hex(bytes);
}
private static String hmac(String str, String secret) throws InvalidKeyException, NoSuchAlgorithmException {
SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(secretKey);
byte[] result = mac.doFinal(str.getBytes(StandardCharsets.UTF_8));
String base64 = Base64.getEncoder().encodeToString(result);
return base64;
}
private static String hex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
class Test {
public static int Main() {
APIAuth auth = new APIAuth("key", "secret");
APIClient client = new APIClient("https://business-sandbox.cryptopay.me", auth);
string path = "/api/invoices";
string data = "{"price_amount":"100","price_currency":"EUR","pay_currency":"BTC"}";
string response = client.DoRequest(DateTime.Now, path, data);
Console.WriteLine(response);
return 0;
}
}
class APIClient {
private string baseURL;
private APIAuth auth;
public APIClient(string url, APIAuth apiAuth)
{
baseURL = url;
auth = apiAuth;
}
public string DoRequest(DateTime date, string path, string data = "", string contentType = "application/json", List<KeyValuePair<string, string>> Headers = null, string verb = "POST")
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseURL + path);
HttpWebResponse response;
StreamWriter sw;
StreamReader sr;
string dateStr;
string responseData;
request.Method = verb;
request.ContentType = contentType;
request.ContentLength = data.Length;
request.Date = date;
dateStr = date.ToUniversalTime().ToString("r");
request.Headers.Add("Authorization", auth.GenerateAuthorizationHeader(verb, data, contentType, dateStr, path));
sw = new StreamWriter(request.GetRequestStream());
sw.Write(data);
sw.Close();
response = (HttpWebResponse)request.GetResponse();
sr = new StreamReader(response.GetResponseStream());
responseData = sr.ReadToEnd();
return (responseData);
}
}
class APIAuth {
private string key;
private string secret;
public APIAuth(string apikey, string apisecret)
{
key = apikey;
secret = apisecret;
}
public string GenerateAuthorizationHeader(string httpVerb, string jsonBodyStr, string httpContentType, string dateStr, string relativeUrl)
{
string signature = GenerateSigniture(httpVerb, jsonBodyStr, httpContentType, dateStr, relativeUrl);
return $"HMAC {key}:{signature}";
}
public string GenerateSigniture(string httpVerb, string jsonBodyStr, string httpContentType, string dateStr, string relativeUrl) {
string jsonBodyHash = GetMD5Hash(jsonBodyStr);
string signitureData = string.Join("\n", httpVerb, jsonBodyHash, httpContentType, dateStr, relativeUrl);
byte[] apiSecretBytes = Encoding.UTF8.GetBytes(secret);
byte[] signitureBytes = Encoding.UTF8.GetBytes(signitureData);
var hmacsha1 = new HMACSHA1(apiSecretBytes, false);
byte[] resultBytes = hmacsha1.ComputeHash(signitureBytes);
return Convert.ToBase64String(resultBytes);
}
private string GetMD5Hash(string text) {
StringBuilder returnvalue = new StringBuilder();
MD5CryptoServiceProvider cryptoSP = new MD5CryptoServiceProvider();
byte[] HashBytes = Encoding.UTF8.GetBytes(text);
HashBytes = cryptoSP.ComputeHash(HashBytes);
foreach(byte bte in HashBytes)
returnvalue.Append(bte.ToString("x2").ToLower());
return returnvalue.ToString();
}
}
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Net
Imports System.Security.Cryptography
Imports System.Text
Class Test
Public Shared Function Main() As Integer
Dim auth As APIAuth = New APIAuth("key", "secret")
Dim client As APIClient = New APIClient("https://business-sandbox.cryptopay.me", auth)
Dim path As String = "/api/invoices"
Dim data As String = "{""price_amount"":""0.5"",""price_currency"":""ETH"",""pay_currency"":""ETH""}"
Dim response As String = client.DoRequest(DateTime.Now, path, data)
Console.WriteLine(response)
Return 0
End Function
End Class
Class APIClient
Private baseURL As String
Private auth As APIAuth
Public Sub New(ByVal url As String, ByVal apiAuth As APIAuth)
baseURL = url
auth = apiAuth
End Sub
Public Function DoRequest(ByVal date As DateTime, ByVal path As String, ByVal Optional data As String = "", ByVal Optional contentType As String = "application/json", ByVal Optional Headers As List(Of KeyValuePair(Of String, String)) = Nothing, ByVal Optional verb As String = "POST") As String
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Dim request As HttpWebRequest = CType(WebRequest.Create(baseURL & path), HttpWebRequest)
Dim response As HttpWebResponse
Dim sw As StreamWriter
Dim sr As StreamReader
Dim dateStr As String
Dim responseData As String
request.Method = verb
request.ContentType = contentType
request.ContentLength = data.Length
request.Date = date
dateStr = date.ToUniversalTime().ToString("r")
request.Headers.Add("Authorization", auth.GenerateAuthorizationHeader(verb, data, contentType, dateStr, path))
sw = New StreamWriter(request.GetRequestStream())
sw.Write(data)
sw.Close()
response = CType(request.GetResponse(), HttpWebResponse)
sr = New StreamReader(response.GetResponseStream())
responseData = sr.ReadToEnd()
Return (responseData)
End Function
End Class
Class APIAuth
Private key As String
Private secret As String
Public Sub New(ByVal apikey As String, ByVal apisecret As String)
key = apikey
secret = apisecret
End Sub
Public Function GenerateAuthorizationHeader(ByVal httpVerb As String, ByVal jsonBodyStr As String, ByVal httpContentType As String, ByVal dateStr As String, ByVal relativeUrl As String) As String
Dim signature As String = GenerateSigniture(httpVerb, jsonBodyStr, httpContentType, dateStr, relativeUrl)
Return $"HMAC {key}:{signature}"
End Function
Public Function GenerateSigniture(ByVal httpVerb As String, ByVal jsonBodyStr As String, ByVal httpContentType As String, ByVal dateStr As String, ByVal relativeUrl As String) As String
Dim jsonBodyHash As String = GetMD5Hash(jsonBodyStr)
Dim signitureData As String = String.Join(vbLf, httpVerb, jsonBodyHash, httpContentType, dateStr, relativeUrl)
Dim apiSecretBytes As Byte() = Encoding.UTF8.GetBytes(secret)
Dim signitureBytes As Byte() = Encoding.UTF8.GetBytes(signitureData)
Dim hmacsha1 = New HMACSHA1(apiSecretBytes, False)
Dim resultBytes As Byte() = hmacsha1.ComputeHash(signitureBytes)
Return Convert.ToBase64String(resultBytes)
End Function
Private Function GetMD5Hash(ByVal text As String) As String
Dim returnvalue As StringBuilder = New StringBuilder()
Dim cryptoSP As MD5CryptoServiceProvider = New MD5CryptoServiceProvider()
Dim HashBytes As Byte() = Encoding.UTF8.GetBytes(text)
HashBytes = cryptoSP.ComputeHash(HashBytes)
For Each bte As Byte In HashBytes
returnvalue.Append(bte.ToString("x2").ToLower())
Next
Return returnvalue.ToString()
End Function
End Class
<?php
namespace Cryptopay;
class Authentication
{
private $apiKey;
private $apiSecret;
public function __construct($apiKey, $apiSecret) {
$this->apiKey = $apiKey;
$this->apiSecret= $apiSecret;
}
public function buildRequestHeaders($method, $path, $body, $headers) {
if ($body) {
$bodyHash = md5($body);
} else {
$bodyHash = '';
}
$date = $headers['Date'];
$contentType = $headers['Content-Type'];
$sigString = implode("\n", [$method, $bodyHash, $contentType, $date, $path]);
$signature = base64_encode(hash_hmac('sha1', $sigString, $this->apiSecret, true));
return [
'Authorization' => 'HMAC '.$this->apiKey.':'.$signature
];
}
}
api_key = 'DjlHuWlApznJ7vrhPBL0fA'
api_secret = '3pPl6TbsoRlz0FLpKM6r-UG788g4-Fk5d1v1gKdXAA8'
string_to_signature = [
'POST',
'ba3c4838768171e3a221a9d619f5440c',
'application/json',
'Tue, 25 Sep 2018 17:41:40 GMT',
'/api/invoices'
].join("\n")
digest = OpenSSL::Digest.new('sha1')
signature = OpenSSL::HMAC.digest(digest, api_secret, string_to_signature)
encoded_signature = Base64.strict_encode64(signature)