Skip to content
Rijan Bhattarai

eSewa and Khalti integration in Next.js (2026): start, pay, verify

By · · 9 min read

eSewa and Khalti are the two payment wallets most Nepali online stores add first. This guide shows how to connect both to a Next.js App Router site, with every request and check done on the server.

Short answer: For eSewa and Khalti integration in Next.js, start each payment on the server and send the buyer to the gateway. Then confirm the payment with the gateway's own status API before you mark the order paid. Every detail below was checked against the official eSewa and Khalti docs in November 2026.

How eSewa and Khalti payments work in Next.js

Both gateways follow the same three steps, even though their APIs look different. Your server starts the payment, the buyer pays on the gateway's page, and your server confirms the result.

Step eSewa ePay v2 Khalti ePayment (KPG-2)
Start Signed HTML form POST to eSewa Server POST to the initiate API
Buyer pays On the eSewa login page On the payment_url Khalti returns
Return Success URL with Base64 data Return URL with pidx and status
Confirm Status check API Lookup API
Amount unit Rupees Paisa (NPR 10 is 1000)

The rest of this guide covers each gateway in turn, then the mistakes behind most failed orders. The code uses Next.js 16 route handlers and the crypto module built into Node.js, so you need no extra package.

eSewa ePay v2 integration in Next.js

eSewa ePay v2 works with a signed form that the buyer's browser sends to eSewa. Your server signs it with your secret key, so the key never reaches the browser.

Test details from the eSewa docs

eSewa publishes shared test values for its UAT environment, which is its name for the testing server. Use them until eSewa gives you your own code and key.

Setting Testing (UAT) Live
Form URL https://rc-epay.esewa.com.np/api/epay/main/v2/form https://epay.esewa.com.np/api/epay/main/v2/form
Status URL https://rc.esewa.com.np/api/epay/transaction/status/ https://esewa.com.np/api/epay/transaction/status/
Product code and key EPAYTEST with key 8gBm/:&EnhH.1/q Issued by eSewa
Test buyer eSewa ID 9711111111 (or ending 2 or 3), password Nepal@123 Real buyer accounts
MPIN and token MPIN 1122, token 123456 Sent to the buyer

Sign the payment request

The signature is an HMAC SHA256 hash of a short message, and you send it encoded as Base64. You sign three fields in a fixed order: total_amount, transaction_uuid and product_code, joined as key=value pairs with commas.

// lib/esewa.ts
import { createHmac } from "node:crypto";

export function esewaSign(message: string) {
  return createHmac("sha256", process.env.ESEWA_SECRET_KEY!).update(message).digest("base64");
}

export function esewaFields(order: { id: string; amount: number }) {
  const total = String(order.amount);
  const fields = {
    amount: total,
    tax_amount: "0",
    product_service_charge: "0",
    product_delivery_charge: "0",
    total_amount: total,
    transaction_uuid: order.id, // letters, numbers and hyphens only
    product_code: process.env.ESEWA_PRODUCT_CODE!,
    success_url: `${process.env.SITE_URL}/api/esewa/success`,
    failure_url: `${process.env.SITE_URL}/checkout?failed=esewa`,
    signed_field_names: "total_amount,transaction_uuid,product_code",
  };
  const message = `total_amount=${total},transaction_uuid=${order.id},product_code=${fields.product_code}`;
  return { ...fields, signature: esewaSign(message) };
}

Every field must be sent, so send 0 for tax and charges you do not use. The total_amount must equal the amount plus tax, service charge and delivery charge. The docs also allow up to three optional properties[name] fields if you want to pass extra data.

Send the buyer to eSewa

Put the fields in hidden inputs inside a form that posts to the eSewa form URL. A Server Component can build the fields, so the signing still happens on your server.

// app/checkout/esewa/page.tsx
import { esewaFields } from "@/lib/esewa";

