### Node.js Fullstack Backend Setup Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/configuration.md Set up the backend for the Node.js fullstack example by navigating to the 'backend' directory, installing dependencies, and starting the server. ```bash cd nodejs/pay-api-app/backend npm install npm start # Server runs on http://localhost:3000 ``` -------------------------------- ### Node.js Fullstack Frontend Setup Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/configuration.md Set up the frontend for the Node.js fullstack example by navigating to the 'frontend' directory, installing dependencies, and running the development server. ```bash cd nodejs/pay-api-app/frontend npm install npm run dev # Frontend runs on http://localhost:5173 ``` -------------------------------- ### Node.js Running Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/configuration.md Execute the Node.js example using 'npm start' or 'node index.js'. ```bash npm start # or node index.js ``` -------------------------------- ### Run Node.js Pay API Examples Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/QUICK-REFERENCE.md Instructions for setting up and running the Node.js examples, including a basic setup and a full-stack example with an Express backend and a Vue frontend. ```bash cd nodejs npm install npm start # Or fullstack cd nodejs/pay-api-app/backend npm install && npm start # Backend on :3000 # In another terminal cd nodejs/pay-api-app/frontend npm install && npm run dev # Frontend on :5173 ``` -------------------------------- ### Go Installation Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/configuration.md Install Go dependencies for the iKhokha Pay API example by running 'go mod tidy' in the 'golang' directory. ```bash cd golang go mod tidy ``` -------------------------------- ### Run Go Pay API Example Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/QUICK-REFERENCE.md Instructions for running the Go example. Ensure you create a `.env` file with your credentials before execution. ```bash cd golang # Create .env with credentials go run main.go ``` -------------------------------- ### Dart Project Setup and Installation Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/configuration.md Navigate to the Dart iKhokha package directory and fetch its dependencies. This prepares your Dart project for integration. ```bash cd dart/ik_pay dart pub get ``` -------------------------------- ### Run Dart Pay API Example Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/QUICK-REFERENCE.md Instructions for fetching dependencies and running the Dart example. ```bash cd dart/ik_pay dart pub get dart run main.dart ``` -------------------------------- ### Run C# Pay API Example Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/QUICK-REFERENCE.md Instructions for building and running the C# example using the .NET CLI. ```bash cd c-sharp donet build donet run ``` -------------------------------- ### C# Simple Example Configuration Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/configuration.md Configure the C# example with hardcoded constants for the API endpoint, Application ID, and Application Key. ```csharp const string apiEndPoint = "https://api.ikhokha.com/public-api/v1/api/payment"; const string ApplicationId = "Your Application Id"; const string ApplicationKey = "Your Application Key"; ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/nodejs/pay-api-app/frontend/README.md Installs all necessary packages for the project. Run this command after cloning the repository. ```sh npm install ``` -------------------------------- ### C# Setup Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/configuration.md Build the C# project by navigating to the 'c-sharp' directory and running 'dotnet build'. ```bash cd c-sharp dotnet build ``` -------------------------------- ### Project Setup with .NET CLI Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/api-reference/paylink-csharp.md Commands to create a new .NET console project, navigate into it, and add the required Newtonsoft.Json NuGet package. This is the initial setup for the project. ```bash dotnet new console -n IKPayAPI cd IKPayAPI dotnet add package Newtonsoft.Json ``` -------------------------------- ### Payment History Request Example Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/endpoints.md This example shows how to request payment history by providing a start and end date as query parameters. ```http GET https://api.ikhokha.com/public-api/v1/api/payments/history?startDate=2024-01-01&endDate=2024-01-31 ``` -------------------------------- ### Install Dependencies Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/QUICK-REFERENCE.md Install necessary packages for Node.js, Go, C#, and Dart environments. ```bash # Node.js npm install # Go go get github.com/joho/godotenv # C# dotnet add package Newtonsoft.Json # Dart dart pub get ``` -------------------------------- ### Run Node.js Application Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/nodejs/README.md Starts the Node.js application, typically for running API examples. ```bash npm run start ``` -------------------------------- ### Run Go PayLink Example Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/api-reference/paylink-go.md Execute the Go PayLink API example directly using 'go run'. Ensure you have the main.go file in your current directory. ```bash go run main.go ``` -------------------------------- ### Node.js Installation Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/configuration.md Install Node.js dependencies by navigating to the 'nodejs' directory and running 'npm install'. ```bash cd nodejs npm install ``` -------------------------------- ### Get Payment Status Request Example Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/endpoints.md This example demonstrates the URL format for retrieving the status of a specific payment link using its ID. ```http GET https://api.ikhokha.com/public-api/v1/api/getStatus/abc123def456 ``` -------------------------------- ### C# Running Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/configuration.md Execute the C# example using the command 'dotnet run'. ```bash dotnet run ``` -------------------------------- ### Create Payment Link (Node.js) Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/examples.md This example demonstrates how to create a payment link using the PayLink class. Ensure you have the 'crypto-js', 'url', and 'axios' packages installed. Replace placeholder credentials with your actual Application ID and Key. ```javascript import crypto from "crypto-js"; import url from "url"; import axios from "axios"; class PayLink { config = { apiEndPoint: "", applicationId: "", applicationKey: "", }; constructor({ apiEndPoint, applicationId, applicationKey }) { this.config = { apiEndPoint, applicationId, applicationKey, }; if (Object.values(this.config).some((value) => value === "")) { throw new Error("Please provide all required configuration values"); } } async createPaylink(request) { const requestBody = JSON.stringify(request); const payloadToSign = this.createPayloadToSign(this.config.apiEndPoint, requestBody); const signature = crypto .HmacSHA256(payloadToSign, this.config.applicationKey.trim()) .toString(crypto.enc.Hex); const response = await axios.post(this.config.apiEndPoint, request, { headers: { Accept: "application/json", "IK-APPID": this.config.applicationId.trim(), "IK-SIGN": signature.trim(), }, }); return response.data; } createPayloadToSign(urlPath, body = "") { const parsedUrl = new url.parse(urlPath); const basePath = parsedUrl.path; if (!basePath) throw new Error("No basePath in url"); const payload = basePath + body; return payload.replace(/[\\"']/g, "\\$&" ).replace(/ /g, "\\0"); } } // Usage const request = { entityID: "4", externalEntityID: "4", amount: 200, currency: "ZAR", requesterUrl: "https://example.com/requester", 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", }, }; const payLink = new PayLink({ apiEndPoint: "https://api.ikhokha.com/public-api/v1/api/payment", applicationId: "Your Application Id Here", applicationKey: "Your Application Key Here", }); payLink .createPaylink(request) .then((response) => { console.log("Paylink created successfully: ", response.paylinkUrl); console.log("Paylink ID: ", response.paylinkID); }) .catch((error) => { console.error("An error occurred: ", error); }); ``` -------------------------------- ### Build .NET Project Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/c-sharp/README.md Builds the .NET project. Ensure you have the .NET SDK installed. ```bash dotnet build ``` -------------------------------- ### Install Dependencies Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/dart/ik_pay/README.md Run this command to fetch the necessary Dart packages for your project. ```bash dart pub get ``` -------------------------------- ### Complete POST Request Example in JavaScript Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/authentication.md This JavaScript example demonstrates how to construct a POST request, including serializing the body to JSON and generating the IK-SIGN header. ```javascript // 1. Create request body const requestBody = { entityID: "4", externalEntityID: "4", amount: 200, currency: "ZAR", requesterUrl: "https://example.com/requester", 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" } }; // 2. Serialize to JSON const jsonBody = JSON.stringify(requestBody); // 3. Generate signature const endpoint = "https://api.ikhokha.com/public-api/v1/api/payment"; // const signature = generateSignature(endpoint, jsonBody, APP_KEY); // 4. Make request with headers // const response = await axios.post(endpoint, requestBody, { // headers: { // "Accept": "application/json", // "Content-Type": "application/json", // "IK-APPID": APP_ID, // "IK-SIGN": signature // } // }); // 5. Handle response // console.log(response.data); ``` -------------------------------- ### Installation Command Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/api-reference/paylink-dart.md The command to run in the terminal to fetch the project's dependencies as defined in pubspec.yaml. ```bash dart pub get ``` -------------------------------- ### Go .env File Setup Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/configuration.md Create a '.env' file in the 'golang/' directory to configure the Payment API endpoint, Application ID, and Application Secret. ```bash cat > .env << 'EOF' IK_API_URL="https://api.ikhokha.com/public-api/v1/api/payment" IK_APP_ID="your-app-id" IK_APP_SECRET="your-app-secret" EOF ``` -------------------------------- ### Node.js Fullstack Example Configuration Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/configuration.md Configure the fullstack Node.js example using environment variables for API endpoint, application ID, and application key. Defaults are provided if environment variables are not set. ```javascript const payLink = new PayLink({ apiEndPoint: process.env.IK_API_URL || "https://api.ikhokha.com/public-api/v1/api", applicationId: process.env.IK_APP_ID, applicationKey: process.env.IK_APP_KEY }); ``` -------------------------------- ### Go .gitignore Example Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/configuration.md Ensure the '.env' file is excluded from version control by adding it to the '.gitignore' file. ```text .env *.exe *.dll *.so .DS_Store ``` -------------------------------- ### Node.js Dependencies Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/configuration.md Install necessary Node.js packages for the iKhokha Pay API examples. This includes axios for HTTP requests and crypto-js for cryptographic operations. ```json { "dependencies": { "axios": "^1.7.4", "crypto-js": "^4.2.0" } } ``` -------------------------------- ### C# Environment Variables Setup (Command Prompt) Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/configuration.md Set environment variables for IK_APP_ID and IK_APP_KEY in the Windows Command Prompt before running the C# application. ```cmd set IK_APP_ID=your-app-id set IK_APP_KEY=your-app-key dotnet run ``` -------------------------------- ### C# Environment Variables Setup (Linux/macOS) Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/configuration.md Set environment variables for IK_APP_ID and IK_APP_KEY in Linux/macOS terminals before running the C# application. ```bash export IK_APP_ID="your-app-id" export IK_APP_KEY="your-app-key" dotnet run ``` -------------------------------- ### Install godotenv dependency Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/api-reference/paylink-go.md Command to install the godotenv package, which is used for loading environment variables from .env files. ```bash go get github.com/joho/godotenv ``` -------------------------------- ### Run Development Server Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/nodejs/pay-api-app/frontend/README.md Compiles and hot-reloads the application for development. This command starts a local development server with live updates. ```sh npm run dev ``` -------------------------------- ### PayLink Usage Example Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/api-reference/paylink-csharp.md Demonstrates how to use the PayLinkResponse object after a successful payment link creation. It shows how to access the generated URL and ID. ```csharp var response = await CreatePaymentLink(); Console.WriteLine($"URL: {response.paylinkUrl}"); Console.WriteLine($"ID: {response.paylinkID}"); ``` -------------------------------- ### C# Usage Example for PaymentRequest Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/types.md An example of how to construct a payment request object in C#. Includes fields like entityID, amount, currency, and URLs. ```csharp new { entityID = Guid.NewGuid().ToString(), externalEntityID = Guid.NewGuid().ToString(), amount = 200, 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", } } ``` -------------------------------- ### Flutter Payment Integration Example Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/api-reference/paylink-dart.md A basic Flutter StatefulWidget demonstrating how to initiate a payment, handle the response, and display errors using a SnackBar. ```dart class PaymentPage extends StatefulWidget { @override State createState() => _PaymentPageState(); } class _PaymentPageState extends State { void _initiatePayment() async { try { final request = PaymentRequest(...); final response = await createPayLink(request); // Navigate to payment URL if (await canLaunchUrl(Uri.parse(response.paymentLink))) { await launchUrl(Uri.parse(response.paymentLink)); } } catch (e) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('Payment failed: $e')), ); } } @override Widget build(BuildContext context) { return ElevatedButton( onPressed: _initiatePayment, child: Text('Create Payment Link'), ); } } ``` -------------------------------- ### Create Payment Link (C#) Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/examples.md This C# example demonstrates how to create a payment link using the iKhokha Pay API. It includes generating a signature for authentication and making a POST request. ```csharp using System.Text; using Newtonsoft.Json; using System.Security.Cryptography; using System.Text.RegularExpressions; class PayLinkResponse { public string paylinkID { get; set; } public string paylinkUrl { get; set; } public string externalTransactionID { get; set; } public string responseCode { get; set; } } class Program { const string apiEndPoint = "https://api.ikhokha.com/public-api/v1/api/payment"; const string ApplicationId = "Your Application Id"; const string ApplicationKey = "Your Application Key"; static async Task Main() { try { var paymentLink = await CreatePaymentLink(); if (paymentLink != null) { Console.WriteLine("Payment Link: " + paymentLink?.paylinkUrl); Console.WriteLine("Payment ID: " + paymentLink?.paylinkID); } } catch (Exception ex) { Console.Error.WriteLine("Error occurred: " + ex.Message); } } public static async Task CreatePaymentLink() { var request = new { entityID = Guid.NewGuid().ToString(), externalEntityID = Guid.NewGuid().ToString(), amount = 200, 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); 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(); var paylink = JsonConvert.DeserializeObject(responseBody); return paylink; } else { throw new Exception($"Failed to send request: {response.StatusCode}"); } } } static string CreatePayloadToSign(string url, string body) { var uri = new Uri(url); string basePath = uri.AbsolutePath; string fullPayload = basePath + body; return JsStringEscape(fullPayload); } static string JsStringEscape(string str) { str = str.Replace("\", "\\\\"); str = str.Replace("\"", "\\\""); str = Regex.Replace(str, " ", "\\0"); return str; } static string SignPayload(string payload, string key) { 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(); } } } ``` -------------------------------- ### C# Environment Variables Setup (PowerShell) Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/configuration.md Set environment variables for IK_APP_ID and IK_APP_KEY in PowerShell before running the C# application. ```powershell $env:IK_APP_ID="your-app-id" $env:IK_APP_KEY="your-app-key" dotnet run ``` -------------------------------- ### Install Newtonsoft.Json NuGet Package Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/configuration.md Install the Newtonsoft.Json package for JSON serialization in your .NET project. This is a common dependency for handling JSON data. ```bash dotnet add package Newtonsoft.Json ``` -------------------------------- ### Express Server Configuration Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/api-reference/express-backend.md Sets up an Express server with necessary middleware like CORS and body-parser. Ensure these dependencies are installed. ```javascript const express = require("express"); const cors = require("cors"); const bodyParser = require("body-parser"); const PayLink = require("./paylink"); const app = express(); // Middleware app.use(bodyParser.json()); app.use(cors()); const payLink = new PayLink(); // Routes... app.listen(3000, () => { console.log("Server is running on port 3000"); }); ``` -------------------------------- ### Frontend Payment Creation with Fetch API Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/api-reference/express-backend.md Example of how a Vue frontend can initiate a payment by sending a POST request to the backend API using the Fetch API and opening the returned paylink URL. ```javascript // Frontend code async function createPayment() { const response = await fetch('http://localhost:3000/payment', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(paymentData) }); const data = await response.json(); window.open(data.paylinkUrl, '_blank'); } ``` -------------------------------- ### C# Environment Variable Configuration Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/configuration.md Configure the C# example to use environment variables for Application ID and Application Key, with fallbacks to default values. ```csharp const string apiEndPoint = "https://api.ikhokha.com/public-api/v1/api/payment"; const string ApplicationId = Environment.GetEnvironmentVariable("IK_APP_ID") ?? "Your Application Id"; const string ApplicationKey = Environment.GetEnvironmentVariable("IK_APP_KEY") ?? "Your Application Key"; ``` -------------------------------- ### Initialize PayLink Class Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/api-reference/paylink-nodejs.md Instantiate the PayLink class with your iKhokha API credentials. Ensure that `applicationId` and `applicationKey` are securely loaded, for example, from environment variables. ```javascript import PayLink from "./paylink.js"; const payLink = new PayLink({ apiEndPoint: "https://api.ikhokha.com/public-api/v1/api", applicationId: process.env.IK_APP_ID, applicationKey: process.env.IK_APP_KEY }); ``` -------------------------------- ### Express Backend for Payment Links (Node.js) Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/examples.md This example sets up an Express.js server to handle payment link creation, status checks, webhooks, and payment history retrieval. It requires 'express', 'cors', and 'body-parser' packages. ```javascript const express = require("express"); const cors = require("cors"); const bodyParser = require("body-parser"); const PayLink = require("./paylink"); const app = express(); app.use(bodyParser.json()); app.use(cors()); const payLink = new PayLink(); // Create payment link app.post("/payment", async (req, res) => { try { const response = await payLink.createPaylink(req.body); res.json(response); } catch (error) { res.status(400).json({ error: error.message }); } }); // Check payment status app.get("/payment/:id", async (req, res) => { try { const response = await payLink.getStatusById(req.params.id); res.json(response); } catch (error) { res.status(400).json({ error: error.message }); } }); // Receive webhook callback app.post("/payment/webhook/callback", (req, res) => { console.log("Webhook received:", req.body); res.status(200).send({ success: true }); }); // Get payment history app.get("/payments/history", async (req, res) => { try { const { startDate, endDate } = req.query; const response = await payLink.getPaymentHistory(startDate, endDate); res.json(response); } catch (error) { res.status(400).json({ error: error.message }); } }); app.listen(3000, () => { console.log("Server is running on port 3000"); }); ``` -------------------------------- ### Go Environment Variables (.env format) Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/types.md Example environment variables for configuring iKhokha API access in Go. Includes API URL, App ID, and App Secret. ```dotenv IK_API_URL="https://api.ikhokha.com/public-api/v1/api/payment" IK_APP_ID="Your APP ID" IK_APP_SECRET="Your APP SECRET" ``` -------------------------------- ### Create Payment Link Request Example Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/endpoints.md This JSON object represents a sample request body for creating a payment link. It includes all necessary fields for a transaction, such as amount, currency, and redirect URLs. ```json { "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" } } ``` -------------------------------- ### Required Using Statements Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/api-reference/paylink-csharp.md Lists the necessary using directives for the iKhokha PayLink C# examples. These include namespaces for JSON handling, text manipulation, and cryptography. ```csharp using System.Text; using Newtonsoft.Json; using System.Security.Cryptography; using System.Text.RegularExpressions; ``` -------------------------------- ### Create Payment Link in Dart Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/examples.md This Dart example shows how to construct a payment request, generate a signature, and send it to the iKhokha API to create a payment link. It includes model definitions for requests and responses, signature generation logic, and error handling. ```dart import 'dart:convert'; import 'package:crypto/crypto.dart'; import 'package:http/http.dart' as http; // Models class PaymentRequest { final String entityID; final String externalEntityID; final int amount; final String currency; final String requesterUrl; final String mode; final String externalTransactionID; final Urls urls; PaymentRequest({ required this.entityID, required this.externalEntityID, required this.amount, required this.currency, required this.requesterUrl, required this.mode, required this.externalTransactionID, required this.urls, }); Map toJson() => { 'entityID': entityID, 'externalEntityID': externalEntityID, 'amount': amount, 'currency': currency, 'requesterUrl': requesterUrl, 'mode': mode, 'externalTransactionID': externalTransactionID, 'urls': urls.toJson(), }; } class Urls { final String callbackUrl; final String successPageUrl; final String failurePageUrl; final String cancelUrl; Urls({ required this.callbackUrl, required this.successPageUrl, required this.failurePageUrl, required this.cancelUrl, }); Map toJson() => { 'callbackUrl': callbackUrl, 'successPageUrl': successPageUrl, 'failurePageUrl': failurePageUrl, 'cancelUrl': cancelUrl, }; } class PaymentResponse { final String paylinkID; final String paymentLink; final String externalTransactionID; final String responseCode; PaymentResponse({ required this.paylinkID, required this.paymentLink, required this.externalTransactionID, required this.responseCode, }); factory PaymentResponse.fromJson(Map json) { return PaymentResponse( paylinkID: json['paylinkID'], paymentLink: json['paylinkUrl'], externalTransactionID: json['externalTransactionID'], responseCode: json['responseCode'], ); } } // Signature generation String generateSignature(String body, String endpoint, String secret) { final uri = Uri.parse(endpoint); final basePath = uri.path; if (basePath.isEmpty) { throw Exception('No basePath in url'); } final sanitizedBody = "$basePath$body".replaceAllMapped( RegExp(r'[\"\\' ' ]'), (match) => '\\${match.group(0)}', ); final key = utf8.encode(secret); final bytes = utf8.encode(sanitizedBody); final hmacSha256 = Hmac(sha256, key); final digest = hmacSha256.convert(bytes); return digest.toString(); } // Create payment link Future createPayLink(PaymentRequest request) async { final apiUrl = "https://api.ikhokha.com/public-api/v1/api/payment"; final appId = "Your App ID here"; final appKey = "Your App Key here"; final payload = jsonEncode(request.toJson()); final signature = generateSignature(payload, apiUrl, appKey); final response = await http.post( Uri.parse(apiUrl), headers: { 'Content-Type': 'application/json', 'IK-APPID': appId, 'IK-SIGN': signature, }, body: payload, ); if (response.statusCode != 200) { throw Exception('Failed to create paylink: ${response.statusCode}'); } print(response.body); return PaymentResponse.fromJson(jsonDecode(response.body)); } // Main void main() async { final requestBody = PaymentRequest( entityID: 'RANDOM1234', externalEntityID: 'ENTITY1234', amount: 10000, currency: 'ZAR', requesterUrl: 'https://example.com/requester', mode: 'live', externalTransactionID: 'TRANS789111', urls: Urls( callbackUrl: 'https://example.com/callback', successPageUrl: 'https://example.com/success', failurePageUrl: 'https://example.com/failure', cancelUrl: 'https://example.com/cancel', ), ); try { print('Creating paylink...'); final response = await createPayLink(requestBody); print('Paylink created: ${response.paymentLink}'); print('Paylink ID: ${response.paylinkID}'); } catch (e) { print('Error creating paylink: $e'); } } ``` -------------------------------- ### Create Payment Link Response Example Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/endpoints.md This JSON object shows a successful response when creating a payment link. It contains the payment link URL and its unique ID. ```json { "responseCode": "0", "message": "Success", "paylinkUrl": "https://payment.ikhokha.com/redirect?id=...", "paylinkID": "abc123def456", "externalTransactionID": "4" } ``` -------------------------------- ### Get Payment Transaction History Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/api-reference/paylink-nodejs.md Retrieves a history of payment transactions within a specified date range. This method is available in the fullstack example. ```javascript async getPaymentHistory(startDate: string, endDate: string): Promise ``` ```javascript try { const history = await payLink.getPaymentHistory("2024-01-01", "2024-01-31"); console.log("Payments:", history); } catch (error) { console.error("Failed to fetch history:", error.message); } ``` -------------------------------- ### Get Payment Link Status by ID Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/api-reference/paylink-nodejs.md Retrieves the current status of a specific payment link using its ID. This method is available in the fullstack example. ```javascript async getStatusById(paylinkID: string): Promise ``` ```javascript try { const status = await payLink.getStatusById("abc123def456"); console.log("Payment status:", status.responseCode); } catch (error) { console.error("Failed to get status:", error.message); } ``` -------------------------------- ### Add Dart Pub Packages Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/configuration.md Install necessary Dart packages for crypto operations (HMAC-SHA256) and HTTP requests. Use 'dart pub get' or 'dart pub add'. ```bash dart pub get # or dart pub add crypto http ``` -------------------------------- ### Build and Run .NET Project Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/api-reference/paylink-csharp.md Commands to build the .NET project and then run the application from the command line. Ensure you have updated your credentials before running. ```bash dotnet build dotnet run ``` -------------------------------- ### GET /api/getStatus/{paylinkID} Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/authentication.md Retrieves the status of a payment using the paylink ID. For GET requests, the signature is computed solely from the URL path. ```APIDOC ## GET /api/getStatus/{paylinkID} ### Description Retrieves the status of a payment link. The signature for this request is generated using only the URL path. ### Method GET ### Endpoint /api/getStatus/{paylinkID} ### Parameters #### Path Parameters - **paylinkID** (string) - Required - The ID of the payment link to check the status for. ### Headers - **IK-APPID** (string) - Required - Your application ID. - **IK-SIGN** (string) - Required - The generated signature. ### Response #### Success Response (200) - **data** (object) - Contains the status of the payment link. #### Response Example ```json { "data": { "status": "completed", "transactionId": "some-transaction-id" } } ``` ``` -------------------------------- ### Run .NET Project Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/c-sharp/README.md Executes the .NET project. Requires the .NET SDK. ```bash dotnet run ``` -------------------------------- ### GET Request Signature in JavaScript Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/authentication.md For GET requests, the signature is computed solely from the URL path. Ensure the path includes the full API prefix. ```javascript const paylinkID = "abc123def456"; const endpoint = `https://api.ikhokha.com/public-api/v1/api/getStatus/${paylinkID}`; // For GET, payload is just the path const path = new URL(endpoint).pathname; // "/public-api/v1/api/getStatus/abc123def456" // const signature = crypto // .HmacSHA256(path, APP_KEY) // .toString(crypto.enc.Hex); // const response = await axios.get(endpoint, { // headers: { // "IK-APPID": APP_ID, // "IK-SIGN": signature // } // }); ``` -------------------------------- ### Build and Execute Go PayLink Application Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/api-reference/paylink-go.md Build the Go application into an executable file named 'paylink' and then run it. This is an alternative to running directly with 'go run'. ```bash go build -o paylink ./paylink ``` -------------------------------- ### Create Project Structure Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/api-reference/paylink-dart.md Bash commands to set up the basic directory structure for a Dart project. ```bash mkdir ik_pay cd ik_pay mkdir models touch main.dart models/payment_models.dart pubspec.yaml ``` -------------------------------- ### Get Payment Status Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/endpoints.md Retrieves the current status of a payment link using its unique identifier. ```APIDOC ## GET /getStatus/{paylinkID} ### Description Retrieves the current status of a payment link. ### Method GET ### Endpoint /getStatus/{paylinkID} ### Parameters #### Path Parameters - **paylinkID** (string) - Required - The unique payment link identifier ### Request Example GET https://api.ikhokha.com/public-api/v1/api/getStatus/abc123def456 ### Response #### Success Response (200) Response structure matches PaymentResponse type (see types.md) ``` -------------------------------- ### Create and Handle Payments with Database Integration Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/api-reference/express-backend.md This pseudocode demonstrates creating a payment link, saving payment details to a database, and handling webhook callbacks to update payment status. ```javascript // Pseudocode app.post("/payment", async (req, res) => { const response = await payLink.createPaylink(req.body); // Save to database await db.payments.insert({ paylinkID: response.paylinkID, externalTransactionID: req.body.externalTransactionID, status: 'pending', amount: req.body.amount, createdAt: new Date() }); res.json(response); }); // Webhook handler app.post("/payment/webhook/callback", async (req, res) => { const { paylinkID, status } = req.body; // Update database await db.payments.update( { paylinkID }, { status } ); res.status(200).send(); }); ``` -------------------------------- ### GET /payment/:id Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/api-reference/express-backend.md Retrieves the current status of a specific payment link using its unique ID. ```APIDOC ## GET /payment/:id ### Description Retrieves the current status of a payment link. ### Method GET ### Endpoint /payment/:id ### Parameters #### Path Parameters - **id** (string) - Required - Payment link ID ### Response #### Success Response (200) - **responseCode** (string) - Response code, "0" indicates success. - **paylinkID** (string) - The unique ID of the paylink. - **externalTransactionID** (string) - The external transaction ID associated with the paylink. #### Response Example { "responseCode": "0", "paylinkID": "abc123def456", "externalTransactionID": "4" } #### Error Response (400) { "error": "Payment link not found or API error" } ``` -------------------------------- ### Initialize PayLink Client (Node.js) Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/QUICK-REFERENCE.md Initialize the PayLink client with API endpoint and credentials for Node.js. ```javascript const payLink = new PayLink({ apiEndPoint: "https://api.ikhokha.com/public-api/v1/api/payment", applicationId: process.env.IK_APP_ID, applicationKey: process.env.IK_APP_SECRET }); ``` -------------------------------- ### GET /payments/history Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/api-reference/express-backend.md Retrieves payment history for a specified date range. Requires startDate and endDate query parameters. ```APIDOC ## GET /payments/history ### Description Retrieves payment history for a date range. ### Method GET ### Endpoint /payments/history ### Parameters #### Query Parameters - **startDate** (string) - Required - Start date (format not specified) - **endDate** (string) - Required - End date (format not specified) ### Request Example ```http GET /payments/history?startDate=2024-01-01&endDate=2024-01-31 HTTP/1.1 ``` ### Response #### Success Response (200) - **paylinkID** (string) - Description - **externalTransactionID** (string) - Description - **amount** (number) - Description - **currency** (string) - Description - **status** (string) - Description #### Response Example ```json [ { "paylinkID": "abc123", "externalTransactionID": "4", "amount": 200, "currency": "ZAR", "status": "completed", ... }, ... ] ``` #### Error Response (400) - **error** (string) - Description of the error #### Error Response Example ```json { "error": "Invalid date range" } ``` ### Status Codes - **200** - History retrieved successfully - **400** - Invalid parameters or API error ``` -------------------------------- ### Go Main Function for PayLink Creation Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/api-reference/paylink-go.md Demonstrates the complete process of creating a payment link using the iKhokha Pay API. This includes constructing the request body, calling the CreatePayLink function, and handling the response. ```go func main() { // 1. Create payment request requestBody := PaymentRequest{ EntityID: "MyEntityID1234", ExternalEntityID: "MARTIANS1234", Amount: 10000, Currency: "ZAR", RequesterUrl: "https://example.com/requester", Mode: "live", ExternalTransactionID: "TRANS789111", Urls: Urls{ CallBackUrl: "https://example.com/callback", SuccessPageUrl: "https://example.com/success", FailurePageUrl: "https://example.com/failure", CancelUrl: "https://example.com/cancel", }, } // 2. Create payment link fmt.Println("Creating paylink...") response, err := CreatePayLink(requestBody) if err != nil { fmt.Println("Error creating paylink:", err) return } // 3. Print result fmt.Println("Paylink created successfully:", response.PaylinkUrl) } ``` -------------------------------- ### Configure API Credentials Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/QUICK-REFERENCE.md Set up environment variables for your iKhokha API credentials and endpoint. ```bash # Create .env file IK_APP_ID="your-app-id" IK_APP_SECRET="your-app-secret" IK_API_URL="https://api.ikhokha.com/public-api/v1/api/payment" ``` -------------------------------- ### Get Payment History Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/QUICK-REFERENCE.md Retrieves a history of payments within a specified date range. Requires authentication headers and date parameters. ```APIDOC ## Get Payment History ### Description Retrieves a list of payment records within a specified date range. This endpoint is useful for reconciliation and auditing purposes. ### Method GET ### Endpoint https://api.ikhokha.com/public-api/v1/api/payments/history ### Headers - **IK-APPID**: Your application ID. - **IK-SIGN**: The HMAC-SHA256 signature of the request. ### Parameters #### Query Parameters - **startDate** (string) - Required - The start date for the history query (format to be specified, e.g., YYYY-MM-DD). - **endDate** (string) - Required - The end date for the history query (format to be specified, e.g., YYYY-MM-DD). ### Response #### Success Response (200) - **Array of payment records**: Each record contains details of a payment. ### Response Example ```json [ { "responseCode": "0", "message": "Success", "paylinkUrl": "https://payment.ikhokha.com/redirect?id=...", "paylinkID": "abc123def456", "externalTransactionID": "order-456" }, { "responseCode": "0", "message": "Success", "paylinkUrl": "https://payment.ikhokha.com/redirect?id=...", "paylinkID": "ghi789jkl012", "externalTransactionID": "order-789" } ] ``` ``` -------------------------------- ### Create Payment Link (C#) Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/QUICK-REFERENCE.md Create a payment link in C#. The actual creation logic is referenced from another file. ```csharp // C# var response = await CreatePaymentLink(); // See example in examples.md Console.WriteLine("Payment URL: " + response.paylinkUrl); ``` -------------------------------- ### Custom Payment Link Creation in C# Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/api-reference/paylink-csharp.md Shows how to create a payment link with custom parameters such as amount, currency, transaction ID, and various URLs for callbacks and redirects. This method requires converting the amount to cents and signing the payload. ```csharp static async Task CreateCustomPaymentLink( string entityID, decimal amountInRands, string transactionID) { var amount = (int)(amountInRands * 100); // Convert to cents var request = new { entityID = entityID, externalEntityID = entityID, amount = amount, currency = "ZAR", requesterUrl = "https://example.com", mode = "live", externalTransactionID = transactionID, urls = new { callbackUrl = "https://example.com/webhook", successPageUrl = "https://example.com/success", failurePageUrl = "https://example.com/failure", cancelUrl = "https://example.com/cancel" } }; var json = JsonConvert.SerializeObject(request); var payload = CreatePayloadToSign(apiEndPoint, json); var signature = SignPayload(payload, ApplicationKey); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("IK-APPID", ApplicationId); client.DefaultRequestHeaders.Add("IK-SIGN", signature); var content = new StringContent(json, Encoding.UTF8, "application/json"); var httpResponse = await client.PostAsync(apiEndPoint, content); var responseBody = await httpResponse.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject(responseBody); } } ``` -------------------------------- ### Loading API Credentials from appsettings.json in C# Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/api-reference/paylink-csharp.md Shows how to configure API credentials (Application ID and Application Key) within the appsettings.json file. This is an alternative to using environment variables for managing secrets. ```json { "IKhokha": { "ApplicationId": "...", "ApplicationKey": "..." } } ``` -------------------------------- ### Check HTTP Status Code for Paylink Creation Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/api-reference/paylink-dart.md Example of checking the HTTP status code of the response to ensure the paylink was created successfully. ```dart if (response.statusCode != 200) { throw Exception('Failed to create paylink'); } ``` -------------------------------- ### Troubleshooting Missing Environment Variables Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/configuration.md Resolve 'Missing required environment variables' errors by verifying the .env file, checking variable names for case sensitivity, and ensuring correct formatting. ```text - Verify .env file exists and is readable - Check variable names match exactly (case-sensitive in some systems) - Ensure no quotes or extra whitespace in variable values ``` -------------------------------- ### Urls toJson Example Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/api-reference/paylink-dart.md Shows the serialization of the Urls object into a Map suitable for JSON encoding. This is used when constructing the request body for the API. ```dart Map toJson() => { 'callbackUrl': callbackUrl, 'successPageUrl': successPageUrl, 'failurePageUrl': failurePageUrl, 'cancelUrl': cancelUrl, } ``` -------------------------------- ### GET /payment/:id Route Implementation Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/api-reference/express-backend.md Retrieves the status of a specific payment link using its ID. The ID is passed as a URL parameter. ```javascript app.get("/payment/:id", async (req, res) => { const paymentId = req.params.id; const response = await payLink.getStatusById(paymentId); res.send(response); }); ``` -------------------------------- ### Build for Production Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/nodejs/pay-api-app/frontend/README.md Compiles and minifies the application for production deployment. This command generates optimized build artifacts. ```sh npm run build ``` -------------------------------- ### PaymentResponse fromJson Example Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/api-reference/paylink-dart.md Demonstrates how to deserialize a JSON response from the API into a PaymentResponse object. Note the mapping from 'paylinkUrl' in JSON to 'paymentLink' in the Dart object. ```dart final jsonResponse = { 'paylinkID': 'abc123', 'paylinkUrl': 'https://payment.ikhokha.com/redirect?... 'externalTransactionID': 'TRANS-12345', 'responseCode': '0' }; final response = PaymentResponse.fromJson(jsonResponse); print(response.paymentLink); // https://payment.ikhokha.com/redirect?... ``` -------------------------------- ### Create .env File for PayLink API Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/api-reference/paylink-go.md Create a .env file to store your API credentials and endpoint URL. This is essential for configuring the Go application to communicate with the Ikhokha PayLink API. ```bash cat > .env << EOF IK_API_URL="https://api.ikhokha.com/public-api/v1/api/payment" IK_APP_ID="your-app-id" IK_APP_SECRET="your-secret-key" EOF ``` -------------------------------- ### Complete Payment Link Request Flow in C# Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/api-reference/paylink-csharp.md Demonstrates the end-to-end process of creating a payment link, checking the response, extracting the payment URL and ID, and handling potential failures. ```csharp // 1. Create payment link var response = await CreatePaymentLink(); // 2. Check response if (response.responseCode == "0") { // 3. Get payment URL string paylinkUrl = response.paylinkUrl; string paylinkID = response.paylinkID; Console.WriteLine($"Payment created: {paylinkID}"); Console.WriteLine($"User URL: {paylinkUrl}"); // 4. Redirect user to paylinkUrl } else { Console.WriteLine($"Failed: {response.responseCode}"); } ``` -------------------------------- ### Environment Variable Configuration for PayLink Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/api-reference/paylink-nodejs.md Shows how to configure the PayLink client using environment variables for API endpoint, application ID, and application key. Requires `dotenv` for loading variables from a `.env` file. ```bash export IK_APP_ID="your-app-id" export IK_APP_KEY="your-app-key" ``` ```javascript import dotenv from "dotenv"; dotenv.config(); const payLink = new PayLink({ apiEndPoint: process.env.IK_API_URL || "https://api.ikhokha.com/public-api/v1/api", applicationId: process.env.IK_APP_ID, applicationKey: process.env.IK_APP_KEY }); ``` -------------------------------- ### Validate Node.js Configuration Source: https://github.com/ikhokha/ik-pay-api-examples/blob/main/_autodocs/configuration.md Use this function to check for the presence of required configuration properties like apiEndPoint, applicationId, and applicationKey before starting your Node.js application. ```javascript const validateConfig = (config) => { if (!config.apiEndPoint) throw new Error("Missing apiEndPoint"); if (!config.applicationId) throw new Error("Missing applicationId"); if (!config.applicationKey) throw new Error("Missing applicationKey"); }; ```