import { NextRequest, NextResponse } from 'next/server' import { cookies } from 'next/headers' import pool from '@/lib/db' import { getNowPaymentsConfig } from '@/lib/nowpayments' // GET /api/payments/check-status?payment_id=xxx - Check payment status manually export async function GET(request: NextRequest) { try { // Get buyer_id from session cookie const cookieStore = await cookies() const buyerIdCookie = cookieStore.get('buyer_id')?.value if (!buyerIdCookie) { return NextResponse.json( { error: 'Authentication required' }, { status: 401 } ) } const buyer_id = parseInt(buyerIdCookie, 10) const { searchParams } = new URL(request.url) const payment_id = searchParams.get('payment_id') if (!payment_id) { return NextResponse.json( { error: 'payment_id is required' }, { status: 400 } ) } // Check if it's a pending order or completed sale const [pendingRows] = await pool.execute( 'SELECT * FROM pending_orders WHERE payment_id = ? AND buyer_id = ?', [payment_id, buyer_id] ) const [salesRows] = await pool.execute( 'SELECT * FROM sales WHERE payment_id = ? AND buyer_id = ?', [payment_id, buyer_id] ) const pendingOrders = pendingRows as any[] const sales = salesRows as any[] if (pendingOrders.length === 0 && sales.length === 0) { return NextResponse.json( { error: 'Payment not found' }, { status: 404 } ) } // Get NOWPayments config (testnet or production) const nowPaymentsConfig = getNowPaymentsConfig() // Check payment status with NOWPayments const nowPaymentsResponse = await fetch( `${nowPaymentsConfig.baseUrl}/v1/payment/${payment_id}`, { method: 'GET', headers: { 'x-api-key': nowPaymentsConfig.apiKey, }, } ) if (!nowPaymentsResponse.ok) { const error = await nowPaymentsResponse.json() return NextResponse.json( { error: 'Failed to check payment status', details: error }, { status: 500 } ) } const paymentStatus = await nowPaymentsResponse.json() return NextResponse.json({ payment_id, status: paymentStatus.payment_status, payment_status: paymentStatus.payment_status, pay_amount: paymentStatus.pay_amount, pay_currency: paymentStatus.pay_currency, price_amount: paymentStatus.price_amount, price_currency: paymentStatus.price_currency, }) } catch (error) { console.error('Error checking payment status:', error) return NextResponse.json( { error: 'Failed to check payment status' }, { status: 500 } ) } }