export default async function EsewaCheckout() {
  const order = await getPendingOrder(); // your own data function
  const fields = esewaFields({ id: order.id, amount: order.total });
  return (
    <form action={process.env.ESEWA_FORM_URL} method="POST">
      {Object.entries(fields).map(([name, value]) => (
        <input key={name} type="hidden" name={name} value={value} />
      ))}
      <button type="submit">Pay with eSewa</button>
    </form>
  );
}

Verify the eSewa response on the server

After payment, eSewa sends the buyer to your success URL with the result encoded in Base64, inside a data query parameter. Decode it and check its signature, then confirm the payment with the status API before you trust it.

// app/api/esewa/success/route.ts
import { esewaSign } from "@/lib/esewa";

export async function GET(req: Request) {
  const data = new URL(req.url).searchParams.get("data") ?? "";
  const body = JSON.parse(Buffer.from(data, "base64").toString("utf8"));
  const message = body.signed_field_names
    .split(",")
    .map((k: string) => `${k}=${body[k]}`)
    .join(",");
  if (esewaSign(message) !== body.signature) return new Response("Bad signature", { status: 400 });

  const order = await getOrder(body.transaction_uuid);
  const check = new URL(process.env.ESEWA_STATUS_URL!);
  check.search = new URLSearchParams({
    product_code: process.env.ESEWA_PRODUCT_CODE!,
    total_amount: String(order.total),
    transaction_uuid: order.id,
  }).toString();
  const status = await (await fetch(check, { cache: "no-store" })).json();

  if (status.status === "COMPLETE") await markPaid(order.id, status.ref_id);
  return Response.redirect(new URL(`/orders/${order.id}`, req.url), 303);
}

The status check URLs for testing and for live payments are in the table at the top of this section. Only the COMPLETE status means the money has really reached your merchant wallet.

The other statuses each need their own handling in your order code. PENDING means the buyer started the payment but never finished it on eSewa. NOT_FOUND means the eSewa session expired, and CANCELED means eSewa reversed the payment on its side. AMBIGUOUS means the payment is stuck in between, so hold the order and check again later.

Khalti ePayment integration in Next.js

Khalti's ePayment API starts on your server, which makes it a little simpler than eSewa. You post the order to Khalti, get back a payment link, and redirect the buyer to it.

Test details from the Khalti docs

Khalti runs a separate sandbox with its own merchant dashboard and test accounts. Sign up as a test merchant at test-admin.khalti.com to get a sandbox secret key.

Setting Sandbox Live
API base https://dev.khalti.com/api/v2/ https://khalti.com/api/v2/
Merchant dashboard test-admin.khalti.com admin.khalti.com
Test Khalti IDs 9800000000 to 9800000005 Real buyer accounts
Test MPIN and OTP MPIN 1111, OTP 987654 Sent to the buyer

Start a Khalti payment

Send a POST request to epayment/initiate/ with your secret key in the Authorization header. The amount is always in paisa, so a NPR 500 order is sent to Khalti as 50000.

// app/api/khalti/start/route.ts
export async function POST(req: Request) {
  const order = await getPendingOrder();
  const res = await fetch(`${process.env.KHALTI_API}epayment/initiate/`, {
    method: "POST",
    headers: { Authorization: `Key ${process.env.KHALTI_SECRET_KEY}`, "Content-Type": "application/json" },
    body: JSON.stringify({
      return_url: `${process.env.SITE_URL}/api/khalti/return`,
      website_url: process.env.SITE_URL,
      amount: order.total * 100, // paisa
      purchase_order_id: order.id,
      purchase_order_name: order.title,
    }),
  });
  if (!res.ok) return Response.json(await res.json(), { status: 400 });
  const { pidx, payment_url } = await res.json();
  await savePidx(order.id, pidx);
  return Response.redirect(payment_url, 303);
}

Khalti rejects any amount of NPR 10 or less, so run your tests with a slightly bigger order. You can also send customer_info, amount_breakdown and product_details if you want them shown on the payment page.

Confirm the Khalti payment with lookup

