The eSewa payment gateway (ePay) takes a few steps to integrate. I walk through each one with a working example: a live demo and the source code. eSewa's own docs are on the eSewa developer site.
The stack
- Hono and the Hono JSX middleware
- htmx as the client-side framework
- eSewa (ePay)
- Drizzle ORM for database access
- React components for frontend rendering
- Tailwind CSS for styling
- Cloudflare D1
- Cloudflare Workers
- Bun, Zod and more
eSewa test credentials
eSewa ID: 9806800001/2/3/4/5
Password: Nepal@123 MPIN: 1122 (for application only)
Token:123456Setting up the backend
I won't go deep into the stack or the setup. I'll stick to the basic routes and the payment flow.
import { Hono } from 'hono';
import schema from '../drizzle';
import CryptoJS from 'crypto-js';
import { drizzle } from 'drizzle-orm/d1';
import Layout from '../components/layout';With the imports in place, set up the app with its webhook and failure routes.
export const secret = '8gBm/:&EnhH.1/q'; // Secret provided by Esewa
const esewa = new Hono();
// Webhook route for payment verification
esewa.post('/webhook', async c => {
return c.json({ result: 'Payment done' });
});
// Handle payment failure
esewa.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.
// Display the payment form
esewa.get('/', async c => {
const db = drizzle(c.env.DB);
const [products] = await db.select().from(schema.products).limit(1);
return c.html(<ESewa products={products} />);
});This is the main route. It renders the payment form, fetching a single product on the server and passing it to the client. In a real app, fetch the actual order from your database instead.
// Payment verification route
esewa.get('/verify', async c => {
const token = c.req.query('data');
if (!token) return c.json({ result: 'Missing token' });
const decodedData = Buffer.from(token, 'base64').toString('utf-8');
const data = JSON.parse(decodedData);
const signedFieldNames = data.signed_field_names.split(',');
const message = signedFieldNames
.map(field => `${field}=${data[field]}`)
.join(',');
const hmac = CryptoJS.HmacSHA256(message, secret);
const signature = CryptoJS.enc.Base64.stringify(hmac);
if (signature === data.signature) {
return c.html(
<Layout>
<h1>Payment Success</h1>
<span>Transaction ID: {data.transaction_uuid}</span>
<span>Status: {data.status}</span>
</Layout>,
);
} else {
return c.json({ result: 'Invalid signature' });
}
});
export default esewa;How payment verification works
After eSewa redirects the user back to the site (through the /verify route), I
check the payment with an HMAC signature. The server verifies the payment
details against eSewa's signature to make sure nothing was tampered with.
Each transaction gets its own unique transaction UUID. The signature is built from the product and transaction details, which ensures the data wasn't modified along the way.
Here is the function that creates the signature:
import CryptoJS from 'crypto-js';
export const createSignature = (data: {
amount: number;
tax_amount: number;
transaction_uuid: string;
product_code: string;
}) => {
const secret = '8gBm/:&EnhH.1/q';
// total_amount,transaction_uuid,product_code
const message = `total_amount=${
data.amount + data.tax_amount
},transaction_uuid=${data.transaction_uuid},product_code=${
data.product_code
}`;
const hmac = CryptoJS.HmacSHA256(message, secret);
const signature = CryptoJS.enc.Base64.stringify(hmac);
return signature;
};Client-side implementation
On the frontend, I render the payment form that submits the required data to the eSewa API, and generate the signature the transaction needs.
export default function Esewa({ products }: { products: ProductType }) {
const url = 'https://api.nischal-dahal.com.np';
const transactionUuid = uuidv4();
const signature = createSignature({
amount: products.price,
tax_amount: Math.floor(products.price * 0.1),
transaction_uuid: transactionUuid,
product_code: 'EPAYTEST',
});
return (
<Layout>
<div>
<br />
<h1 className="mb-6 text-2xl font-bold text-green-500">
Payment With Esewa
</h1>
<form
className="flex w-full max-w-md flex-col gap-4"
action="https://rc-epay.esewa.com.np/api/epay/main/v2/form"
method="post"
>
<div className="flex gap-4">
<label htmlFor="product-name">Name</label>
<h1 id="product-name">{products.name}</h1>
<input
id="transaction_uuid"
name="transaction_uuid"
value={transactionUuid}
/>
<input id="amount" name="amount" value={products.price} />
<input
id="tax_amount"
name="tax_amount"
value={Math.floor(products.price * 0.1)}
/>
<input id="total_amount" name="total_amount" value={110} />
<input id="product_code" name="product_code" value="EPAYTEST" />
<input
id="product_service_charge"
name="product_service_charge"
value={0}
/>
<input
id="product_delivery_charge"
name="product_delivery_charge"
value={0}
readOnly
/>
<input
id="success_url"
name="success_url"
value={`${url}/esewa/verify`}
/>
<input
id="failure_url"
name="failure_url"
value={`${url}/esewa/failure`}
/>
<input
name="signed_field_names"
value="total_amount,transaction_uuid,product_code"
/>
<input name="signature" value={signature} />
</div>
<button type="submit">Submit Payment</button>
<div id="result"></div>
</form>
</div>
<script type="text/template" id="product-template"></script>
</Layout>
);
}Status check
https://uat.esewa.com.np/api/epay/transaction/status/?product_code=EPAYTEST&total_amount=100&transaction_uuid=123