Skip to content

Web Checkout (KPG-2)

This documentation details the process of implementing the latest e-Payment Checkout platform released by Khalti.

How it works?

  • User visits the merchant's website to make some purchase
  • A unique purchase_order_id is generated at merchant's system
  • Payment request is made to Khalti providing the purchase_order_id, amount in paisa and return_url
  • User is redirected to the epayment portal (eg. https://pay.khalti.com)
  • After payment is made by the user, a successful callback is made to the return_url
  • The merchant website can optionally confirm the payment received
  • The merchant website then proceeds other steps after payment confirmation

Getting Started

There is no special installation plugin or SDK required for this provided you are able to make a POST request from your web application. However, we shall come up with handy plugins in coming days.

Tip

A merchant account is required for integration.

Access Information

For Sandbox Access

Signup from here as a merchant.

Please use 987654 as login OTP for sandbox env.

For Production Access

Please visit here

Test Credentials for sandbox environment

Test Khalti ID for 9800000000 9800000001 9800000002 9800000003 9800000004 9800000005

Test MPIN 1111

Test OTP 987654

Demo Flow for Checkout

API Authorization

HTTP Authorization for api requests is done using Auth Keys. Auth Key must be passed in the header for authorization in the following format

{
    "Authorization": "Key <LIVE_SECRET_KEY>"  
}  

Tip

Use live_secret_key from test-admin.khalti.com during sandbox testing and use live_secret_key from admin.khalti.com for production environments.

API Endpoints

API Endpoints

> **Sandbox**

[https://a.khalti.com/api/v2/](https://a.khalti.com/api/v2/)

> **Production**

[https://khalti.com/api/v2/](https://khalti.com/api/v2/)

Initiating a Payment request

Every payment request should be first initiated from the merchant as a server side POST request. Upon success, a unique request identifier is provided called pidx that should be used for any future references

URL Method Authorization Format
/epayment/initiate/ POST Required application/json

JSON Payload Details

Field Required Description
return_url Yes
  • Landing page after the transaction.
  • Field must contain a URL.
website_url Yes
  • The URL of the website.
  • Field must contain a URL.
amount Yes
  • Total payable amount excluding the service charge.
  • Amount must be passed in Paisa
purchase_order_id Yes Unique identifier for the transaction generated by merchant
purchase_order_name Yes This is the name of the product.
customer_info No This field represents to whom the txn is going to be billed to.
amount_breakdown No Any number of labels and amounts can be passed but the sum of amount_breakdown.amount mount be equal to amount.
product_details No No of set is unlimited

Sample Request Payload

{
  "return_url": "https://example.com/payment/",
  "website_url": "https://example.com/",
  "amount": 1300,
  "purchase_order_id": "test12",
  "purchase_order_name": "test",
  "customer_info": {
      "name": "Khalti Bahadur",
      "email": "example@gmail.com",
      "phone": "9800000123"
  },
  "amount_breakdown": [
      {
          "label": "Mark Price",
          "amount": 1000
      },
      {
          "label": "VAT",
          "amount": 300
      }
  ],
  "product_details": [
      {
          "identity": "1234567890",
          "name": "Khalti logo",
          "total_price": 1300,
          "quantity": 1,
   "unit_price": 1300
      }
  ],
  "merchant_username": "merchant_name",
  "merchant_extra": "merchant_extra"
}
Additionally Configuration also accepts attribute starting with merchant_ that can be used to pass additional (meta) data.

  • merchant_name: This is merchant name

  • merchant_extra: This is extra data

The additional data starting with merchant_ is returned in success response payload.

Examples

curl --location 'https://a.khalti.com/api/v2/epayment/initiate/' \
--header 'Authorization: key live_secret_key_68791341fdd94846a146f0457ff7b455' \
--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"
}
}'
<?php
    $curl = curl_init();
    curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://a.khalti.com/api/v2/epayment/initiate/',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS =>'{
    "return_url": "http://example.com/",
    "website_url": "https://example.com/",
    "amount": "1000",
    "purchase_order_id": "Order01",
        "purchase_order_name": "test",

    "customer_info": {
        "name": "Test Bahadur",
        "email": "test@khalti.com",
        "phone": "9800000001"
    }
    }

    ',
    CURLOPT_HTTPHEADER => array(
        'Authorization: key live_secret_key_68791341fdd94846a146f0457ff7b455',
        'Content-Type: application/json',
    ),
    ));

    $response = curl_exec($curl);

    curl_close($curl);
    echo $response;
import requests
import json

url = "https://a.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',
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)
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://a.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);
        }
    }
}
var request = require('request');
var options = {
    'method': 'POST',
    'url': 'https://a.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);
});

Success Response

    {
        "pidx": "bZQLD9wRVWo4CdESSfuSsB",
        "payment_url": "https://test-pay.khalti.com/?pidx=bZQLD9wRVWo4CdESSfuSsB",
        "expires_at": "2023-05-25T16:26:16.471649+05:45",
        "expires_in": 1800
    }

After getting the success response, the user should be redirected to the payment_url obtained in the success response.

Error Responses

return_url is blank

{
    "return_url": [
        "This field may not be blank."
    ],
    "error_key": "validation_error"
}

return_url is invalid

{
    "return_url": [
        "Enter a valid URL."
    ],
    "error_key": "validation_error"
}

website_url is blank

{
    "website_url": [
        "This field may not be blank."
    ],
    "error_key": "validation_error"
}

website_url is invalid

{
    "website_url": [
        "Enter a valid URL."
    ],
    "error_key": "validation_error"
}

Amount is less than 10

{
    "amount": [
        "Amount should be greater than Rs. 1, that is 100 paisa."
    ],
    "error_key": "validation_error"
}