Khalti sends the buyer back to your return_url with pidx, status, transaction_id and the amount in the query string. Treat those values as a hint only, then call the lookup API with the pidx to get the real status.

// app/api/khalti/return/route.ts
export async function GET(req: Request) {
  const pidx = new URL(req.url).searchParams.get("pidx") ?? "";
  const res = await fetch(`${process.env.KHALTI_API}epayment/lookup/`, {
    method: "POST",
    headers: { Authorization: `Key ${process.env.KHALTI_SECRET_KEY}`, "Content-Type": "application/json" },
    body: JSON.stringify({ pidx }),
    cache: "no-store",
  });
  const result = await res.json();
  const order = await getOrderByPidx(pidx);

  if (result.status === "Completed" && result.total_amount === order.total * 100) {
    await markPaid(order.id, result.transaction_id);
  }
  return Response.redirect(new URL(`/orders/${order.id}`, req.url), 303);
}

Khalti's docs say that only the Completed status counts as a successful payment. You should treat Expired and User canceled as failed payments and release the order. Pending and Initiated should be held, and Khalti's support team can confirm what happened.

Common eSewa and Khalti integration mistakes

Most broken checkouts in Nepal come from the same few small errors in the code. Each one below causes either lost orders or orders marked paid without any money.

  1. Trusting the success page: anyone can open a success URL by hand, so always confirm with the status or lookup API first.
  2. Mixing rupees and paisa: eSewa takes rupees and Khalti takes paisa, so a missing * 100 charges 1% of the price.
  3. Not checking the amount: compare the confirmed amount with your saved order total, not with a value from the URL.
  4. Reusing transaction IDs: eSewa needs a new transaction_uuid and Khalti a new purchase_order_id for every attempt.
  5. Leaving test URLs in production: keep every gateway URL and key in environment variables, and switch them all together at launch.
  6. Skipping pending orders: run a scheduled job that rechecks pending and ambiguous payments, because buyers sometimes close the tab early.

Keep both secret keys in server-only environment variables on your hosting platform. Never prefix them with NEXT_PUBLIC_, because that copies them into the JavaScript that every visitor downloads.

Going live with eSewa and Khalti

You need a merchant account with each gateway before you can take real money. The eSewa team then issues your live product code and your own secret key. Khalti issues a live secret key in its admin.khalti.com dashboard.

Before launch, run one full test order through each gateway in its test environment. Then swap the URLs and keys, place one small real order, and refund it. That one real order proves that the live keys, the redirects and your order updates all work.

If you sell through a store builder instead, check whether it has an official eSewa and Khalti plugin first. My e-commerce website service covers stores where these payments are built in and tested for you. You can also see what online stores cost in the website cost guide for Nepal.

Frequently asked questions

Do I need both eSewa and Khalti on my store?

Offering both wallets is the safer choice for most online stores in Nepal. Some buyers keep money in only one wallet, and a missing option can mean a lost sale. Both gateways follow the same start, pay and confirm pattern, so adding the second one takes far less work than the first.

Can I test eSewa and Khalti without real money?

Yes. eSewa has a UAT environment with the shared product code EPAYTEST and a public test account. Khalti has a sandbox at dev.khalti.com with test Khalti IDs, an MPIN and an OTP. Neither test environment moves real money, so you can repeat payments as often as you need.

Why does my Khalti payment fail with an amount error?

The most common cause is sending the amount in rupees instead of paisa. Khalti expects paisa, so multiply the rupee total by 100 before you send it. Khalti also rejects payments of NPR 10 or less, which catches many developers who test with tiny amounts.

Can I accept eSewa and Khalti without a backend?

You cannot do it safely without some server code. The eSewa signature needs your secret key, and Khalti's initiate and lookup calls need your secret key too. Next.js route handlers give you that backend inside the same project, so you do not need a separate server for it.

Sources: eSewa ePay developer docs and Khalti ePayment docs, both checked on 28 November 2026.