Skip to content
Nischal Dahal

Integrating the Khalti payment gateway

How I integrate Khalti Web Checkout into a Hono app, from initiating a payment to verifying it with the lookup API.

September 12, 20246 min read
Open in ClaudeOpen in ChatGPTMarkdown

Khalti's latest ePayment platform, Khalti Web Checkout, takes a few steps to integrate. I walk through each one with a working example: a live demo and the source code. Khalti's own docs are on the Khalti developer site.

First, get a secret key from the Khalti test merchant panel. After signing up, log in. The OTP never arrives in your inbox; use 987654.

The keys look like this:

const khalti_secret = "key xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
const live_public_key = "key xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

Khalti test credentials

 
Test Khalti ID for 980000000(0-5)
 
Test MPIN 1111
 
Test OTP 987654

Setting up the backend

For the eSewa integration, see my previous post.

Start by importing the dependencies.

import { Hono } from "hono";
import { Context } from "../context";
import axios from "axios";
import { requireUser } from "../middlewares/auth/require_user";
import Layout from "../components/layout";
import Khalti from "../pages/khalti";
import { drizzle } from "drizzle-orm/d1";
import schema from "../drizzle";

For TypeScript, these are the interfaces I use for Khalti's responses. Validate them before relying on them, since the Khalti team can change the API.

type KhaltiStatus =
  | "Completed"
  | "Pending"
  | "Initiated"
  | "Refunded"
  | "Expired"
  | "User canceled";
 
export interface KhaltiPaymentResponse {
  pidx: string;
  total_amount: number;
  status: KhaltiStatus;
  transaction_id: string | null;
  fee: number;
  refunded: boolean;
}
 
export interface KhaltiPaymentInitResponse {
  pidx: string;
  payment_url: string;
  expires_at: string;
  expires_in: number;
  go_link: string;
}
 
export interface KhaltiPaymentLookupResponse {
  pidx: string;
  total_amount: number;
  status: KhaltiStatus;
  transaction_id: string | null;
  fee: number;
  refunded: boolean;
}

Use your own merchant secret key.

const secret_key = "Key your_secret_key";

I initiate the payment before the user clicks the pay button. Initiating it after the click works too.

const khalti = new Hono();
 
khalti.get("/", async (c) => {
  const url = "https://api.nischal-dahal.com.np";
  const db = drizzle(c.env.DB);
  const [p1] = await db.select().from(schema.products);
  const amount_in_paisa = p1.price * 100;
 
  const options = {
    method: "POST",
    url: "https://a.khalti.com/api/v2/epayment/initiate/",
    headers: {
      Authorization: secret_key,
      "Content-Type": "application/json",
    },
    data: {
      return_url: `${url}/khalti/verify`,
      website_url: url,
      amount: amount_in_paisa,
      purchase_order_id: "Order01",
      purchase_order_name: p1.name,
      customer_info: {
        name: "Nischal Dahal",
        email: "nischaldahal01395@gmail.com",
        phone: "9800000001",
      },
    },
  };
 
  const response = await axios.request<KhaltiPaymentInitResponse>(options);
  console.log(response.data);
 
  return c.html(
    <Layout>
      <Khalti data={response.data} />
    </Layout>,
  );
});

This is the main route. It fetches a single product on the server, initiates the payment for it and renders the payment page. In a real app, fetch the actual order from your database instead.

Next come the webhook and failure routes.

// Webhook route for payment verification
khalti.post("/webhook", async (c) => {
  // Handle the webhook when Khalti payment completes
  return c.json({ result: "Payment done" });
});
 
// Handle payment failure
khalti.get("/failure", (c) =>
  c.html(
    <Layout>
      <h1>Payment Failed</h1>
      <p>Please try again</p>
    </Layout>,
  ),
);

The webhook route is the place to verify the payment or run any other logic I need after it completes.

