74 lines
2.5 KiB
TypeScript
74 lines
2.5 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
import ZarinPal from 'zarinpal-node-sdk';
|
|
import { getDatabase } from '@/lib/db';
|
|
|
|
const zarinpal = new ZarinPal({
|
|
merchantId: process.env.ZARINPAL_MERCHANT_ID || 'test-merchant-id',
|
|
sandbox: process.env.NODE_ENV !== 'production',
|
|
});
|
|
|
|
export async function POST(request: NextRequest) {
|
|
try {
|
|
const body = await request.json();
|
|
const { albumId, amount, customerName, email, phoneNumber } = body;
|
|
|
|
if (!albumId || !amount) {
|
|
return NextResponse.json(
|
|
{ error: 'Album ID and amount are required' },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
// Clean phone number: remove +98, spaces, and any non-digits
|
|
// ZarinPal expects format: 09XXXXXXXXX (11 digits starting with 0)
|
|
const cleanPhone = phoneNumber.replace(/\D/g, ''); // Remove all non-digits
|
|
const mobileNumber = cleanPhone.startsWith('98')
|
|
? '0' + cleanPhone.slice(2) // +98 9390084053 -> 09390084053
|
|
: cleanPhone.startsWith('9')
|
|
? '0' + cleanPhone // 9390084053 -> 09390084053
|
|
: cleanPhone; // Already in correct format
|
|
|
|
// Get the base URL for callback
|
|
const protocol = request.headers.get('x-forwarded-proto') || 'http';
|
|
const host = request.headers.get('host') || 'localhost:3000';
|
|
const callback_url = `${protocol}://${host}/payment/callback`;
|
|
|
|
// Initiate payment with ZarinPal
|
|
const response = await zarinpal.payments.create({
|
|
amount: amount,
|
|
callback_url: callback_url,
|
|
description: `Purchase album: ${albumId}`,
|
|
mobile: mobileNumber,
|
|
email: email,
|
|
});
|
|
|
|
if (response.data && response.data.code === 100) {
|
|
const authority = response.data.authority;
|
|
|
|
// Store payment authority in database
|
|
const db = getDatabase();
|
|
db.prepare(`
|
|
INSERT INTO payment_authorities (authority, albumId, amount, customerName, email, phoneNumber, status)
|
|
VALUES (?, ?, ?, ?, ?, ?, 'pending')
|
|
`).run(authority, albumId, amount, customerName, email, mobileNumber);
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
authority: authority,
|
|
paymentUrl: `https://sandbox.zarinpal.com/pg/StartPay/${authority}`,
|
|
});
|
|
} else {
|
|
return NextResponse.json(
|
|
{ error: 'Failed to initiate payment', code: response.data?.code },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
} catch (error: any) {
|
|
console.error('Payment initiation error:', error);
|
|
return NextResponse.json(
|
|
{ error: error.message || 'Failed to initiate payment' },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|