php function call api code example

Example: php function call api

<?php
    // NOTE: This function requires cURL to be available to PHP.

    function lyyti_apiCall($call_string, $http_method = 'GET', $payload = null)
    {
        // Generate the signature based on the API keys
        $public_key = 'apitesti';
        $private_key = 'asdasdasd123';
        $timestamp = time();
        $signature = hash_hmac(
            'sha256',
            base64_encode($public_key.','.$timestamp.','.$call_string),
            $private_key
        );

        // Set the required HTTP headers
        $http_headers = array(
            'Accept: application/json; charset=utf-8',
            'Authorization: LYYTI-API-V2 public_key='.$public_key.', timestamp='.$timestamp.', signature='.$signature
        );

        // Initialize the cURL connection
        $curl = curl_init('https://api.lyyti.com/v2/'.$call_string);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

        // Handle HTTP method and payload
        if ($http_method != 'GET' && isset($payload))
        {
            if ($http_method == 'PATCH')
            {
                $http_headers[] = 'Content-Type: application/merge-patch+json';
            }
            else
            {
                $http_headers[] = 'Content-Type: application/json; charset=utf-8';
            }
            if ($http_method == 'POST')
            {
                curl_setopt($curl, CURLOPT_POST, true);
            }
            else
            {
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $http_method);
            }
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($payload));
        }

        // Set the HTTP headers and execute the call
        curl_setopt($curl, CURLOPT_HTTPHEADER, $http_headers);
        $result_json = curl_exec($curl);

        // Check for errors
        if ($curl_errno = curl_errno($curl))
        {
            return array('curl_error' => array('errno' => $curl_errno, 'message' => curl_strerror($curl_errno)));
        }
        curl_close($curl);

        // Turn the resulting JSON into a PHP associative array and return it
        $result_array = json_decode($result_json, $assoc = true);
        return $result_array;
    }
?>

Tags:

Php Example