Skip to content

Khalti Payment Gateway Integration Guide

Published: at 12:00 AM (2 min read)

Khalti Payment Gateway Integration Guide

Khalti provides payment gateway for web and SDKs for mobile application.

Prerequisites

Before starting the integration, you’ll need:

Merchant Account

API Key

Get it from your Khalti merchant dashboard (sandbox/production).

Step 1: Initiate Payment Request

Send a POST request to Khalti’s API to start the payment process.

API Endpoints

Required Headers

You also have to have a extra headers, ‘Authorization’ whose value would be: key <your_secret_key>

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

Request Body Structure

And the body should have following structure and values:

{
  "return_url": "https://your-website.com/payment-success",
  "website_url": "https://your-website.com",
  "amount": 1000,
  "purchase_order_id": "ORDER123",
  "purchase_order_name": "T-Shirt",
  "customer_info": {
    "name": "John Doe",
    "email": "john@example.com",
    "phone": "9800000000"
  },
  "merchant_name": "Your Store Name",
  "merchant_extra": "Additional metadata (optional)"
}

Field Explanations

Successful Response

If the request is successful, we get the following response:

{
  "pidx": "unique-payment-id",
  "payment_url": "https://pay.khalti.com/?pidx=...",
  "expires_at": "2023-12-31T23:59:59"
}

Step 2: Handle Payment Callback

After the post request is sent to payment_url and if the payment succeeds then khalti redirects user to above’s return_url with following get parameters:

Step 3: Verify Payment (Mandatory Step)

Use the Lookup API to confirm the payment status using the pidx.

API Endpoints

Verification Request

{
  "pidx": "unique-payment-id-from-callback"
}

Successful Verification Response

{
  "pidx": "unique-payment-id",
  "total_amount": 1000,
  "status": "Completed",
  "transaction_id": "GFq9PFS7b2iYvL8Lir90Xe",
  "fee": 0,
  "refunded": false
}

Summary

The Khalti payment integration process involves three main steps:

  1. Initiate Payment: Send POST request with payment details
  2. Handle Callback: Process the redirect from Khalti with payment status
  3. Verify Payment: Confirm the payment status using the Lookup API

This verification step is crucial for security and ensures that the payment was actually completed successfully.


Previous Post
How does Promise.all() work?
Next Post
A Beginner’s Guide to Git for Everyday Use