Example API call function

Just fill in your public and private keys and you're good to go!

🚧

It would probably be a very good idea to keep this file, or at least the API keys, in a directory that is not directly accessible from the web!

<?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;
    }
?>
// Replace this with whatever you need to do with the results
function resultsHandler(input) {
    // If you use the ?as_array=1 parameter in the API call, the resulting
    // object will have an array named "results" as a property
    input.results.forEach(function(oneResult) {
        console.log(oneResult);
        console.log("\n");
    });
}

function lyyti_apiCall(call_string, callbackFunction) {
  // Store these somewhere safe and smart
    var public_key = 'apitesti';
    var private_key = 'asdasdasd123';

    var CryptoJS = require('crypto-js');        // npm install crypto-js
    var Base64 = require('js-base64').Base64;   // npm install js-base64
    var HTTPS = require('https');

    var timestamp = Math.floor(new Date()/1000);
    var signature = CryptoJS.HmacSHA256(
        Base64.encode(public_key+','+timestamp+','+call_string),
        private_key
    ).toString(CryptoJS.enc.Hex);

    var options = {
        hostname: 'api.lyyti.com',
        path: '/v2/'+call_string,
        method: 'GET',
        headers: {
            'Accept': 'application/json; charset=utf-8',
            'Authorization': 'LYYTI-API-V2 public_key='+public_key+', timestamp='+timestamp+', signature='+signature
        }
    };

    var request = HTTPS.get(options, function (response) {
        var buffer = '';

        response.on('data', function (chunk) {
            buffer += chunk;
        });

        response.on('end', function (err) {
            // This is an example, it's probably better to use promises, async/await, or something similar here
            callbackFunction(JSON.parse(buffer));
        });
    });
}

// Use the as_array=1 parameter to get the results as an array rather than object
lyyti_apiCall('events?as_array=1', resultsHandler);
# .NET version using PowerShell (save as a .ps1 file)
# Credits to: https://github.com/kabtoffe

$script:LyytiPublicKey = "apitesti"
$script:LyytiPrivateKey = "asdasdasd123"
$script:LyytiAPIBaseUrl = "https://api.lyyti.com/v2/"

function Get-UnixTimeStamp{
    param([DateTime]$DateTime)

    $DateTime = $DateTime.ToUniversalTime()
    Get-Date -Date $DateTime -UFormat %s -Millisecond 0
}

function Get-StringFromBytes{
    param([byte[]]$Bytes)

    $sbinary = ""
    for ($i = 0; $i -lt $Bytes.Length; $i++){
        $sbinary += $Bytes[$i].ToString("X2")
    }
    $sbinary
}

function Get-LyytiSignatureHash{

    param(
        [DateTime]$Timestamp,
        [string]$UnixTimeStamp,
        [string]$Callstring
    )

    if ($UnixTimeStamp -eq $null){
        $UnixTimeStamp = Get-UnixTimeStamp -DateTime $Timestamp
    }

    $message = "$LyytiPublicKey,$UnixTimeStamp,$Callstring"
    $secret = $LyytiPrivateKey

    Write-Verbose "Message: $message"

    $hmacsha = New-Object System.Security.Cryptography.HMACSHA256
    $hmacsha.key = [Text.Encoding]::UTF8.GetBytes($secret)
    $MessageBytes = [Text.Encoding]::UTF8.GetBytes($message)
    $MessageBase64 = [Convert]::ToBase64String($MessageBytes)
    $MessageBase64Bytes = [Text.Encoding]::UTF8.GetBytes($MessageBase64)
    $SignatureHash = $hmacsha.ComputeHash($MessageBase64Bytes)
    $Signature = Get-StringFromBytes -Bytes $SignatureHash
    $Signature.ToLower()
}

function Get-LyytiAuthHeader{
    param($CallString)
    $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
    $UnixTimeStamp = Get-UnixTimeStamp ([DateTime]::Now)
    $SignatureHash = Get-LyytiSignatureHash -UnixTimeStamp $UnixTimeStamp -Callstring $CallString
    $headers.Add("Accept", "application/json; charset=utf-8")
    $AuthHeader = "LYYTI-API-V2 public_key=$LyytiPublicKey, timestamp=$UnixTimeStamp, signature=$SignatureHash"
    Write-Verbose $AuthHeader
    $headers.Add("Authorization", $AuthHeader)
    $headers
}

function Invoke-LyytiApiCall{
    param($CallString, $Body)

    $header = Get-LyytiAuthHeader -CallString $CallString
    
    if ($Body -ne $null){
        Invoke-RestMethod -Method POST -Uri "$LyytiAPIBaseUrl$CallString" -Headers $header -Body $Body
    }
    else{
        Invoke-RestMethod -Method GET -Uri "$LyytiAPIBaseUrl$CallString" -Headers $header
    }
}