add payment and integration with midtrans
This commit is contained in:
@@ -3,6 +3,8 @@
|
||||
import { getServerSession } from "next-auth";
|
||||
import { authOptions } from "@/lib/auth";
|
||||
import { tripService } from "@/server/services/trip.service";
|
||||
import { paymentService } from "@/server/services/payment.service";
|
||||
import { bookingService } from "@/server/services/booking.service";
|
||||
import { revalidatePath } from "next/cache";
|
||||
|
||||
export async function markParticipantPaidAction(tripId: string) {
|
||||
@@ -23,6 +25,51 @@ export async function markParticipantPaidAction(tripId: string) {
|
||||
}
|
||||
}
|
||||
|
||||
export type StartMidtransResponse =
|
||||
| { error: string }
|
||||
| {
|
||||
success: true;
|
||||
snapToken: string;
|
||||
snapJsUrl: string;
|
||||
clientKey: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Mulai pembayaran online via Midtrans untuk trip tertentu. Resolve booking
|
||||
* dari (tripId, userId) supaya client tidak perlu tahu bookingId.
|
||||
*/
|
||||
export async function startMidtransPaymentAction(
|
||||
tripId: string
|
||||
): Promise<StartMidtransResponse> {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user) {
|
||||
return { error: "Kamu harus login terlebih dahulu" };
|
||||
}
|
||||
|
||||
try {
|
||||
const booking = await bookingService.getByTripAndUser(
|
||||
tripId,
|
||||
session.user.id
|
||||
);
|
||||
if (!booking || booking.status === "CANCELLED") {
|
||||
return { error: "Kamu tidak terdaftar di trip ini" };
|
||||
}
|
||||
|
||||
const result = await paymentService.startMidtransPayment(
|
||||
booking.id,
|
||||
session.user.id
|
||||
);
|
||||
return {
|
||||
success: true,
|
||||
snapToken: result.snapToken,
|
||||
snapJsUrl: result.snapJsUrl,
|
||||
clientKey: result.clientKey,
|
||||
};
|
||||
} catch (err) {
|
||||
return { error: (err as Error).message };
|
||||
}
|
||||
}
|
||||
|
||||
export async function confirmParticipantPaymentAction(
|
||||
tripId: string,
|
||||
participantId: string
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { startMidtransPaymentAction } from "@/features/booking/actions";
|
||||
|
||||
interface SnapCallbacks {
|
||||
onSuccess?: (result: unknown) => void;
|
||||
onPending?: (result: unknown) => void;
|
||||
onError?: (result: unknown) => void;
|
||||
onClose?: () => void;
|
||||
}
|
||||
|
||||
interface SnapApi {
|
||||
pay: (token: string, callbacks?: SnapCallbacks) => void;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
snap?: SnapApi;
|
||||
}
|
||||
}
|
||||
|
||||
const SCRIPT_ID = "midtrans-snap-script";
|
||||
|
||||
function loadSnapScript(snapJsUrl: string, clientKey: string): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (typeof window === "undefined") {
|
||||
reject(new Error("Snap hanya bisa dimuat di browser"));
|
||||
return;
|
||||
}
|
||||
if (window.snap) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
const existing = document.getElementById(SCRIPT_ID);
|
||||
if (existing) {
|
||||
existing.addEventListener("load", () => resolve());
|
||||
existing.addEventListener("error", () =>
|
||||
reject(new Error("Gagal memuat Snap.js"))
|
||||
);
|
||||
return;
|
||||
}
|
||||
const script = document.createElement("script");
|
||||
script.id = SCRIPT_ID;
|
||||
script.src = snapJsUrl;
|
||||
script.async = true;
|
||||
script.setAttribute("data-client-key", clientKey);
|
||||
script.onload = () => resolve();
|
||||
script.onerror = () => reject(new Error("Gagal memuat Snap.js"));
|
||||
document.body.appendChild(script);
|
||||
});
|
||||
}
|
||||
|
||||
interface MidtransPayButtonProps {
|
||||
tripId: string;
|
||||
}
|
||||
|
||||
export function MidtransPayButton({ tripId }: MidtransPayButtonProps) {
|
||||
const router = useRouter();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
async function handleClick() {
|
||||
setLoading(true);
|
||||
setError("");
|
||||
|
||||
const result = await startMidtransPaymentAction(tripId);
|
||||
if ("error" in result) {
|
||||
setError(result.error);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await loadSnapScript(result.snapJsUrl, result.clientKey);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : "Gagal memuat pembayaran");
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!window.snap) {
|
||||
setError("Snap belum siap, refresh halaman dan coba lagi");
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
window.snap.pay(result.snapToken, {
|
||||
onSuccess: () => {
|
||||
// Webhook server akan tetap jadi sumber kebenaran. Refresh page untuk pull state baru.
|
||||
router.refresh();
|
||||
},
|
||||
onPending: () => router.refresh(),
|
||||
onError: () => {
|
||||
setError(
|
||||
"Pembayaran gagal diproses. Coba lagi atau pakai metode lain."
|
||||
);
|
||||
router.refresh();
|
||||
},
|
||||
onClose: () => {
|
||||
// User menutup popup tanpa menyelesaikan. Refresh saja, kalau status berubah
|
||||
// (mis. user sudah bayar VA) callback dari Midtrans akan datang ke webhook.
|
||||
router.refresh();
|
||||
},
|
||||
});
|
||||
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
{error && (
|
||||
<div className="mb-3 rounded-xl bg-red-50 px-4 py-3 text-sm font-medium text-red-600">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleClick}
|
||||
disabled={loading}
|
||||
className="w-full rounded-xl bg-secondary-600 py-3 text-sm font-bold text-white shadow-lg shadow-secondary-600/20 transition-colors hover:bg-secondary-700 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
{loading ? "Memuat Snap..." : "Bayar online via Midtrans"}
|
||||
</button>
|
||||
<p className="mt-2 text-center text-[11px] text-neutral-500">
|
||||
Bayar pakai BCA VA, GoPay, QRIS, kartu, dan lainnya. Status terupdate
|
||||
otomatis setelah pembayaran terkonfirmasi gateway.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user