// Payment verification route
khalti.get("/verify", async (c) => {
  const pidx = c.req.query("pidx");
 
  const transaction_id = c.req.query("transaction_id");
  const tidx = c.req.query("tidx");
  const amount = c.req.query("amount");
  const total_amount = c.req.query("total_amount");
  const mobile = c.req.query("mobile");
  const status = c.req.query("status");
  const purchase_order_id = c.req.query("purchase_order_id");
 
  // demo for getting all useful parameter so that you can save in db
 
  const lookup = await axios.post<KhaltiPaymentResponse>(
    "https://a.khalti.com/api/v2/epayment/lookup/",
    {
      pidx: pidx,
    },
    {
      headers: {
        Authorization: secret_key,
        "Content-Type": "application/json",
      },
    },
  );
 
  if (lookup.data.status != "Completed") {
    return c.json({ result: "Payment not completed" });
  }
 
  // create a payment record, save data, update status
 
  return c.html(
    <Layout>
      <div>
        <h1>Payment {lookup.data.status}</h1>
        <pre>{JSON.stringify(lookup.data, null, 2)}</pre>
      </div>
    </Layout>,
  );
});

After the user completes the payment, the success response arrives at the return URL set during initiation, with these parameters:

  • pidx: the initial payment identifier
  • status: status of the transaction
    • Completed: the transaction succeeded
    • Pending: the transaction is pending; call the lookup API
    • User canceled: the user canceled the transaction
  • transaction_id: the transaction identifier at Khalti
  • tidx: same value as transaction_id
  • amount: amount paid in paisa
  • mobile: the payer's Khalti ID
  • purchase_order_id: the purchase_order_id sent during initiation
  • purchase_order_name: the purchase_order_name sent during initiation
  • total_amount: same value as amount

After the callback arrives, use the pidx from earlier to look up the payment and confirm its status.

khalti.get("/lookup", async (c) => {
  const token = c.req.query("token");
 
  if (!token) {
    return c.json({ result: "Missing token" });
  }
 
  const response = await axios
    .post<KhaltiPaymentLookupResponse>(
      "https://a.khalti.com/api/v2/epayment/lookup/",
      { pidx: token },
      {
        headers: { Authorization: secret_key },
        "Content-Type": "application/json",
      },
    )
    .then((response) => {
      console.log(response.data);
      return response.data;
    })
    .catch((error) => {
      console.error("Error in Khalti lookup:", error);
      return c.json({ result: "you suck!" });
    });
 
  return c.json({ result: response });
});
 
export default khalti;

How payment verification works

To verify a payment after the callback, call the Payment Lookup API with the pidx received during initiation.

Endpoint: POST /epayment/lookup/. Pass the Authorization header with your live secret key.

Request payload:

{
  "pidx": "<pidx_from_initiation>"
}

Response:

{
  "pidx": "<pidx_from_initiation>",
  "total_amount": 1000,
  "status": "Completed",
  "transaction_id": "<transaction_id_from_initiation>",
  "fee": 0,
  "refunded": false
}

On failure:

{
  "error_key": "invalid_pidx",
  "message": "Invalid pidx provided."
}

Client-side implementation

On the frontend, I render the data from the initiated payment: a button that sends the user to payment_url, plus a few details about the order.

// client
 
export default function Khalti({ data }: { data: KhaltiPaymentInitResponse }) {
  const url = "https://api.nischal-dahal.com.np";
 
  return (
    <Layout>
      <div>
        <h1 className="mb-6 font-bold">Hello, Khalti Web Checkout!</h1>
        <a href={data.go_link}>
          <button class={"rounded border bg-purple-800 px-3 py-2 text-white"}>
            Pay via khalti
          </button>
        </a>
        <pre>
          {JSON.stringify(
            {
              return_url: `${url}/khalti/verify`,
              website_url: url,
              amount: 1000,
              purchase_order_id: "order1",
              purchase_order_name: "Macbook",
              customer_info: {
                name: "Nischal Dahal",
                email: "nischaldahal01395@gmail.com",
                phone: "9800000001",
              },
            },
            null,
            2,
          )}
        </pre>
      </div>
    </Layout>
  );
}