sync
This commit is contained in:
132
app/api/payments/ipn-callback/route.ts
Normal file
132
app/api/payments/ipn-callback/route.ts
Normal file
@@ -0,0 +1,132 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import pool from '@/lib/db'
|
||||
|
||||
// POST /api/payments/ipn-callback - Handle NOWPayments IPN callbacks
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json()
|
||||
|
||||
// NOWPayments IPN callback structure
|
||||
// You may need to adjust based on actual NOWPayments IPN format
|
||||
const {
|
||||
payment_id,
|
||||
invoice_id,
|
||||
order_id,
|
||||
payment_status,
|
||||
pay_amount,
|
||||
pay_currency,
|
||||
price_amount,
|
||||
price_currency,
|
||||
} = body
|
||||
|
||||
console.log('IPN Callback received:', {
|
||||
payment_id,
|
||||
invoice_id,
|
||||
order_id,
|
||||
payment_status,
|
||||
})
|
||||
|
||||
// Find pending order by payment_id or invoice_id
|
||||
const paymentIdToFind = invoice_id || payment_id
|
||||
const [pendingRows] = await pool.execute(
|
||||
'SELECT * FROM pending_orders WHERE payment_id = ?',
|
||||
[paymentIdToFind]
|
||||
)
|
||||
|
||||
const pendingOrders = pendingRows as any[]
|
||||
if (pendingOrders.length === 0) {
|
||||
// Check if sale already exists (idempotency)
|
||||
const [existingSales] = await pool.execute(
|
||||
'SELECT * FROM sales WHERE payment_id = ?',
|
||||
[paymentIdToFind]
|
||||
)
|
||||
const existing = existingSales as any[]
|
||||
if (existing.length > 0) {
|
||||
// Sale already created, just return success
|
||||
console.log('Sale already exists for payment_id:', paymentIdToFind)
|
||||
return NextResponse.json({ status: 'ok' }, { status: 200 })
|
||||
}
|
||||
|
||||
console.error('Pending order not found for payment_id:', paymentIdToFind)
|
||||
return NextResponse.json(
|
||||
{ error: 'Pending order not found' },
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
|
||||
const pendingOrder = pendingOrders[0]
|
||||
|
||||
// Update payment status based on payment_status
|
||||
// NOWPayments statuses: waiting, confirming, confirmed, sending, partially_paid, finished, failed, refunded, expired
|
||||
if (payment_status === 'finished' || payment_status === 'confirmed') {
|
||||
// Payment successful - create sale record
|
||||
try {
|
||||
// Check inventory again before creating sale
|
||||
const [dropRows] = await pool.execute(
|
||||
'SELECT * FROM drops WHERE id = ?',
|
||||
[pendingOrder.drop_id]
|
||||
)
|
||||
const drops = dropRows as any[]
|
||||
if (drops.length === 0) {
|
||||
console.error('Drop not found for pending order:', pendingOrder.id)
|
||||
return NextResponse.json({ status: 'error', message: 'Drop not found' }, { status: 200 })
|
||||
}
|
||||
|
||||
const drop = drops[0]
|
||||
|
||||
// Calculate current fill from sales
|
||||
const [salesRows] = await pool.execute(
|
||||
'SELECT COALESCE(SUM(size), 0) as total_fill FROM sales WHERE drop_id = ?',
|
||||
[pendingOrder.drop_id]
|
||||
)
|
||||
const salesData = salesRows as any[]
|
||||
const currentFill = salesData[0]?.total_fill || 0
|
||||
|
||||
// Convert fill to the drop's unit for comparison
|
||||
let currentFillInDropUnit = currentFill
|
||||
let sizeInDropUnit = pendingOrder.size
|
||||
if (drop.unit === 'kg') {
|
||||
currentFillInDropUnit = currentFill / 1000
|
||||
sizeInDropUnit = pendingOrder.size / 1000
|
||||
}
|
||||
|
||||
// Check if there's still enough inventory
|
||||
const remaining = drop.size - currentFillInDropUnit
|
||||
if (sizeInDropUnit > remaining) {
|
||||
console.error('Not enough inventory for pending order:', pendingOrder.id)
|
||||
// Delete pending order since inventory is no longer available
|
||||
await pool.execute('DELETE FROM pending_orders WHERE id = ?', [pendingOrder.id])
|
||||
return NextResponse.json({ status: 'error', message: 'Inventory no longer available' }, { status: 200 })
|
||||
}
|
||||
|
||||
// Create sale record
|
||||
const [result] = await pool.execute(
|
||||
'INSERT INTO sales (drop_id, buyer_id, size, payment_id) VALUES (?, ?, ?, ?)',
|
||||
[pendingOrder.drop_id, pendingOrder.buyer_id, pendingOrder.size, pendingOrder.payment_id]
|
||||
)
|
||||
|
||||
const saleId = (result as any).insertId
|
||||
|
||||
// Delete pending order since sale is created
|
||||
await pool.execute('DELETE FROM pending_orders WHERE id = ?', [pendingOrder.id])
|
||||
|
||||
console.log(`Payment confirmed - Sale ${saleId} created from pending order ${pendingOrder.id}`)
|
||||
} catch (error) {
|
||||
console.error('Error creating sale from pending order:', error)
|
||||
return NextResponse.json({ status: 'error' }, { status: 200 })
|
||||
}
|
||||
} else if (payment_status === 'failed' || payment_status === 'expired') {
|
||||
// Payment failed - delete pending order
|
||||
await pool.execute('DELETE FROM pending_orders WHERE id = ?', [pendingOrder.id])
|
||||
console.log(`Payment failed - Pending order ${pendingOrder.id} deleted`)
|
||||
}
|
||||
|
||||
// Return success to NOWPayments
|
||||
return NextResponse.json({ status: 'ok' }, { status: 200 })
|
||||
} catch (error) {
|
||||
console.error('Error processing IPN callback:', error)
|
||||
// Still return 200 to prevent NOWPayments from retrying
|
||||
return NextResponse.json({ status: 'error' }, { status: 200 })
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user