race condition fixed, payment inside

This commit is contained in:
root
2025-12-21 09:56:59 +01:00
parent 6741f5ed72
commit 67646c75a4
6 changed files with 714 additions and 30 deletions

View File

@@ -3,7 +3,9 @@ import { cookies } from 'next/headers'
import pool from '@/lib/db'
import { getNowPaymentsConfig } from '@/lib/nowpayments'
// POST /api/payments/create-invoice - Create a NOWPayments invoice
// POST /api/payments/create-invoice - Create a NOWPayments payment
// Note: Endpoint name kept as "create-invoice" for backward compatibility
// but it now uses the /v1/payment endpoint instead of /v1/invoice
export async function POST(request: NextRequest) {
try {
// Get buyer_id from session cookie
@@ -20,7 +22,7 @@ export async function POST(request: NextRequest) {
const buyer_id = parseInt(buyerIdCookie, 10)
const body = await request.json()
const { drop_id, size } = body
const { drop_id, size, pay_currency } = body
// Validate required fields
if (!drop_id || !size) {
@@ -132,10 +134,16 @@ export async function POST(request: NextRequest) {
const expiresAt = new Date()
expiresAt.setMinutes(expiresAt.getMinutes() + 10)
// Create NOWPayments invoice
// Note: NOWPayments doesn't support invoice_timeout parameter
// Expiration is handled by our pending_orders table (10 minutes)
const nowPaymentsResponse = await fetch(`${nowPaymentsConfig.baseUrl}/v1/invoice`, {
// Create NOWPayments payment
// Note: Payment API requires pay_currency (crypto currency)
// Use currency from request, or fall back to env/default
const payCurrency = pay_currency || process.env.NOWPAYMENTS_PAY_CURRENCY || 'btc'
// Optional: Use fixed rate for 20 minutes (prevents rate changes during checkout)
// If is_fixed_rate is true, payment expires after 20 minutes if not paid
const isFixedRate = process.env.NOWPAYMENTS_FIXED_RATE === 'true' || false
const nowPaymentsResponse = await fetch(`${nowPaymentsConfig.baseUrl}/v1/payment`, {
method: 'POST',
headers: {
'x-api-key': nowPaymentsConfig.apiKey,
@@ -144,11 +152,11 @@ export async function POST(request: NextRequest) {
body: JSON.stringify({
price_amount: priceAmount,
price_currency: nowPaymentsConfig.currency,
pay_currency: payCurrency, // Required: crypto currency (btc, eth, etc)
order_id: orderId,
order_description: `${drop.item} - ${size}g`,
ipn_callback_url: ipnCallbackUrl,
success_url: `${baseUrl}/?payment=success&order_id=${orderId}`,
cancel_url: `${baseUrl}/?payment=cancelled&order_id=${orderId}`,
is_fixed_rate: isFixedRate, // Optional: freeze exchange rate for 20 minutes
}),
})
@@ -158,28 +166,36 @@ export async function POST(request: NextRequest) {
await connection.rollback()
connection.release()
return NextResponse.json(
{ error: 'Failed to create payment invoice', details: error },
{ error: 'Failed to create payment', details: error },
{ status: 500 }
)
}
const invoice = await nowPaymentsResponse.json()
const payment = await nowPaymentsResponse.json()
// Store pending order with expiration time (atomically reserves inventory)
// payment.payment_id is the NOWPayments payment ID
await connection.execute(
'INSERT INTO pending_orders (payment_id, order_id, drop_id, buyer_id, size, price_amount, price_currency, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
[invoice.id, orderId, drop_id, buyer_id, size, priceAmount, nowPaymentsConfig.currency, expiresAt]
[payment.payment_id, orderId, drop_id, buyer_id, size, priceAmount, nowPaymentsConfig.currency, expiresAt]
)
// Commit transaction - inventory is now reserved
await connection.commit()
connection.release()
// Return invoice URL - sale will be created by external IPN handler when payment is confirmed
// Return payment details - sale will be created by external IPN handler when payment is confirmed
return NextResponse.json({
invoice_url: invoice.invoice_url,
payment_id: invoice.id,
payment_id: payment.payment_id,
payment_status: payment.payment_status,
pay_address: payment.pay_address, // Address where customer sends payment
pay_amount: payment.pay_amount, // Amount in crypto to pay
pay_currency: payment.pay_currency, // Crypto currency
price_amount: payment.price_amount, // Price in fiat
price_currency: payment.price_currency, // Fiat currency
order_id: orderId,
payin_extra_id: payment.payin_extra_id, // Memo/tag for certain currencies (XRP, XLM, etc)
expiration_estimate_date: payment.expiration_estimate_date, // When payment expires
}, { status: 201 })
} catch (error) {
await connection.rollback()
@@ -187,9 +203,9 @@ export async function POST(request: NextRequest) {
throw error
}
} catch (error) {
console.error('Error creating invoice:', error)
console.error('Error creating payment:', error)
return NextResponse.json(
{ error: 'Failed to create invoice' },
{ error: 'Failed to create payment' },
{ status: 500 }
)
}