Examples
Next.js Example
Complete example of PayBridge integration with Next.js 14+.
Project Setup
Install Packages
npm install @paybridgejs/khaltiFile Structure
app/
├── api/
│ └── payment/
│ ├── initiate/
│ │ └── route.ts
│ └── verify/
│ └── route.ts
├── success/
│ └── page.tsx
├── layout.tsx
└── page.tsx
lib/
└── payment.ts1. Environment Variables
Create .env.local:
# Khalti
KHALTI_SECRET_KEY=your_khalti_secret_key
# App
NEXT_PUBLIC_BASE_URL=http://localhost:30002. Payment Utilities
Create lib/payment.ts:
import { khalti } from "@paybridgejs/khalti";
export const Khalti = new khalti({
secretKey: process.env.KHALTI_SECRET_KEY!,
});3. API Route: Initiate Payment
Create app/api/payment/initiate/route.ts:
import { NextResponse } from "next/server"
import { Khalti } from "@/lib/khalti"
export async function POST() {
const payment = await Khalti.initiate({
return_url: "http://localhost:3000/success",
website_url: "http://localhost:3000",
amount: 1000,
purchase_order_id: "ORDER-1",
purchase_order_name: "Test Product",
})
console.log("INITIATE RESPONSE:", payment)
return NextResponse.json(payment)
}4. API Route: Verify Payment
Create app/api/payment/verify/route.ts:
import { NextRequest, NextResponse } from "next/server";
import { Khalti } from "@/lib/khalti";
export async function POST(req: NextRequest) {
try {
const body = await req.json();
if (!body?.pidx) {
return NextResponse.json(
{ verified: false, message: "Missing payment ID" },
{ status: 400 },
);
}
const data = await Khalti.verify({ pidx: body.pidx });
if (data.status === "Completed") {
return NextResponse.json({
verified: true,
message: "Payment verified successfully",
status: data.status,
data,
});
}
return NextResponse.json(
{
verified: false,
message: `Payment is ${data.status.toLowerCase()}`,
status: data.status,
data,
},
{ status: 400 },
);
} catch (error) {
console.error("VERIFY ERROR:", error);
return NextResponse.json(
{
verified: false,
message: error instanceof Error ? error.message : "Verification failed",
},
{ status: 400 },
);
}
}
5. Success Page
Create app/success/page.tsx:
"use client";
import { useEffect, useState } from "react";
import { useSearchParams } from "next/navigation";
export default function SuccessPage() {
const searchParams = useSearchParams();
const pidx = searchParams.get("pidx");
const [loading, setLoading] = useState(true);
const [verified, setVerified] = useState(false);
const [message, setMessage] = useState("");
useEffect(() => {
async function verifyPayment() {
try {
if (!pidx) {
setMessage("Missing payment ID");
setLoading(false);
return;
}
const response = await fetch("/api/payment/verify", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ pidx }),
});
const data = await response.json();
if (data.verified) {
setVerified(true);
setMessage(data.message);
} else {
setVerified(false);
setMessage(data.message ?? "Payment verification failed");
}
} catch {
setVerified(false);
setMessage("Something went wrong");
} finally {
setLoading(false);
}
}
verifyPayment();
}, [pidx]);
if (loading) {
return <div>Verifying payment...</div>;
}
return (
<div>
<h1>{verified ? "Payment Successful" : "Payment Failed"}</h1>
<p>{message}</p>
<p>Pidx: {pidx}</p>
</div>
);
}6. Home Page
Create app/page.tsx:
"use client"
export default function HomePage() {
const handlePayment = async () => {
const response = await fetch("/api/payment/initiate", {
method: "POST",
})
const data = await response.json()
window.location.href = data.payment_url
}
return (
<main>
<button
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition"
onClick={handlePayment}>
Pay with Khalti
</button>
</main>
)
}Testing
-
Start the dev server:
npm run dev -
Test payment initiation:
- Visit http://localhost:3000
- Click "Pay with Khalti" button
- Use test credentials (from respective dashboards)
-
Check success page:
- After payment, you'll be redirected to
/success - Payment status will be verified
- After payment, you'll be redirected to
Next Steps
-Working on adding more features and improving documentation. Stay tuned!
- Error Handling - Handle edge cases
- Express Example - Backend framework