Amount is invalid

{
    "amount": [
        "A valid integer is required."
    ],
    "error_key": "validation_error"
}

purchase_order_id is blank

{
    "purchase_order_id": [
        "This field may not be blank."
    ],
    "error_key": "validation_error"
}

purchase_order_name is blank

{
    "purchase_order_name": [
        "This field may not be blank."
    ],
    "error_key": "validation_error"
}

Amount breakdown doesn't total to the amount passed

{
    "amount": [
        "Amount Breakdown mismatch."
    ],
    "error_key": "validation_error"
}

Payment Success Callback

After the user completes the payment, the success response is obtained in the return URL specified during payment initiate. Sample of success response return URL.

  • The callback url return_url should support GET method
  • User shall be redirected to the return_url with following parameters for confirmation
    • pidx - The initial payment identifier
    • status - Status of the transaction
      • Completed - Transaction is success
      • Pending - Transaction is in pending state, request for lookup API.
      • User canceled - Transaction has been canceled by user.
    • transaction_id - The transaction identifier at Khalti
    • tidx - Same value as transaction id
    • amount - Amount paid in paisa
    • mobile - Payer KHALTI ID
    • purchase_order_id - The initial purchase_order_id provided during payment initiate
    • purchase_order_name - The initial purchase_order_name provided during payment initiate
    • total_amount - Same value as amount
  • There is no further step required to complete the payment, however merchant can process with their own validation and confirmation steps if required
  • It's recommended that during implementation, payment lookup API is checked for confirmation after the redirect callback is received

Sample Callback Request

  • Success transaction callback

    http://example.com/?pidx=bZQLD9wRVWo4CdESSfuSsB
    &txnId=4H7AhoXDJWg5WjrcPT9ixW
    &amount=1000
    &total_amount=1000
    &status=Completed
    &mobile=98XXXXX904
    &tidx=4H7AhoXDJWg5WjrcPT9ixW
    &purchase_order_id=test12
    &purchase_order_name=test
    &transaction_id=4H7AhoXDJWg5WjrcPT9ixW
    

  • Canceled transaction callback

    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
    

Important

  • Please use the lookup API for tha final validation of the transaction.
  • Khalti payment link expires in 60 minutes in production (default).

Payment Verification (Lookup)

After a callback is received, You can use the pidx provided earlier, to lookup and reassure the payment status.

URL Method Authorization Format
/epayment/lookup/ POST Required application/json

Request Data

{
   "pidx": "HT6o6PEZRWFJ5ygavzHWd5"
}

Success Response

{
   "pidx": "HT6o6PEZRWFJ5ygavzHWd5",
   "total_amount": 1000,
   "status": "Completed",
   "transaction_id": "GFq9PFS7b2iYvL8Lir9oXe",
   "fee": 0,
   "refunded": false
}

Pending Response

{
   "pidx": "HT6o6PEZRWFJ5ygavzHWd5",
   "total_amount": 1000,
   "status": "Pending",
   "transaction_id": null,
   "fee": 0,
   "refunded": false
}

Initiated Response

{
   "pidx": "HT6o6PEZRWFJ5ygavzHWd5",
   "total_amount": 1000,
   "status": "Initiated",
   "transaction_id": null,
   "fee": 0,
   "refunded": false
}

Refunded Response

{
   "pidx": "HT6o6PEZRWFJ5ygavzHWd5",
   "total_amount": 1000,
   "status": "Refunded",
   "transaction_id": "GFq9PFS7b2iYvL8Lir9oXe",
   "fee": 0,
   "refunded": true
}

Expired Response

{
   "pidx": "H889Er9gq4j92oCrePrDwf",
   "total_amount": 1000,
   "status": "Expired",
   "transaction_id": null,
   "fee": 0,
   "refunded": false
}

Canceled Response

{
   "pidx": "vNTeXkSEaEXK2J4i7cQU6e",
   "total_amount": 1000,
   "status": "User canceled",
   "transaction_id": null,
   "fee": 0,
   "refunded": false
}

Payment Status Code

Status Status Code
Completed 200
Pending 200
Expired 400
Initiated 200
Refunded 200
User canceled 400
Partially Refunded 200

Lookup Payload Details

Status Description
pidx This is the payment id of the transaction.
total_amount This is the total amount of the transaction
status Completed - Transaction is success
Pending - Transaction is failed or is in pending state
Refunded - Transaction has been refunded
Expired - This payment link has expired
User canceled - Transaction has been canceled by the user
Partially refunded - Transaction has been partially refunded by the user
transaction_id This is the transaction id for the transaction.
This is the unique identifier.
fee The fee that has been set for the merchant.
refunded True - The transaction has been refunded.
False - The transaction has not been refunded.

Lookup status

Field Description
Completed Provide service to user.
Pending Hold, do not provide service. And contact Khalti team.
Refunded Transaction has been refunded to user. Do not provide service.
Expired User have not made the payment, Do not provide the service.
User canceled User have canceled the payment, Do not provide the service.

Important

  • Only the status with Completed must be treated as success.
  • Status Canceled , Expired , Failed must be treated as failed.
  • If any negative consequences occur due to incomplete API integration or providing service without checking lookup status, Khalti won’t be accountable for any such losses.
  • For status other than these, hold the transaction and contact KHALTI team.
  • Payment link expires in 60 minutes in production.

Generic Errors

When an incorrect Authorization key is passed.

{
   "detail": "Invalid token.",
   "status_code": 401
}

If incorrect pidx is passed.

{
   "detail": "Not found.",
   "error_key": "validation_error"
}

If key is not passed as prefix in Authorization key

{
    "detail": "Authentication credentials were not provided.",
    "status_code": 401
}