Integration Examples
Python
import base64
import hashlib
import hmac
import json
import time
import requests
api_key = '' # put here your public key
secret_key = '' # put here your secret key
request = '/api/v1/invoices/create' # put here request path. For obtaining trading balance use: /api/v1/invoices/create
baseUrl = 'https://sitex.com' # domain without last slash. Do not use https://sitex.com/
# If the nonce is similar to or lower than the previous request number, you will receive the 'too many requests' error message
nonce = 1000 # nonce is a number (preferrably epoch time in milliseconds) that is always higher than the previous request number
merchantId = '' # put here your merchant ID
data = {
'amount': 10,
'currency': "USD",
'merchantId': merchantId,
'request': request,
'nonce': nonce
}
# preparing request URL
completeUrl = baseUrl + request
data_json = json.dumps(data, separators=(',', ':')) # use separators param for deleting spaces
payload = base64.b64encode(data_json.encode('ascii'))
signature = hmac.new(secret_key.encode('ascii'), payload, hashlib.sha512).hexdigest()
# preparing headers
headers = {
'Content-type': 'application/json',
'X-EX-APIKEY': api_key,
'X-EX-PAYLOAD': payload,
'X-EX-SIGNATURE': signature,
}
# sending request
resp = requests.post(completeUrl, headers=headers, data=data_json)
# receiving data
print(json.dumps(resp.json(), sort_keys=True, indent=4))PHP
<?php
$apiKey = ''; //put here your api key
$apiSecret = ''; //put here your secret key
$merchantId = ''; //put here your merchant ID
$request = '/api/v1/invoices/create'; //put here request path
$baseUrl = 'https://sitex.com';
$data = [
'amount' => '10',
'currency' => 'USD',
'merchantId' => $merchantId,
'title' => 'test',
'description' => 'test'
];
//preparing request URL
$completeUrl = $baseUrl . $request;
$dataJsonStr = json_encode($data, JSON_UNESCAPED_SLASHES);
$payload = base64_encode($dataJsonStr);
$signature = hash_hmac('sha512', $payload, $apiSecret);
//preparing headers
$headers = [
'Content-type: application/json',
'X-EX-APIKEY:'.$apiKey,
'X-EX-PAYLOAD:'.$payload,
'X-EX-SIGNATURE:'.$signature
];
$connect = curl_init($completeUrl);
curl_setopt($connect, CURLOPT_POSTFIELDS, $dataJsonStr);
curl_setopt($connect, CURLOPT_HTTPHEADER, $headers);
curl_setopt($connect, CURLOPT_RETURNTRANSFER, true);
$apiResponse = curl_exec($connect);
curl_close($connect);
//receiving data
$jsonArrayResponse = json_decode($apiResponse);
var_dump($jsonArrayResponse);NodeJS
let crypto = require('crypto');
let https = require('https');
let apiKey = ''; //put here your api key
let apiSecret = ''; //put here your secret key
let merchantId = ''; //put here your merchant ID
let request = '/api/v1/invoices/create'; //put here request path
let hostname = 'https://sitex.com';
let data = {
amount: "10",
currency: "USD",
merchantId: merchantId,
title: "title",
description: "description"
}
let dataJsonStr = JSON.stringify(data);
let payload = Buffer.from(dataJsonStr).toString('base64');
let hash = crypto.createHmac('sha512', apiSecret);
let signature = hash.update(payload).digest('hex');
let options = {
hostname: hostname,
path: request,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-EX-APIKEY': apiKey,
'X-EX-PAYLOAD': payload,
'X-EX-SIGNATURE': signature
}
}
const req = https.request(options, res => {
res.setEncoding('utf8')
console.log(`statusCode: ${res.statusCode}`)
let responseBody = '';
res.on('data', chunk => {
responseBody += chunk;
});
res.on('end', () => {
if (res.statusCode !== 200) {
console.error("Api call failed with response code", res.statusCode);
}
console.log('Body:', responseBody);
});
})
req.on('error', error => {
console.error("Request error", error);
})
req.write(dataJsonStr);
req.end();Go
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha512"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strconv"
"time"
)
type apiHelper struct {
PublicKey string
SecretKey string
BaseURL string
}
func (api *apiHelper) SendRequest(requestURL string, data map[string]interface{}) (responseBody []byte, err error) {
//If the nonce is similar to or lower than the previous request number, you will receive the 'too many requests' error message
nonce := int(time.Now().Unix()) //nonce is a number that is always higher than the previous request number
data["request"] = requestURL
data["nonce"] = strconv.Itoa(nonce)
data["nonceWindow"] = true //boolean, enable nonce validation in time range of current time +/- 5s, also check if nonce value is unique
requestBody, err := json.Marshal(data)
if err != nil {
return
}
//preparing request URL
completeURL := api.BaseURL + requestURL
//calculating payload
payload := base64.StdEncoding.EncodeToString(requestBody)
//calculating signature using sha512
h := hmac.New(sha512.New, []byte(api.SecretKey))
h.Write([]byte(payload))
signature := fmt.Sprintf("%x", h.Sum(nil))
client := http.Client{}
request, err := http.NewRequest("POST", completeURL, bytes.NewBuffer(requestBody))
if err != nil {
log.Fatal(err)
}
//setting neccessarry headers
request.Header.Set("Content-type", "application/json")
request.Header.Set("X-EX-APIKEY", api.PublicKey)
request.Header.Set("X-EX-PAYLOAD", payload)
request.Header.Set("X-EX-SIGNATURE", signature)
//sending request
response, err := client.Do(request)
if err != nil {
return
}
defer response.Body.Close()
//reciving data
responseBody, err = ioutil.ReadAll(response.Body)
return
}
func main() {
provider := apiHelper{
PublicKey: "", //put here your public key
SecretKey: "", //put here your secret key
BaseURL: "https://sitex.com", //domain without last slash. Do not use https://sitex.com/
}
//put here request path. For obtaining trading balance use: /api/v1/invoices/create
request := "/api/v1/invoices/create"
//put here data to send
data := map[string]interface{}{
"ticker": "BTC", //for example for obtaining trading balance for BTC currency
}
resultData, err := provider.SendRequest(request, data)
if err != nil {
log.Fatal(err)
}
var result interface{}
if err := json.Unmarshal(resultData, &result); err != nil {
log.Fatal(err)
}
//printing response body to default output
log.Println(result)
}Java
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Formatter;
public class ApiQuickStart {
private static final String URL = "https://sitex.com"; //API Domain URL
private static final String METHOD = "/api/v1/balances"; //TODO: Change to the required method
private static final String SECRET_KEY = "12345eXaMpLeOnlY"; //TODO: Change to yours secret-key
private static final String API_KEY = "12345eXaMpLeOnlY"; //TODO: Change to yours api-key
private static final String JSON_REQUEST_METHOD_BODY = ""; // TODO: required JSON for request method.
// String is Empty if method does not need any parameter
private static final long NONCE_ATTRIBUTE = System.currentTimeMillis();
//Whole JSON request body:
// "request" attribute contains json body specific to yours request.
// "nonce" attribute is a number that is always higher than the previous request number
private static final String REQUEST_BODY = String.format("{\"request\":\"%1$s\",\"nonce\":\"%2$s\"}", JSON_REQUEST_METHOD_BODY, NONCE_ATTRIBUTE);
public static void main(String[] args) throws Exception {
String payload = Base64.getEncoder().encodeToString(REQUEST_BODY.getBytes());
String signature = calcSignature(payload);
// I am using the standard HttpClient (You should use your favorite HTTP client library)
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(URL + METHOD))
.header("Content-type", "application/json")
.header("X-EX-APIKEY", API_KEY)
.header("X-EX-PAYLOAD", payload)
.header("X-EX-SIGNATURE", signature)
.POST(HttpRequest.BodyPublishers.ofString(REQUEST_BODY))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
private static String calcSignature(String data)
throws NoSuchAlgorithmException, InvalidKeyException {
final String HMAC_SHA512 = "HmacSHA512";
SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_KEY.getBytes(), HMAC_SHA512);
Mac mac = Mac.getInstance(HMAC_SHA512);
mac.init(secretKeySpec);
byte[] bytes = mac.doFinal(data.getBytes());
Formatter formatter = new Formatter();
for (byte b : bytes) {
formatter.format("%02x", b);
}
return formatter.toString();
}
}Kotlin
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
private const val API_KEY = "" //TODO: put here your public key
private const val API_SECRET = "" //TODO: put here your secret key
private const val URL = "https://sitex.com" // Domain
private const val BALANCE_METHOD = "/api/v1/invoices/create" // Method
fun main() {
val ticker = "BTC" // I want to get the balance for the BTC ticker
val nonce = System.currentTimeMillis() // nonce is a number that is always higher than the previous request number
// Create Json object (You should use your favorite Json de-serialization library)
val dataJson = "{\"request\":\"$BALANCE_METHOD\",\"ticker\":\"$ticker\",\"nonce\":\"$nonce\",\"nonceWindow\":true}";
// Payload and signature
val payload = Base64.getEncoder().encodeToString(dataJson.toByteArray())
val signature = calcSignature(payload)
// I am using the standard HttpClient (You should use your favorite HTTP client library)
val client = HttpClient.newHttpClient()
val request = HttpRequest.newBuilder()
.uri(URI.create(URL + BALANCE_METHOD))
.header("Content-type", "application/json")
.header("X-EX-APIKEY", API_KEY)
.header("X-EX-PAYLOAD", payload)
.header("X-EX-SIGNATURE", signature)
.POST(HttpRequest.BodyPublishers.ofString(dataJson))
.build()
val response = client.send(request, HttpResponse.BodyHandlers.ofString())
println(response.body())
}
private fun calcSignature(data: String): String? {
val HMAC_SHA512 = "HmacSHA512"
val secretKeySpec = SecretKeySpec(API_SECRET.toByteArray(), HMAC_SHA512)
val mac = Mac.getInstance(HMAC_SHA512)
mac.init(secretKeySpec)
val bytes = mac.doFinal(data.toByteArray())
val formatter = Formatter()
for (b in bytes) {
formatter.format("%02x", b)
}
return formatter.toString()
}Last updated