### Create Payment Link - JavaScript Source: https://developer.ikhokha.com/overview Use this JavaScript snippet to create a payment link. Ensure you have the 'crypto-js', 'url', and 'axios' libraries installed. Replace placeholder IDs with your actual application credentials. ```javascript const crypto = require("crypto-js"); const url = require("url"); const axios = require("axios"); const apiEndPoint = "https://api.ikhokha.com/public-api/v1/api/payment"; const ApplicationId = "YourAppIDHere"; const ApplicationKey = "YourAppSecretHere"; const request = { entityID: "4", externalEntityID: "4", amount: 200, currency: "ZAR", requesterUrl: "https://example.com/requester", description: "Test Description 1", paymentReference: "4", mode: "live", externalTransactionID: "4", urls: { callbackUrl: "https://example.com/callback", successPageUrl: "https://example.com/success", failurePageUrl: "https://example.com/failure", cancelUrl: "https://example.com/cancel", }, }; function createPayloadToSign(urlPath, body = "") { try { const parsedUrl = new url.parse(urlPath); const basePath = parsedUrl.path; if (!basePath) throw new Error("No basePath in url"); const payload = basePath + body; return jsStringEscape(payload); } catch (error) { console.log("Error on createPayloadToSign" + " " + error); } } function jsStringEscape(str) { try { return str.replace(/[\\"']/g, "\\$& ").replace(/\u0000/g, "\\0"); } catch (error) { console.log("Error on jsStringEscape" + " " + error); } } async function createPaymentLink() { let reqestbody = JSON.stringify(request); if (reqestbody.startsWith("'") && reqestbody.endsWith("'")) { reqestbody = reqestbody.substring(1, reqestbody.length - 1); } const payloadToSign = createPayloadToSign(apiEndPoint, reqestbody); console.log(payloadToSign) const signature = crypto .HmacSHA256(payloadToSign, ApplicationKey.trim()) .toString(crypto.enc.Hex); try { const response = await axios.post(`${apiEndPoint}`, request, { headers: { Accept: "application/json", "IK-APPID": ApplicationId.trim(), "IK-SIGN": signature.trim(), }, }); return response.data; } catch (error) { console.log("Error on create Payment link" + " " + error); } } console.log("Run create payment Link"); createPaymentLink() .then((paymentLink) => { console.log("Payment Link:", paymentLink); }) .catch((error) => { console.error("Error occurred:", error); }); console.log("End Create Payment link"); ``` -------------------------------- ### Transaction History Source: https://developer.ikhokha.com/overview Retrieve a history of all transactions within a specified date range. This endpoint requires start and end dates in YYYY-MM-DD format. ```APIDOC ## GET https://api.ikhokha.com/public-api/v1/api/payments/history?startDate={startDate} &endDate={endDate} ### Description Retrieves a list of past transactions within a specified date range. ### Method GET ### Endpoint https://api.ikhokha.com/public-api/v1/api/payments/history?startDate={startDate} &endDate={endDate} ### Parameters #### Query Parameters - **startDate** (string) - FALSE - The start date for the transaction history (YYYY-MM-DD) - **endDate** (string) - FALSE - The end date for the transaction history (YYYY-MM-DD) ### Response #### Success Response (200) - **Response** (Array) - An array of transaction objects. - **[0].paylinkID** (string) - Unique identifier for the payment link - **[0].status** (string) - Payment status - **[0].createdAt** (string (ISO 8601 format)) - Timestamp when the payment link was created - **[0].amount** (integer) - Amount in smallest currency unit (e.g., cents for ZAR) - **[0].description** (string) - Description of the payment - **[0].externalTransactionID** (string) - External transaction identifier ### Response Example ```json { "Response": [ { "paylinkID": "d8z202zhpns1kl5", "status": "PAID", "createdAt": "2024-02-20T12:00:56.235Z", "amount": 100, "description": "Test Description 1", "externalTransactionID": "d8z202zhpns1kl5ext" } ] } ``` ``` -------------------------------- ### Get Payment Status by External Reference Source: https://developer.ikhokha.com/overview Retrieves the payment status using an external transaction ID. This endpoint is useful for checking the status of a payment initiated through an external system. ```APIDOC ## GET /public-api/v1/api/getStatus/external ### Description Retrieves the payment status using an external transaction ID or a payment link ID. ### Method GET ### Endpoint https://api.ikhokha.com/public-api/v1/api/getStatus/external ### Parameters #### Query Parameters - **externalReference** (string) - Required - The external transaction ID to look up. - **paymentLinkId** (string) - Required - The unique identifier for the payment link. ### Response #### Success Response (200) - **paylinkID** (string) - Unique identifier for the payment link. - **status** (string) - Payment status. - **createdAt** (string) - Timestamp when the payment link was created (ISO 8601 format). - **amount** (integer) - Amount in smallest currency unit. - **description** (string) - Optional - Description of the payment. #### Response Example ```json { "paylinkID": "d8z202zhpns1kl5", "status": "PAID", "createdAt": "2024-02-20T12:00:56.235Z", "amount": 100, "description": "Test Description 1" } ``` ``` -------------------------------- ### Get Payment Status by Paylink ID Source: https://developer.ikhokha.com/overview Retrieves the payment status using the unique payment link ID. This is the primary method for checking the status of a payment initiated via iKhokha. ```APIDOC ## GET /public-api/v1/api/getStatus/{paylinkId} ### Description Retrieves the payment status using the unique payment link ID. ### Method GET ### Endpoint https://api.ikhokha.com/public-api/v1/api/getStatus/{paylinkId} ### Parameters #### Path Parameters - **paylinkId** (string) - Required - The unique identifier for the payment link. ### Response #### Success Response (200) - **paylinkID** (string) - Unique identifier for the payment link. - **status** (string) - Payment status. - **createdAt** (string) - Timestamp when the payment link was created (ISO 8601 format). - **amount** (integer) - Amount in smallest currency unit. - **description** (string) - Optional - Description of the payment. #### Response Example ```json { "paylinkID": "d8z202zhpns1kl5", "status": "PAID", "createdAt": "2024-02-20T12:00:56.235Z", "amount": 100, "description": "Test Description 1" } ``` ``` -------------------------------- ### Create Payment Link using C# Source: https://developer.ikhokha.com/overview Use this snippet to create a payment link. Ensure the amount is in cents. The code handles API endpoint configuration, request body creation, payload signing, and making the POST request to the iKhokha API. ```csharp using System; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using System.Security.Cryptography; using System.Text.RegularExpressions; using System.Reflection.Metadata; class Program { const string apiEndPoint = "https://api.ikhokha.com/public-api/v1/api/payment"; const string ApplicationId = "YourAppIDHere"; const string ApplicationKey = "YourAppSecretHere"; static async Task Main() { try { var paymentLink = await CreatePaymentLink(); if (paymentLink != null) { Console.WriteLine("Payment Link: " + paymentLink); } } catch (Exception ex) { Console.Error.WriteLine("Error occurred: " + ex.Message); } } // Create Payment Link // Note - The amount field has to be in CENTS public static async Task CreatePaymentLink() { var request = new { entityID = Guid.NewGuid().ToString(), externalEntityID = Guid.NewGuid().ToString(), amount = 200, // Note amount is in cents currency = "ZAR", requesterUrl = "https://example.com/success", description = "Test Description 1", paymentReference = Guid.NewGuid().ToString(), mode = "live", externalTransactionID = Guid.NewGuid().ToString(), urls = new { callbackUrl = "https://example.com/success", successPageUrl = "https://example.com/success", failurePageUrl = "https://example.com/failure", cancelUrl = "https://example.com/cancel", }, }; string requestBodyStr = JsonConvert.SerializeObject(request); var reqestbody = Newtonsoft.Json.JsonConvert.SerializeObject(request); if (reqestbody.StartsWith("'") && reqestbody.EndsWith("'")) { reqestbody = reqestbody.Substring(1, reqestbody.Length - 1); } string payloadToSign = CreatePayloadToSign(apiEndPoint, requestBodyStr); string signature = SignPayload(payloadToSign, ApplicationKey); var requestContent = new StringContent(requestBodyStr, Encoding.UTF8, "application/json"); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("IK-APPID", ApplicationId); client.DefaultRequestHeaders.Add("IK-SIGN", signature); var response = await client.PostAsync(apiEndPoint, requestContent); if (response.IsSuccessStatusCode) { var responseBody = await response.Content.ReadAsStringAsync(); return responseBody; } else { throw new Exception($"Failed to send request: {response.StatusCode}"); } } } //Main changes start from here static string CreatePayloadToSign(string url, string body) { var uri = new Uri(url); //Get base path from url string basePath = uri.AbsolutePath; // Directly use the body string that was already JSON serialized. string fullPayload = basePath + body; return JsStringEscape(fullPayload); } static string JsStringEscape(string str) { // Correctly escaping backslashes, quotes, and other necessary characters. str = str.Replace("\", "\\\\"); // Escape backslashes first to prevent double escaping str = str.Replace("\"", "\\\""); // Escape double quotes str = Regex.Replace(str, "\u0000", "\\0"); // Null character if necessary return str; } static string SignPayload(string payload, string key) { //Code for generating signature using (var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(key))) { byte[] hashmessage = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(payload)); return BitConverter.ToString(hashmessage).Replace("-", string.Empty).ToLower(); } } } ``` -------------------------------- ### Create Payment Link with Python Source: https://developer.ikhokha.com/overview This snippet demonstrates how to create a payment link using the iKhokha Public API. It includes functions for payload signing and making the POST request. Ensure you have your App ID and App Secret configured. ```python import requests import json import hashlib import hmac import uuid api_end_point = "https://api.ikhokha.com/public-api/v1/api/payment" app_id = "YourAppIDHere" app_secret = "YourAppSecretHere" def create_payload_to_sign(url, body): uri = url.split('//', 1)[-1] base_path = '/' + uri.split('/', 1)[-1] full_payload = base_path + body return full_payload def sign_payload(payload, key): key_bytes = key.encode('utf-8') payload_bytes = payload.encode('utf-8') hmac_obj = hmac.new(key_bytes, payload_bytes, hashlib.sha256) return hmac_obj.hexdigest() def create_payment_link(): request = { "entityID": str(uuid.uuid4()), "externalEntityID": str(uuid.uuid4()), "amount": 200, "currency": "ZAR", "requesterUrl": "https://example.com/success", "description": "Test Description 1", "paymentReference": str(uuid.uuid4()), "mode": "live", "externalTransactionID": str(uuid.uuid4()), "urls": { "callbackUrl": "https://example.com/success", "successPageUrl": "https://example.com/success", "failurePageUrl": "https://example.com/failure", "cancelUrl": "https://example.com/cancel" } } request_body_str = json.dumps(request) payload_to_sign = create_payload_to_sign(api_end_point, request_body_str) # print(payload_to_sign) # Manually replace quotes with three backslashes and quotes payload_to_sign = payload_to_sign.replace('"', r'\"').replace(': ', r':').replace(', ', r',') print(payload_to_sign) signature = sign_payload(payload_to_sign, app_secret) print(signature) headers = { "Content-Type": "application/json", "IK-APPID": app_id, "IK-SIGN": signature } response = requests.post( api_end_point, headers=headers, data=request_body_str) if response.status_code == 200: return response.json() else: raise Exception(f"Failed to send request: {response.status_code}") def main(): try: for _ in range(1): payment_link = create_payment_link() if payment_link: print("Payment Link:", payment_link) except Exception as e: print("Error occurred:", e) if __name__ == "__main__": main() ``` -------------------------------- ### Create Payment Link using cURL Source: https://developer.ikhokha.com/overview This cURL command demonstrates how to create a payment link by sending a POST request to the iKhokha API. Ensure you include your Application ID and a generated signature in the headers. ```curl curl -X POST "https://api.ikhokha.com/public-api/v1/api/payment" \ -H "Content-Type: application/json" \ -H "IK-APPID: YourAppIDHere" \ -H "IK-SIGN: GeneratedSignatureHere" \ -d '{ "entityID": "4", "externalEntityID": "4", "amount": 1000, "currency": "ZAR", "requesterUrl": "https://example.com/requester", "description": "Test Description 1", "paymentReference": "4", "mode": "live", "externalTransactionID": "4", "urls": { "callbackUrl": "https://example.com/callback", "successPageUrl": "https://example.com/success", "failurePageUrl": "https://example.com/failure", "cancelUrl": "https://example.com/cancel" } }' ``` -------------------------------- ### Create Payment Link Source: https://developer.ikhokha.com/overview Initiates a new payment link for a customer. This endpoint allows you to specify payment details, currency, and relevant URLs for callbacks and redirects. ```APIDOC ## POST /public-api/v1/api/payment ### Description Initiates a new payment link for a customer. This endpoint allows you to specify payment details, currency, and relevant URLs for callbacks and redirects. ### Method POST ### Endpoint https://api.ikhokha.com/public-api/v1/api/payment ### Headers - **IK-APPID** (string) - Required - Your Application ID. - **IK-SIGN** (string) - Required - The signature generated for the request. ### Request Body - **entityID** (string) - Required - The entity ID for the payment. - **externalEntityID** (string) - Required - The external entity ID. - **amount** (integer) - Required - The payment amount. - **currency** (string) - Required - The currency of the payment (e.g., ZAR). - **requesterUrl** (string) - Required - The URL of the requester. - **description** (string) - Optional - Description of the payment. - **paymentReference** (string) - Required - The payment reference. - **mode** (string) - Required - The mode of the payment (e.g., live). - **externalTransactionID** (string) - Required - The external transaction ID. - **urls** (object) - Required - Object containing various URLs. - **callbackUrl** (string) - Required - The callback URL. - **successPageUrl** (string) - Required - The URL for the success page. - **failurePageUrl** (string) - Required - The URL for the failure page. - **cancelUrl** (string) - Required - The URL for the cancel page. ### Request Example ```json { "entityID": "4", "externalEntityID": "4", "amount": 1000, "currency": "ZAR", "requesterUrl": "https://example.com/requester", "description": "Test Description 1", "paymentReference": "4", "mode": "live", "externalTransactionID": "4", "urls": { "callbackUrl": "https://example.com/callback", "successPageUrl": "https://example.com/success", "failurePageUrl": "https://example.com/failure", "cancelUrl": "https://example.com/cancel" } } ``` ``` -------------------------------- ### Create Payment Link Response Source: https://developer.ikhokha.com/overview This is a sample response object after successfully creating a payment link. It contains details like responseCode, message, paylinkUrl, paylinkID, and externalTransactionID. ```json { "responseCode": "00", "message": "", "paylinkUrl": "https://securepay.ikhokha.red/2zh1zj6y8xpb0g3", "paylinkID": "2zh1zj6y8xpb0g3", "externalTransactionID": "TRANS789" } ``` -------------------------------- ### Create Payment Link - PHP Source: https://developer.ikhokha.com/overview This PHP snippet demonstrates how to create a payment link using the Ikhokha API. It utilizes cURL for making the HTTP request and includes functions for payload signing. ```php "4", "externalEntityID" => "4", "amount" => 1000, "currency" => "ZAR", "requesterUrl" => "https://example.com/requester", "description" => "Test Description 1", "paymentReference" => "4", "mode" => "live", "externalTransactionID" => "5", "urls" => [ "callbackUrl" => "https://example.com/callback", "successPageUrl" => "https://example.com/success", "failurePageUrl" => "https://example.com/failure", "cancelUrl" => "https://example.com/cancel" ] ]; function escapeString($str) { $escaped = preg_replace(['/[\\"\'\"]/u', '/\x00/'], ['\\$0', '\\0'], (string)$str); $cleaned = str_replace('\/', '/', $escaped); return $cleaned; } function createPayloadToSign($urlPath, $body) { $parsedUrl = parse_url($urlPath); $basePath = $parsedUrl['path']; if (!$basePath) { throw new Exception("No path present in the URL"); } $payload = $basePath . $body; $escapedPayloadString = escapeString($payload); return $escapedPayloadString; } function generateSignature($payloadToSign, $secret) { return hash_hmac('sha256', $payloadToSign, $secret); } $stringifiedBody = json_encode($requestBody); $payloadToSign = createPayloadToSign($endpoint, $stringifiedBody); $ikSign = generateSignature($payloadToSign, $appSecret); // Initialize cURL session $ch = curl_init($endpoint); // Set cURL options curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $stringifiedBody); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "IK-APPID: $appID", "IK-SIGN: $ikSign" ]); // Execute cURL session $response = curl_exec($ch); curl_close($ch); // Decode and output the response $responseData = json_decode($response, true); echo print_r($responseData, true); ?> ``` -------------------------------- ### Create Payment Link Source: https://developer.ikhokha.com/overview This endpoint allows you to generate a payment link for a transaction. You need to provide details such as the amount, currency, and URLs for callbacks and redirects. ```APIDOC ## POST https://api.ikhokha.com/public-api/v1/api/payment ### Description Creates a payment link for a transaction, enabling customers to complete payments. ### Method POST ### Endpoint https://api.ikhokha.com/public-api/v1/api/payment ### Parameters #### Request Body - **entityID** (string) - FALSE - Application key ID - **externalEntityID** (string) - TRUE - 3rd Party account identifier - **amount** (number) - FALSE - currency value in smallest unit (e.g., cents for ZAR) - **currency** (string) - FALSE - - **requesterUrl** (string) - FALSE - URL from which the call originates - **mode** (string) - FALSE - Mode of the transaction - **description** (string) - TRUE - Descriptor for the transaction - **externalTransactionID** (string) - FALSE - Unique transaction ID - **urls.callbackUrl** (string) - FALSE - URL to which callbacks are sent - **urls.successPageUrl** (string) - FALSE - URL for the success page - **urls.failurePageUrl** (string) - FALSE - URL for the failure page - **urls.cancelUrl** (string) - TRUE - URL for the cancellation page ### Request Example ```json { "entityID": "APPID123", "externalEntityID": "EXTID456", "amount": 10000, "currency": "ZAR", "requesterUrl": "https://example.com/requester", "mode": "live", "externalTransactionID": "TRANS789", "urls": { "callbackUrl": "https://example.com/callback", "successPageUrl": "https://example.com/success", "failurePageUrl": "https://example.com/failure", "cancelUrl": "https://example.com/cancel" } } ``` ### Response #### Success Response (200) - **responseCode** (string) - Defined by iKhokha - **message** (string) - responseCode descriptor - **paylinkUrl** (string) - url to redirect to for payment - **paylinkID** (string) - - **externalTransactionID** (string) - #### Response Example ```json { "responseCode": "00", "message": "", "paylinkUrl": "https://securepay.ikhokha.red/2zh1zj6y8xpb0g3", "paylinkID": "2zh1zj6y8xpb0g3", "externalTransactionID": "TRANS789" } ``` ``` -------------------------------- ### Handle Ikhokha Webhook Response in JavaScript Source: https://developer.ikhokha.com/overview This snippet demonstrates how to set up an Express.js server to receive and validate Ikhokha webhook requests. It includes signature verification using crypto-js. ```javascript const crypto = require("crypto-js"); const url = require("url"); const express = require("express"); const bodyParser = require("body-parser"); const app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); const port = 3001; const callbackUrl = "https://example.com/order?order=order-id"; const applicationKeySecret = "YourAppSecretHere"; app.post("/", (req, res) => { const body = req.body; delete body.text; const { pathname } = new URL(callbackUrl); const payloadToSign = createPayloadToSign(pathname, JSON.stringify(body)); const signature = crypto .HmacSHA256(payloadToSign, applicationKeySecret.trim()) .toString(crypto.enc.Hex); // Validate the request if (signature !== req.headers["ik-sign"]) { console.log( `Signatures does not match, calculated ${signature} but got ${req.headers["ik-sign"]}` ); return res.sendStatus(403); } // Process the request as needed res.sendStatus(200); }); app.listen(port, () => { console.log(`Example app listening on port ${port}`); }); function createPayloadToSign(urlPath, body = "") { try { const parsedUrl = new url.parse(urlPath); const basePath = parsedUrl.path; if (!basePath) throw new Error("No basePath in url"); const payload = basePath + body; return jsStringEscape(payload); } catch (error) { console.log("Error on createPayloadToSign" + " " + error); } } function jsStringEscape(str) { try { return str.replace(/[\\"']/g, "\\$&\").replace(/\u0000/g, "\\0"); } catch (error) { console.log("Error on jsStringEscape" + " " + error); } } ``` -------------------------------- ### Create Payment Link Request Source: https://developer.ikhokha.com/overview Use this JSON object to create a payment link. Ensure all required fields, including entityID, amount, currency, requesterUrl, mode, externalTransactionID, and URLs, are provided. ```json { "entityID": "APPID123", "externalEntityID": "EXTID456", "amount": 10000, "currency": "ZAR", "requesterUrl": "https://example.com/requester", "mode": "live", "externalTransactionID": "TRANS789", "urls": { "callbackUrl": "https://example.com/callback", "successPageUrl": "https://example.com/success", "failurePageUrl": "https://example.com/failure", "cancelUrl": "https://example.com/cancel" } } ``` -------------------------------- ### Webhook Response Source: https://developer.ikhokha.com/overview This is an endpoint that is specified in the callback URL during the create payment link request. It is called once after a successful or failed payment. ```APIDOC ## POST [Specified in the callback url on the create payment link request] ### Description Receives payment status updates (SUCCESS or FAILURE) via webhook after a payment attempt on a payment link. ### Method POST ### Endpoint Specified in the callback url on the create payment link request ### Parameters #### Header - **ik-appid** (string) - The app id you created in the Merchant Dashboard Portal - **ik-sign** (string) - The signature generated with the request payload and callback url #### Request Body - **paylinkID** (string) - FALSE - The paylinkID is the same paylinkID in the create payment link request - **status** (string) - FALSE - The status value can be either SUCCESS or FAILURE depending on the outcome of the payment attempt - **externalTransactionID** (string) - FALSE - The externalTransactionID suppplied in the original create payment link request - **responseCode** (string) - FALSE - The response code indicates the rest of the payload is good to use ### Response Example ```json { "paylinkID": "jm421493s3r4pdf", "status": "SUCCESS", "externalTransactionID": "TRANS789", "responseCode": "00" } ``` ``` -------------------------------- ### Transaction History Response Object Source: https://developer.ikhokha.com/overview This JSON object represents the response structure for a transaction history query. It includes details for each transaction. ```json [ { "paylinkID": "d8z202zhpns1kl5", "status": "PAID", "createdAt": "2024-02-20T12:00:56.235Z", "amount": 100, "description": "Test Description 1", "externalTransactionID": "d8z202zhpns1kl5ext" }, ] ``` -------------------------------- ### Payment Status Response Object (External) Source: https://developer.ikhokha.com/overview This JSON object details the response structure for checking payment status using an external transaction ID. It provides key information about the payment. ```json { "paylinkID": "d8z202zhpns1kl5", "status": "PAID", "createdAt": "2024-02-20T12:00:56.235Z", "amount": 100, "description": "Test Description 1", } ``` -------------------------------- ### Webhook Response Body Source: https://developer.ikhokha.com/overview The body of the webhook response provides details about the payment status. Key fields include paylinkID, status, externalTransactionID, and responseCode. ```json { "paylinkID": "jm421493s3r4pdf", "status": "SUCCESS", "externalTransactionID": "TRANS789", "responseCode": "00" } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.