### Install MkDocs Material Theme (Bash) Source: https://github.com/khalti/docs.khalti.com/blob/master/content/contribution.md Installs the 'material' theme for mkdocs, which is used to build the Khalti documentation site. This command requires pip to be installed. ```bash pip install mkdocs-material ``` -------------------------------- ### Python Payment Initiation Example Source: https://context7.com/khalti/docs.khalti.com/llms.txt A server-side example demonstrating payment initiation using Python's requests library. Includes setting up headers, payload, and basic error handling. ```APIDOC ## Python Payment Initiation Example ### Description Server-side payment initiation using Python for backend integration with proper error handling. ### Language Python ### Code ```python import requests import json url = "https://dev.khalti.com/api/v2/epayment/initiate/" payload = json.dumps({ "return_url": "http://example.com/", "website_url": "https://example.com/", "amount": "1000", "purchase_order_id": "Order01", "purchase_order_name": "test", "customer_info": { "name": "Ram Bahadur", "email": "test@khalti.com", "phone": "9800000001" } }) headers = { 'Authorization': 'key live_secret_key_68791341fdd94846a146f0457ff7b455', 'Content-Type': 'application/json', } try: response = requests.request("POST", url, headers=headers, data=payload) result = response.json() print(f"Payment URL: {result['payment_url']}") print(f"Payment IDX: {result['pidx']}") except Exception as e: print(f"Error initiating payment: {e}") ``` ``` -------------------------------- ### PHP Debugging for Plugin Installation Source: https://github.com/khalti/docs.khalti.com/blob/master/content/gotchas.md This snippet allows you to retrieve configuration and predefined variables for debugging issues when installing Khalti plugins. It's useful for checking dependencies, extensions, and potential SSL problems. ```php ``` -------------------------------- ### Node.js Payment Initiation Example Source: https://context7.com/khalti/docs.khalti.com/llms.txt A backend example for initiating payments using Node.js and the 'request' module. Demonstrates how to configure the request with necessary headers and JSON payload. ```APIDOC ## Node.js Payment Initiation Example ### Description Backend payment initiation using Node.js with request module for JavaScript-based servers. ### Language Node.js ### Code ```javascript var request = require('request'); var options = { 'method': 'POST', 'url': 'https://dev.khalti.com/api/v2/epayment/initiate/', 'headers': { 'Authorization': 'key live_secret_key_68791341fdd94846a146f0457ff7b455', 'Content-Type': 'application/json', }, body: JSON.stringify({ "return_url": "http://example.com/", "website_url": "https://example.com/", "amount": "1000", "purchase_order_id": "Order01", "purchase_order_name": "test", "customer_info": { "name": "Ram Bahadur", "email": "test@khalti.com", "phone": "9800000001" } }) }; request(options, function (error, response) { if (error) throw new Error(error); console.log(response.body); }); ``` ``` -------------------------------- ### API Authorization Header Example Source: https://github.com/khalti/docs.khalti.com/blob/master/content/khalti-epayment.md This example shows how to format the Authorization header for API requests. It requires a 'Key' followed by your secret key, which differs between sandbox and production environments. ```json { "Authorization": "Key " } ``` -------------------------------- ### Initiate Payment via Node.js Source: https://github.com/khalti/docs.khalti.com/blob/master/content/khalti-epayment.md Initiates an e-payment transaction using the Khalti API. This example uses the 'request' library to send a POST request with transaction details. It requires 'request' library to be installed. The function takes payment details as input and logs the response body. ```javascript var request = require('request'); var options = { 'method': 'POST', 'url': 'https://dev.khalti.com/api/v2/epayment/initiate/', 'headers': { 'Authorization': 'key live_secret_key_68791341fdd94846a146f0457ff7b455', 'Content-Type': 'application/json', }, body: JSON.stringify({ "return_url": "http://example.com/", "website_url": "https://example.com/", "amount": "1000", "purchase_order_id": "Order01", "purchase_order_name": "test", "customer_info": { "name": "Ram Bahadur", "email": "test@khalti.com", "phone": "9800000001" } }) }; request(options, function (error, response) { if (error) throw new Error(error); console.log(response.body); }); ``` -------------------------------- ### Khalti SDK Public Functions (Conceptual) Source: https://github.com/khalti/docs.khalti.com/blob/master/content/checkout/ios.md Demonstrates the core public functions of the Khalti SDK: `init` for setup, `open` to launch the payment interface, `verify` to check payment status, and `close` to dismiss the payment interface. ```kotlin // val khalti = Khalti.init(Context, KhaltiPayConfig, OnPaymentResult, OnMessage, OnReturn) // khalti.open() // khalti.verify() // khalti.close() ``` -------------------------------- ### Environment Configuration Source: https://context7.com/khalti/docs.khalti.com/llms.txt Guides on setting up Khalti API credentials and base URLs for different environments (sandbox and production). ```APIDOC ## Environment Configuration ### Description This section outlines how to configure your application to interact with the Khalti API, distinguishing between sandbox (testing) and production environments. It includes essential credentials and base URLs. ### Sandbox Environment Configuration For testing purposes, use the sandbox environment. Ensure you obtain the correct test keys from your Khalti developer dashboard. **Environment Variables:** ```bash # Sandbox Environment KHALTI_BASE_URL=https://dev.khalti.com/ KHALTI_SECRET_KEY=test_secret_key_obtained_from_khalti_dashboard KHALTI_PUBLIC_KEY=test_public_key_obtained_from_khalti_dashboard KHALTI_ENVIRONMENT=TEST ``` ### Production Environment Configuration Once your integration is tested and ready for live transactions, switch to the production environment using your live API keys. **Environment Variables:** ```bash # Production Environment KHALTI_BASE_URL=https://khalti.com/ KHALTI_SECRET_KEY=live_secret_key_obtained_from_khalti_dashboard KHALTI_PUBLIC_KEY=live_public_key_obtained_from_khalti_dashboard KHALTI_ENVIRONMENT=LIVE ``` ### Credentials - **Secret Key:** Used for server-side operations and authentication. Keep this key confidential. - **Public Key:** Used for client-side integrations (e.g., JavaScript SDK). It is safe to expose this key. ### Important Notes - Always manage your API keys securely. Avoid hardcoding them directly into your source code. Use environment variables or a secure configuration management system. - Ensure that the `KHALTI_ENVIRONMENT` variable is set correctly to match the environment you are targeting (`TEST` for sandbox, `LIVE` for production). - Refer to the Khalti developer dashboard for the most up-to-date information on obtaining and managing API keys. ``` -------------------------------- ### Serve Khalti Docs Locally (Bash) Source: https://github.com/khalti/docs.khalti.com/blob/master/content/contribution.md Builds and serves the Khalti documentation locally at http://localhost:8000. This command enables live reloading when source files are changed. ```bash mkdocs serve ``` -------------------------------- ### Khalti Payment Success Callback Example Source: https://github.com/khalti/docs.khalti.com/blob/master/content/checkout/diy-banking.md This is an example of a success transaction callback URL from Khalti. The `return_url` should support GET requests and will be appended with payment details for confirmation. Key parameters include `pidx`, `status`, `transaction_id`, `amount`, and `mobile`. Merchants should perform their own validations and are recommended to use the lookup API for final confirmation. ```url http://example.com/?pidx=bZQLD9wRVWo4CdESSfuSsB &txnId=4H7AhoXDJWg5WjrcPT9ixW &amount=10000 &total_amount=10000 &status=Completed &mobile=98XXXXX904 &tidx=4H7AhoXDJWg5WjrcPT9ixW &purchase_order_id=test12 &purchase_order_name=test &transaction_id=4H7AhoXDJWg5WjrcPT9ixW ``` -------------------------------- ### Clone Khalti Docs Repository (Bash) Source: https://github.com/khalti/docs.khalti.com/blob/master/content/contribution.md Clones the Khalti documentation repository fork to your local development machine. Replace with your GitHub username. ```bash git clone git@github.com:/khalti-docs-official-repo.git ``` -------------------------------- ### Initiate Khalti Payment using cURL Source: https://github.com/khalti/docs.khalti.com/blob/master/content/khalti-epayment.md This example demonstrates how to initiate a payment with the Khalti API using cURL. It shows the POST request to the initiation endpoint with the necessary headers (Authorization and Content-Type) and the JSON payload containing payment details. ```bash curl --location 'https://dev.khalti.com/api/v2/epayment/initiate/' \ --header 'Authorization: key 05bf95cc57244045b8df5fad06748dab' \ --header 'Content-Type: application/json' \ --data-raw '{ \ "return_url": "http://example.com/", \ "website_url": "http://example.com/", \ "amount": "1000", \ "purchase_order_id": "Ordwer01", \ "purchase_order_name": "Test", \ "customer_info": { \ "name": "Test Bahadur", \ "email": "test@khalti.com", \ "phone": "9800000001" \ } \ }' ``` -------------------------------- ### Install Khalti SDK using CocoaPods Source: https://github.com/khalti/docs.khalti.com/blob/master/content/checkout/ios.md Add the Khalti SDK to your iOS project by including 'KhaltiCheckout' in your Podfile. This is the primary method for integrating the SDK. ```swift pod 'KhaltiCheckout' ``` -------------------------------- ### Initiate Khalti Payment using C# Source: https://github.com/khalti/docs.khalti.com/blob/master/content/khalti-epayment.md This C# example demonstrates initiating a Khalti API payment using HttpClient. It defines the API URL, constructs the payment payload as an anonymous object, serializes it to JSON, and sets the necessary headers. An asynchronous POST request is made, and the response content is printed. ```csharp using System; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; namespace KhaltiApiExample { class Program { static async Task Main(string[] args) { var url = "https://dev.khalti.com/api/v2/epayment/initiate/"; var payload = new { return_url = "http://example.com/", website_url = "https://example.com/", amount = "1000", purchase_order_id = "Order01", purchase_order_name = "test", customer_info = new { name = "Ram Bahadur", email = "test@khalti.com", phone = "9800000001" } }; var jsonPayload = JsonConvert.SerializeObject(payload); var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json"); var client = new HttpClient(); client.DefaultRequestHeaders.Add("Authorization", "key live_secret_key_68791341fdd94846a146f0457ff7b455"); var response = await client.PostAsync(url, content); var responseContent = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseContent); } } } ``` -------------------------------- ### Initiate Payment via JavaScript (Browser) Source: https://github.com/khalti/docs.khalti.com/blob/master/content/khalti-epayment.md Initiates an e-payment transaction using the Khalti API directly in the browser. This example uses the Fetch API to send a POST request. It opens the payment URL in a new tab upon successful initiation. Ensure valid return_url and website_url are provided. ```javascript function dummyPay() { var myHeaders = new Headers(); myHeaders.append("Authorization", "key live_secret_key_68791341fdd94846a146f0457ff7b455"); myHeaders.append("Content-Type", "application/json"); var raw = JSON.stringify({ "return_url": "https://docs.khalti.com/khalti-epayment/", "website_url": "https://example.com/", "amount": "1000", "purchase_order_id": "Order01", "modes":["KHALTI"], "purchase_order_name": "test", "customer_info": { "name": "Test Bahadur", "email": "test@khalti.com", "phone": "9800000001" } }); var requestOptions = { method: 'POST', headers: myHeaders, body: raw, redirect: 'follow' }; fetch("https://dev.khalti.com/api/v2/epayment/initiate/", requestOptions) .then(result => result.json()) .then(json => window.open(json.payment_url, '_blank')) .catch(error => console.log('error', error)); } ``` -------------------------------- ### Khalti Canceled Transaction Callback Example Source: https://github.com/khalti/docs.khalti.com/blob/master/content/khalti-epayment.md Demonstrates the structure of a callback URL when a user cancels a transaction. This callback includes parameters such as pidx, status (User canceled), and other relevant transaction details. ```URL http://example.com/?pidx=bZQLD9wRVWo4CdESSfuSsB &transaction_id= &tidx= &amount=1000 &total_amount=1000 &mobile= &status=User canceled &purchase_order_id=test12 &purchase_order_name=test ``` -------------------------------- ### Flutter SDK Integration with Dart Source: https://context7.com/khalti/docs.khalti.com/llms.txt Implement cross-platform mobile payment integration using the Khalti Flutter SDK with Dart. This guide covers initializing the SDK with payment configuration, handling payment results, messages, and return URLs through comprehensive callbacks. It also shows how to build a UI element to initiate the payment process. ```dart import 'package:khalti_checkout_flutter/khalti_checkout_flutter.dart'; class KhaltiSDKDemo extends StatefulWidget { const KhaltiSDKDemo({super.key}); @override State createState() => _KhaltiSDKDemoState(); } class _KhaltiSDKDemoState extends State { late final Future khalti; @override void initState() { super.initState(); final payConfig = KhaltiPayConfig( publicKey: '__live_public_key__', pidx: 'bZQLD9wRVWo4CdESSfuSsB', environment: Environment.prod, ); khalti = Khalti.init( enableDebugging: true, payConfig: payConfig, onPaymentResult: (paymentResult, khalti) { log('Payment Status: ${paymentResult.payload?.status}'); log('Transaction ID: ${paymentResult.payload?.transactionId}'); log('Amount: ${paymentResult.payload?.totalAmount}'); khalti.close(context); }, onMessage: ( khalti, { description, statusCode, event, needsPaymentConfirmation, }) async { log('Description: $description, Status Code: $statusCode'); if (needsPaymentConfirmation == true) { await khalti.verify(); } }, onReturn: () => log('Successfully redirected to return_url.'), ); } @override Widget build(BuildContext context) { return FutureBuilder( future: khalti, builder: (context, snapshot) { if (snapshot.hasData) { return ElevatedButton( onPressed: () => snapshot.data!.open(context), child: Text('Pay with Khalti'), ); } return CircularProgressIndicator(); }, ); } } ``` -------------------------------- ### iOS SDK Integration with Swift Source: https://context7.com/khalti/docs.khalti.com/llms.txt Integrate the Khalti iOS SDK using Swift and CocoaPods for native iOS payment processing. This involves adding the pod dependency, initializing the Khalti SDK with configuration details like public key, product ID, and environment, and handling payment results and messages via callbacks. The example shows how to trigger the payment process from a button tap. ```swift // Podfile pod 'KhaltiCheckout' // Swift implementation import KhaltiCheckout class PaymentViewController: UIViewController { var khalti: Khalti? override func viewDidLoad() { super.viewDidLoad() khalti = Khalti.init( config: KhaltiPayConfig( publicKey: "4aa1b684f4de4860968552558fc8487d", pIdx: "8mBsbuzGYDWveAZkMn4Q2F", environment: Environment.TEST ), onPaymentResult: { [weak self] (paymentResult, khalti) in print("Payment Status: (paymentResult.status)") print("Transaction ID: (paymentResult.transactionId)") khalti?.close() }, onMessage: { [weak self] (onMessageResult, khalti) in print("Message: (onMessageResult.message)") let shouldVerify = onMessageResult.needsPaymentConfirmation if shouldVerify { khalti?.verify() } else { khalti?.close() } }, onReturn: { (khalti) in print("Payment completed, return URL loaded") } ) } @IBAction func payButtonTapped(_ sender: UIButton) { khalti?.open() } } ``` -------------------------------- ### Initialize Khalti SDK Source: https://github.com/khalti/docs.khalti.com/blob/master/content/checkout/ios.md Initialize the Khalti SDK with your public key, payment index (pidx), and desired environment (production or test). The initialization includes callbacks for handling payment results, messages, and returns. ```swift Khalti.init(config: KhaltiPayConfig(publicKey:"4aa1b684f4de4860968552558fc8487d", pIdx:"8mBsbuzGYDWveAZkMn4Q2F", environment: Environment.TEST), onPaymentResult: { (paymentResult, khalti) in // Handle payment result }, onMessage: { (onMessageResult, khalti) in // Handle messages }, onReturn: { (khalti) in // Handle return after successful payment }) ``` -------------------------------- ### Initialize Khalti SDK with onReturn Callback (Swift) Source: https://github.com/khalti/docs.khalti.com/blob/master/content/checkout/ios.md Initializes the Khalti SDK with configuration details and defines callbacks for payment results, messages, and returns. The `onReturn` callback is triggered upon successful payment. ```swift khalti = Khalti.init(config: KhaltiPayConfig(publicKey:"4aa1b684f4de4860968552558fc8487d", pIdx:"8mBsbuzGYDWveAZkMn4Q2F",environment:Environment.TEST), onPaymentResult: {[weak self] (paymentResult,khalti) in print("Demo | onPaymentResult", paymentResult) }, onMessage: {[weak self](onMessageResult,khalti) in //Handle onMessage callback here //if needsPaymentConfiramtion true then verify payment status let shouldVerify = onMessageResult.needsPaymentConfirmation if shouldVerify { khalti?.verify() }else{ khalti?.close() } }, onReturn: {(khalti) in // called when payment is success }) ``` -------------------------------- ### Khalti Payment Verification (Lookup) API Initiated Response Example Source: https://github.com/khalti/docs.khalti.com/blob/master/content/checkout/diy-banking.md An 'Initiated' response from the Khalti Payment Verification (Lookup) API. This signifies that the payment process has started but is not yet completed or failed. Similar to the 'Pending' state, `transaction_id` will be null. ```json { "pidx": "HT6o6PEZRWFJ5ygavzHWd5", "total_amount": 10000, "status": "Initiated", "transaction_id": null, "fee": 0, "refunded": false } ``` -------------------------------- ### Initialize KhaltiPayConfig in Kotlin Source: https://github.com/khalti/docs.khalti.com/blob/master/content/checkout/android.md This snippet demonstrates how to create an instance of `KhaltiPayConfig` in Kotlin, which is necessary for setting up the Khalti payment gateway. It requires your public key, payment request ID (pidx), return URL, and the environment (TEST or prod). ```kotlin val config = KhaltiPayConfig( publicKey = "", pidx = "", // returnUrl is optional, can be skipped // returnUrl = "", environment = Environment.TEST ) ``` -------------------------------- ### API Request Examples for Merchant Transactions Source: https://github.com/khalti/docs.khalti.com/blob/master/content/api/transaction_details.md Examples of how to request merchant transaction details using the Khalti API. These examples cover cURL, PHP, Python, and Ruby, demonstrating how to include the authorization header with a secret key. ```bash curl https://khalti.com/api/v2/merchant-transaction// \ -H "Authorization:Key " ``` ```php /"; # Make the call using API. $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $headers = ['Authorization: Key test_secret_key_f59e8b7d18b4499ca40f68195a846e9b']; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // Response $response = curl_exec($ch); $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); ``` ```python import requests url = "https://khalti.com/api/v2/merchant-transaction// headers = { "Authorization": "Key test_secret_key_f59e8b7d18b4499ca40f68195a846e9b" } response = requests.get(url, headers = headers) ``` ```ruby require 'uri' require 'net/http' headers = { Authorization: "Key live_secret_key_fc1207298be544b99fa3ad41c7d7b324" } uri = URI.parse("https://khalti.com/api/v2/merchant-transaction//") https = Net::HTTP.new(uri.host, uri.port) https.use_ssl = true request = Net::HTTP::Get.new(uri.request_uri, headers) response = https.request(request) puts response.body ``` -------------------------------- ### Khalti SDK Initialization Source: https://github.com/khalti/docs.khalti.com/blob/master/content/checkout/ios.md Initializes the Khalti SDK with configuration and callback handlers. This is the first step before using any other Khalti functions. ```APIDOC ## Khalti.init() ### Description Creates an instance of `Khalti`. Use this function to create an object of `Khalti`. ### Method `init` ### Parameters - **Context** (Context) - Required - The Android context. - **KhaltiPayConfig** (KhaltiPayConfig) - Required - Configuration object for Khalti payment. - **OnPaymentResult** (OnPaymentResult) - Required - Callback for payment result. - **OnMessage** (OnMessage) - Required - Callback for messages during the payment process. - **OnReturn** (OnReturn) - Optional - Callback for when the payment is returned. ### Request Example ```swift val khalti = Khalti.init(context, khaltiPayConfig, onPaymentResult, onMessage, onReturn) ``` ``` -------------------------------- ### Khalti SDK Initialization Source: https://github.com/khalti/docs.khalti.com/blob/master/content/checkout/android.md This section details how to initialize the Khalti SDK, including two methods: one with an 'onReturn' callback and one without. It covers the necessary parameters for configuration. ```APIDOC ## Khalti SDK Initialization ### Description Initializes the Khalti SDK with the provided configuration and callbacks. ### Methods #### `init(Context, KhaltiPayConfig, OnPaymentResult, OnMessage, OnReturn)` Creates an instance of `Khalti`. **Parameters:** - `Context` (Context) - Required - The Android context. - `KhaltiPayConfig` (KhaltiPayConfig) - Required - Configuration object including public key, pidx, and environment. - `OnPaymentResult` (Function) - Required - Callback for payment result. - `OnMessage` (Function) - Required - Callback for messages. - `OnReturn` (Function) - Optional - Callback for return events. ### Request Example (With onReturn) ```kotlin val khalti = Khalti.init( LocalContext.current, KhaltiPayConfig( publicKey = "", pidx = "", environment = Environment.TEST // Or Environment.Prod for production ), onPaymentResult = { paymentResult, khalti -> // Your implementation }, onMessage = { payload, khalti -> // Your implementation }, onReturn = { khalti -> // Your implementation } ) ``` ### Request Example (Without onReturn) ```kotlin val khalti = Khalti.init( LocalContext.current, KhaltiPayConfig( publicKey = "", pidx = "", environment = Environment.TEST // Or Environment.Prod for production ), onPaymentResult = { paymentResult, khalti -> // Your implementation }, onMessage = { payload, khalti -> // Your implementation } ) ``` ``` -------------------------------- ### Khalti Payment Verification (Lookup) API Refunded Response Example Source: https://github.com/khalti/docs.khalti.com/blob/master/content/checkout/diy-banking.md This example shows a 'Refunded' status response from the Khalti Payment Verification (Lookup) API. It indicates that a refund has been processed for the transaction. The `refunded` flag will be true, and a valid `transaction_id` may be present. ```json { "pidx": "HT6o6PEZRWFJ5ygavzHWd5", "total_amount": 10000, "status": "Refunded", "transaction_id": "GFq9PFS7b2iYvL8Lir9oXe", "fee": 0, "refunded": true } ``` -------------------------------- ### Khalti Canceled Transaction Callback Example Source: https://github.com/khalti/docs.khalti.com/blob/master/content/checkout/diy-banking.md This example illustrates a canceled transaction callback URL from Khalti. Similar to success callbacks, the `return_url` will be appended with relevant parameters. In this case, the `status` indicates 'User canceled', and fields like `transaction_id` and `mobile` might be empty. It's crucial to use the lookup API for definitive transaction status verification. ```url http://example.com/?pidx=bZQLD9wRVWo4CdESSfuSsB &transaction_id= &tidx= &amount=10000 &total_amount=10000 &mobile= &status=User canceled &purchase_order_id=test12 &purchase_order_name=test ``` -------------------------------- ### Initialize Khalti SDK with onReturn Callback (Kotlin) Source: https://github.com/khalti/docs.khalti.com/blob/master/content/checkout/android.md Initializes the Khalti SDK with payment configuration and defines callbacks for payment results, messages, and return events. This method includes the `onReturn` callback for handling return actions after payment. ```kotlin val khalti = Khalti.init( LocalContext.current, KhaltiPayConfig( publicKey = "", pidx = "", environment = Environment.TEST // Or Environment.Prod for production ), onPaymentResult = { paymentResult, khalti -> // Your implementation }, onMessage = { payload, khalti -> // Your implementation }, onReturn = { khalti -> // Your implementation } ) ``` -------------------------------- ### GET /api/v2/merchant-transaction/{idx}/ Source: https://github.com/khalti/docs.khalti.com/blob/master/content/api/transaction_details.md Fetches the details of a specific merchant transaction identified by its unique index. ```APIDOC ## GET /api/v2/merchant-transaction/{idx}/ ### Description Retrieves the detailed information for a specific payment transaction made to a merchant. ### Method GET ### Endpoint `/api/v2/merchant-transaction//` ### Parameters #### Path Parameters - **idx** (string) - Required - The unique identifier of the transaction. #### Query Parameters None #### Request Body None ### Request Example ```bash curl https://khalti.com/api/v2/merchant-transaction// \ -H "Authorization: Key " ``` ### Response #### Success Response (200) - **idx** (string) - Unique identifier for the transaction. - **type** (object) - Information about the transaction type. - **idx** (string) - Unique identifier for the transaction type. - **name** (string) - Name of the transaction type (e.g., "Wallet payment"). - **state** (object) - Information about the transaction state. - **idx** (string) - Unique identifier for the transaction state. - **name** (string) - Name of the transaction state (e.g., "Completed"). - **template** (string) - A template string for the state (e.g., "is complete"). - **amount** (integer) - The total amount of the transaction. - **fee_amount** (integer) - The fee amount associated with the transaction. - **created_on** (string) - The timestamp when the transaction was created. - **can_refund** (boolean) - Indicates if the transaction can be refunded. - **can_complete** (boolean) - Indicates if the transaction can be marked as complete. - **ebanker** (object|null) - Information about the e-banker, if applicable. - **user** (object) - Information about the user making the payment. - **idx** (string) - Unique identifier for the user. - **name** (string) - Name of the user. - **mobile** (string) - Mobile number of the user. - **merchant** (object) - Information about the merchant receiving the payment. - **idx** (string) - Unique identifier for the merchant. - **name** (string) - Name of the merchant. - **mobile** (string) - Mobile number or email of the merchant. - **refunded** (boolean) - Indicates if the transaction has been refunded. - **child_transactions** (array) - An array of sub-transactions, such as fees. - (object) - Details of a child transaction (same structure as main transaction). - **meta** (object|null) - Additional metadata related to the transaction. - **product_identity** (string) - Identifier for the product associated with the transaction. - **product_name** (string) - Name of the product. - **product_url** (string) - URL of the product. #### Response Example ```json { "idx": "xeR2tuRqEvBLmeJcZzMb5U", "type": { "idx": "2jwzDS9wkxbkDFquJqfAEC", "name": "Wallet payment" }, "state": { "idx": "DhvMj9hdRufLqkP8ZY4d8g", "name": "Completed", "template": "is complete" }, "amount": 3000, "fee_amount": 90, "created_on": "2018-04-16T17:04:05.204629+05:45", "can_refund": true, "can_complete": false, "ebanker": null, "user": { "idx": "aVPXfJQ8HMYKhAePAU6pg5", "name": "Test User", "mobile": "98XXXXXXX9" }, "merchant": { "idx": "UM75Gm2gWmZvA4TPwkwZye", "name": "Test Merchant", "mobile": "testmerchant@khalti.com" }, "refunded": false, "child_transactions": [ { "idx": "uUx2Ead8qqDuRufYh8vsYj", "type": { "idx": "YpwbDVqAnH42odGZmT5vZ8", "name": "Fee" }, "state": { "idx": "DhvMj9hdRufLqkP8ZY4d8g", "name": "Completed", "template": "is complete" }, "amount": 90, "fee_amount": 0, "created_on": "2018-07-19T12:31:55.620318+05:45", "can_refund": true, "can_complete": false, "ebanker": null, "user": { "idx": "UM75Gm2gWmZvA4TPwkwZye", "name": "Test Merchant", "mobile": "testmerchant@khalti.com" }, "merchant": { "idx": "9dUzuqrLetWo9VY3fNwB2E", "name": "", "mobile": "wallet@khalti.com" }, "refunded": false, "child_transactions": [], "meta": null } ], "meta": { "product_identity": "369121518", "product_name": "Test Product", "product_url": "http://testproduct.com/wiki/khalti" } } ``` ``` -------------------------------- ### GET /api/v5/bank/ Source: https://github.com/khalti/docs.khalti.com/blob/master/content/checkout/diy-banking.md Retrieves a list of available banks for e-banking or mobile banking payments. Supports filtering by payment type. ```APIDOC ## GET /api/v5/bank/ ### Description This API provides the bank list for e-banking and mobile banking checkout. ### Method GET ### Endpoint `https://khalti.com/api/v5/bank/` ### Query Parameters - **payment_type** (string) - Required - Specifies the payment type. Use `ebanking` for e-banking or `mobilecheckout` for mobile banking. ### Authorization Not Required ### Response #### Success Response (200) - **total_pages** (integer) - Total number of pages available. - **total_records** (integer) - Total number of records (banks). - **next** (string|null) - URL for the next page of results, or null if none. - **previous** (string|null) - URL for the previous page of results, or null if none. - **record_range** (array) - Array containing the start and end record numbers for the current page. - **current_page** (integer) - The current page number. - **records** (array) - An array of bank objects, each containing: - **idx** (string) - Unique identifier for the bank. - **name** (string) - The full name of the bank. - **short_name** (string) - A short name or abbreviation for the bank. - **logo** (string) - URL of the bank's logo. - **swift_code** (string) - The SWIFT code of the bank. - **has_cardpayment** (boolean) - Indicates if the bank supports card payments. - **address** (string) - The address of the bank's main branch. - **ebanking_url** (string) - URL for the bank's e-banking portal (if applicable). - **has_ebanking** (boolean) - Indicates if the bank supports e-banking. - **has_mobile_checkout** (boolean) - Indicates if the bank supports mobile checkout. - **has_direct_withdraw** (boolean) - Indicates if the bank supports direct withdrawals. - **has_nchl** (boolean) - Indicates if the bank is integrated with NCHL. - **has_mobile_banking** (boolean) - Indicates if the bank supports mobile banking. - **play_store** (string) - URL to the bank's Android app on the Play Store. - **app_store** (string) - URL to the bank's iOS app on the App Store. - **branches** (array) - An array of branch details (currently empty). ### Response Example ```json { "total_pages": 1, "total_records": 14, "next": null, "previous": null, "record_range": [1, 14], "current_page": 1, "records": [ { "idx": "UZmPqTDkdhKmukdZe2gVWZ", "name": "Agricultural Development Bank Limited", "short_name": "ADBL", "logo": "https://khalti-static.s3.ap-south-1.amazonaws.com/media/bank-logo/adbl.png", "swift_code": "ADBLNPKA", "has_cardpayment": false, "address": "Singhadurbar, Kathmandu", "ebanking_url": "", "has_ebanking": true, "has_mobile_checkout": true, "has_direct_withdraw": true, "has_nchl": false, "has_mobile_banking": false, "play_store": "", "app_store": "", "branches": [] } ] } ``` ``` -------------------------------- ### Initialize Khalti SDK with Callbacks in Kotlin Source: https://github.com/khalti/docs.khalti.com/blob/master/content/checkout/android.md This snippet shows how to initialize the Khalti SDK using the `Khalti.init` function in Kotlin. It takes the Android context, the `KhaltiPayConfig` object, and callback functions for handling payment results (`onPaymentResult`), messages (`onMessage`), and return events (`onReturn`). The `onReturn` callback is optional. ```kotlin Khalti.init( LocalContext.current, // context config, onPaymentResult = { paymentResult, khalti -> // your implementation here }, onMessage = { payload, khalti -> // your implementation here }, onReturn = { khalti -> // your implementation here } ) ``` -------------------------------- ### GET /api/v2/payment/status/ Source: https://github.com/khalti/docs.khalti.com/blob/master/content/api/transaction_status.md Retrieves the status of a Khalti transaction. Merchants can use this endpoint to check if a transaction was completed, failed, or is in another state. ```APIDOC ## GET /api/v2/payment/status/ ### Description Retrieves the status of a Khalti transaction. Merchants can use this endpoint to check if a transaction was completed, failed, or is in another state. ### Method GET ### Endpoint https://khalti.com/api/v2/payment/status/ ### Parameters #### Query Parameters - **token** (string) - Required - Token or idx given by Khalti after payment confirmation. - **amount** (integer) - Required - Amount (in paisa) with which payment was initiated. #### Headers - **Authorization** (string) - Required - Test or live secret key in the form `Key ` ### Request Example Assuming the token/idx that we received is `XPPrDcwtHUg4UQbWEnxRzA`. ```python import requests url = "https://khalti.com/api/v2/payment/status/" params = { "token": "XPPrDcwtHUg4UQbWEnxRzA", "amount": 1000 } headers = { "Authorization": "Key test_secret_key_f59e8b7d18b4499ca40f68195a846e9b" } response = requests.get(url, params, headers = headers) ``` ### Response #### Success Response (200) - **status** (boolean) - Indicates the success status of the operation. - **detail** (string) - Provides a detailed message about the transaction state. - **state** (string) - The current state of the transaction (e.g., 'Complete', 'Initiated', 'Confirmed', 'Refunded', 'Partially refunded', 'Failed'). #### Response Example ```json { "status": true, "detail": "Transaction complete.", "state": "Complete" } ``` #### Error Response - **status** (boolean) - Always false for error states. - **state** (string) - The error state of the transaction (e.g., 'Error', 'Failed'). - **detail** (string) - A message describing the error (e.g., 'Transaction not found', 'Transaction failed.'). #### Error Response Example (Transaction Not Found) ```json { "status": false, "state": "Error", "detail": "Transaction not found" } ``` #### Error Response Example (Failed State) ```json { "status": false, "detail": "Transaction failed.", "state": "Failed" } ``` ```