{"templateId":"markdown","sharedDataIds":{"sidebar":"sidebar-products/legacy-api/sidebars.yaml"},"props":{"metadata":{"markdoc":{"tagList":[]},"type":"markdown"},"seo":{"title":"Sample Code","description":"Official Banxa API documentation – on-ramp and off-ramp transfers with identity verification and compliance.","llmstxt":{"hide":false,"sections":[{"title":"Table of contents","includeFiles":["**/*"],"excludeFiles":[]}],"excludeFiles":[]}},"dynamicMarkdocComponents":[],"compilationErrors":[],"ast":{"$$mdtype":"Tag","name":"article","attributes":{},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["When testing the authentication first try with a simple GET request such as Get Crypto Currencies or Get Payment Methods."]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":2,"id":"sample-code","__idx":0},"children":["Sample Code"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Here is some sample code around how to call the API including HMAC authentication. Key things to note when building your integration:"]},{"$$mdtype":"Tag","name":"ul","attributes":{},"children":[{"$$mdtype":"Tag","name":"li","attributes":{},"children":["The data passed to the HMAC algorithm are separated by new lines"]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":["The JSON payload for POST requests should contain no whitespace"]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":["The nonce should be a unix timestamp which is generated for every request"]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":["When generating the data for the HMAC algorithm include the query string"]}]},{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"javascript","header":{"controls":{"copy":{}}},"source":"function generateHmac(data, nonce) {\n   ...\n}\n\nfunction sendGetRequest(query) {\nconst hostname = 'api.banxa-sandbox.com';\nconst nonce = Date.now();\nconst method = 'GET'\nlet data = method + \"\\n\" + query + \"\\n\" + nonce;\n\nconst hmac = generateHmac(data, nonce);\nconst https = require('https')\nconst options = {\n    hostname: hostname,\n    path: query,\n    method: method,\n    headers: {\n        'Content-Type': 'application/json',\n        'Authorization': `Bearer ${hmac}`\n    }\n}\n\nconst req = https.get(options, (res) => {\n    console.log(`STATUS: ${res.statusCode}`);\n    console.log(`HEADERS: ${JSON.stringify(res.headers)}`);\n    res.setEncoding('utf8');\n    res.on('data', (chunk) => {\n      console.log(`BODY: ${chunk}`);\n    });\n    res.on('end', () => {\n      console.log('No more data in response.');\n    });\n  });\n  \n  req.on('error', (e) => {\n    console.error(`problem with request: ${e.message}`);\n  });\n}\n","lang":"javascript"},"children":[]},{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"python","header":{"controls":{"copy":{}}},"source":"import requests\nimport time\nimport hmac\n\nurl = 'https://api.banxa-sandbox.com'\nkey = '[YOUR_MERCHANT_KEY]'\nsecret = b'[YOUR_MERCHANT_SECRET]'\n\ndef generateHmac(payload, nonce):\n    hmacCode = hmac.digest(secret, payload.encode('utf8'), 'SHA256')\n\n    print(payload)\n    print(hmacCode.hex())\n\n    return key + ':' + hmacCode.hex() + ':' + str(nonce)\n\ndef sendGetRequest(query):\n    nonce = int(time.time())\n\n    data = 'GET\\n' + query + '\\n' + str(nonce)\n\n    authHeader = generateHmac(data, nonce)\n\n    response = requests.get(url + query,\n        headers = {\n                'Authorization': 'Bearer ' + authHeader,\n                'Content-Type': 'application/json'\n        })\n\n    print(response.content)\n\ndef sendPostRequest(query, payload):\n    nonce = int(time.time())\n\n    data = 'POST\\n' + query + '\\n' + str(nonce) + '\\n' + payload\n\n    authHeader = generateHmac(data, nonce)\n\n    response = requests.post(url + query,\n        data = payload,\n        headers = {\n                'Authorization': 'Bearer ' + authHeader,\n                'Content-Type': 'application/json'\n        })\n\n    print(response.content)\n\nsendGetRequest('/api/fiats')\n\nprint('----')\n\nsendPostRequest('/api/orders', '{\"account_reference\":\"test01\",\"source\":\"USD\",\"target\":\"BTC\",\"source_amount\":\"100\",\"return_url_on_success\":\"test.com\",\"wallet_address\":\"[VALID_WALLET_ADDRESS]\"}')\n","lang":"python"},"children":[]},{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"java","header":{"controls":{"copy":{}}},"source":"package com.banxa;\n\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\nimport java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\nimport java.util.Formatter;\n\npublic class BanxaService {\n    private static final String BANXA_URL = \"https://api.banxa-sandbox.com\";\n    private static final String KEY = \"[YOUR_MERCHANT_KEY]\";\n    private static final String SECRET = \"[YOUR_MERCHANT_SECRET]\";\n\n    public static void main(String[] args) throws Exception {\n        BanxaService banxaService = new BanxaService();\n        banxaService.sendGetRequest(\"/api/coins\");\n\n        banxaService.sendPostRequest(\"/api/orders\", \"{\" +\n                \"\\\"account_reference\\\":\\\"test01\\\",\" +\n                \"\\\"source\\\":\\\"USD\\\",\" +\n                \"\\\"target\\\":\\\"BTC\\\",\" +\n                \"\\\"source_amount\\\":\\\"100\\\",\" +\n                \"\\\"return_url_on_success\\\":\\\"test.com\\\",\" +\n                \"\\\"wallet_address\\\":\\\"[VALID_WALLET_ADDRESS]\\\"\"+\n                \"}\");\n    }\n\n    private void sendGetRequest(String query) throws Exception {\n        String hmac = getHmac(\"GET\", query, null);\n\n        HttpClient httpClient = HttpClient.newHttpClient();\n        HttpRequest request = HttpRequest.newBuilder()\n                .uri(URI.create(\"https://api.banxa-dev.com\" + query))\n                .timeout(Duration.ofSeconds(10))\n                .header(\"Authorization\", \"Bearer \" + hmac)\n                .header(\"content-type\", \"application/json\")\n                .GET()\n                .build();\n\n        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());\n\n        if (response.statusCode() == 200) {\n            System.out.println(\"OK\");\n        } else {\n            System.out.println(\"Failed: \" + response.statusCode());\n        }\n    }\n\n    private void sendPostRequest(String query, String payload) throws Exception {\n        String hmac = getHmac(\"POST\", query, payload);\n\n        HttpClient httpClient = HttpClient.newHttpClient();\n        HttpRequest request = HttpRequest.newBuilder()\n                .uri(URI.create(BANXA_URL + query))\n                .timeout(Duration.ofSeconds(10))\n                .header(\"Authorization\", \"Bearer \" + hmac)\n                .header(\"content-type\", \"application/json\")\n                .POST(HttpRequest.BodyPublishers.ofString(payload))\n                .build();\n\n        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());\n\n        if (response.statusCode() == 200) {\n            System.out.println(\"OK\");\n        } else {\n            System.out.println(\"Failed: \" + response.statusCode());\n        }\n    }\n\n    public String getHmac(String method, String query, String payload) throws Exception {\n        String nonce = String.valueOf(System.currentTimeMillis());\n\n        String data = method + \"\\n\" +\n                query + \"\\n\" +\n                nonce;\n\n        if (payload != null) {\n            data += \"\\n\" + payload;\n        }\n\n        SecretKeySpec signingKey = new SecretKeySpec(SECRET.getBytes(), \"HmacSHA256\");\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(signingKey);\n        return KEY + \":\" + toHexString(mac.doFinal(data.getBytes())) + \":\" + nonce;\n    }\n\n    private String toHexString(byte[] bytes) {\n        Formatter formatter = new Formatter();\n        for (byte b : bytes) {\n            formatter.format(\"%02x\", b);\n        }\n        return formatter.toString();\n    }\n}\n","lang":"java"},"children":[]},{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"swift","header":{"controls":{"copy":{}}},"source":"import CryptoKit\nimport Foundation\n\nlet hostname = \"https://api.banxa-sandbox.com/\"\nlet key = \"[YOUR_MERCHANT_KEY]\"\nlet secret = \"[YOUR_MERCHANT_SECRET]\".data(using: .utf8)!\nlet secretKey = SymmetricKey(data: secret)\n\npublic func generateHmac(payload: String, nonce: String) -> String {\n    ...\n}\n\n\npublic func getRequest(query: String) {\n    let method = \"GET\"\n    let hmac = generateHmac(method: method, query: query)\n    \n    var request = URLRequest(url: URL(string: hostname + query)!)\n    \n    request.addValue(\"application/json\", forHTTPHeaderField: \"Content-Type\")\n    request.addValue(\"Bearer \" + hmac, forHTTPHeaderField: \"Authorization\")\n    \n    let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { data, response, error in\n        guard error == nil else {\n            return\n        }\n        \n        guard let data = data else {\n            return\n        }\n        \n        do {\n            //create json object from data\n            if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {\n                print (json)\n            }\n        } catch let error {\n            print(error.localizedDescription)\n        }\n    })\n    task.resume()\n}\n\ngetRequest(query: \"api/payment-methods?source=USD\")\n","lang":"swift"},"children":[]},{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"ruby","header":{"controls":{"copy":{}}},"source":"require 'rest-client'\nrequire 'openssl'\n\ndef generate_hmac(time, query, body, method = 'POST')\n  ...\nend\n\ndef request_env_url(resource)\n  \"https://api.banxa-sandbox.com#{query}\"\nend\n\ndef get_request(query)\n  response = RestClient.get(request_env_url(query), signed_header(query, payload, 'GET'))\n  JSON.parse(response.body)\nend\n\ndef signed_header(query, body = nil, method = 'POST', content_type = 'application/json')\n  epoch_time = Time.now.to_i\n  access_signature = generate_hmac(epoch_time, resource, body, method)\n  {\n    \"Authorization\": \"Bearer #{access_signature.encode('UTF-8').to_s}\",\n    \"Accept\": 'application/json',\n    \"Content-Type\": content_type.to_s\n  }\nend\n","lang":"ruby"},"children":[]}]},"headings":[{"value":"Sample Code","id":"sample-code","depth":2}],"frontmatter":{"title":"Step 4: First API Call","seo":{"title":"Sample Code"}},"lastModified":"2026-05-19T23:30:38.000Z","pagePropGetterError":{"message":"","name":""}},"slug":"/products/legacy-api/docs/on-ramp-off-ramp/on-ramp-api-tutorial/step-4-first-api-call","userData":{"isAuthenticated":false,"teams":["anonymous"]},"isPublic":true}