Examples
Express Example
PayBridge with Express.js
Express Example
Complete PayBridge integration with Express.js.
Project Setup
npm init -y
npm install express @paybridgejs/khalti
npm install -D typescript @types/express ts-nodeSetup Library
Create lib/khalti.ts:
import { khalti } from "@paybridgejs/khalti";
export const Khalti = new khalti({
secretKey: process.env.KHALTI_SECRET_KEY!,
});Complete Server
Create src/server.ts:
import express from "express";
import { Khalti } from "../lib/khalti";
const app = express();
const PORT = 3000;
app.use(express.json());
// Route: Initiate payment
app.post("/api/initiate", async (req, res) => {
try {
const payment = await Khalti.initiate({
amount: 1000,
purchase_order_id: "ORDER-1",
purchase_order_name: "Test Product",
return_url: "http://localhost:3000/success",
website_url: "http://localhost:3000",
});
res.json(payment);
} catch (error) {
console.error("Payment initiation failed:", error);
res.status(500).json({ error: "Payment initiation failed" });
}
});
// Route: Verify payment
app.post("/api/verify", async (req, res) => {
try {
const { pidx } = req.body;
if (!pidx) {
return res.status(400).json({
verified: false,
message: "Missing payment ID",
});
}
const data = await Khalti.verify({ pidx });
if (data.status === "Completed") {
return res.json({
verified: true,
message: "Payment verified successfully",
status: data.status,
data,
});
}
return res.status(400).json({
verified: false,
message: `Payment is ${data.status.toLowerCase()}`,
status: data.status,
data,
});
} catch (error) {
console.error("VERIFY ERROR:", error);
res.status(400).json({
verified: false,
message: error instanceof Error ? error.message : "Verification failed",
});
}
});
// Health check
app.get("/", (req, res) => {
res.json({ status: "OK", message: "PayBridge Express Server" });
});
app.listen(PORT, () => {
console.log(`✅ Server running at http://localhost:${PORT}`);
});Testing with cURL
# Start server
npm run dev
# Initiate payment
curl -X POST http://localhost:3000/api/initiate
# Verify payment
curl -X POST http://localhost:3000/api/verify \
-H "Content-Type: application/json" \
-d '{ "pidx": "your_pidx_here" }'Environment Setup
Create .env:
KHALTI_SECRET_KEY=your_khalti_secret_keyRun Server
npx ts-node src/server.tsNext Steps
- Khalti Integration - Learn more
- Error Handling - Handle errors
- Next.js Example - Frontend integration