'use client'
import { hostname, khaltiLiveTestKey } from "@/utils/constants";
import { Button } from "@mantine/core";
import axios from "axios";
import Image from 'next/image';
import { usePathname, useSearchParams } from "next/navigation";
import { useEffect } from "react";
export interface KhaltiPaymentProps {
amt: number;
docId: string;
name: string;
onPaymentSuccess?: (tid: string) => void;
}
function KhaltiPayment({
amt,
docId,
name,
onPaymentSuccess
}: KhaltiPaymentProps) {
const pathname = usePathname();
const searchParams = useSearchParams();
let data = {
return_url: hostname + pathname,
purchase_order_id: docId,
purchase_order_name: name,
website_url: hostname,
amount: amt * 100,
}
useEffect(() => {
const pidx = searchParams.get('pidx');
const pid = searchParams.get('purchase_order_id');
if (pidx != null && pid != null) {
verifyPayment(pidx, pid, amt);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [searchParams])
const initiatePayment = () => {
const postUrl = "https://a.khalti.com/api/v2/epayment/initiate/";
axios
.post(postUrl, data,
{
headers: { "Authorization": `Key ${khaltiLiveTestKey}` }
}
)
.then((response) => { window.location.href = (response.data.payment_url) });
}
const verifyPayment = (pidx: string, pid: string, amount: number) => {
const postUrl = "https://a.khalti.com/api/v2/epayment/lookup/"
const data = {
pidx: pidx,
}
axios
.post(postUrl, data,
{
headers: { "Authorization": `Key ${khaltiLiveTestKey}` }
}
)
.then((response) => {
if (response.data.status === "Completed") {
// do something
}
})
}
return (
<Button
fullWidth
variant="outline"
onClick={initiatePayment}
size="lg"
>
Continue with <Image src="/images/khalti.png" alt="khalti" width={100} height={50}
className="object-cover ml-3"
/>
</Button>
);
}
export default KhaltiPayment;