Code snippets

Example code snippets for signing and sending requests

class Finrax
{
    private $apiKey;
    private $apiSecret;
    private $baseUrl = 'https://payments.finrax.com';
    
    
    public function __construct(string $apiKey, string $apiSecret)
    {
        $this->apiKey = $apiKey;
        $this->apiSecret = $apiSecret;
    }
    
    public function makeRequest($method, $endpoint, array $body = [], array $query = [])
    {
        $method = strtoupper($method);
        $qs = http_build_query($query, '', '&');
        $path = ($qs == '') ? $endpoint : $endpoint . '?' . $qs;
        $ch = curl_init();
        $jsonBody = '';
        if ($method == 'POST' || $method == 'PUT' || $method == 'PATCH') {
            $jsonBody = json_encode($body, JSON_UNESCAPED_SLASHES);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonBody);
        }
        curl_setopt_array($ch, [
            CURLOPT_URL => $this->baseUrl . $path,
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Authorization: ' . $this->buildAuthorizationHeaderValue($path, $jsonBody)
            ]
        ]);
        $response = curl_exec($ch);
        curl_close($ch);
        return json_decode($response, true);
    }
    
    private function buildAuthorizationHeaderValue($path, $jsonBody = '') 
    {
        $timestamp = intval(microtime(true) * 1000);
        $signaturePayload = $path . $timestamp . $jsonBody;
        $signature = hash_hmac('sha256', $signaturePayload, $this->apiSecret);
        return "FRX-API API-Key={$this->apiKey}," .
               "Signature={$signature}," .
               "Timestamp={$timestamp}";
    }
}

Last updated