This commit is contained in:
root
2025-12-20 19:00:42 +01:00
parent 9871289bfb
commit e1a0966dee
23 changed files with 1878 additions and 48 deletions

View File

@@ -0,0 +1,94 @@
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 }
)
}
}

View File

@@ -0,0 +1,153 @@
import { NextRequest, NextResponse } from 'next/server'
import { cookies } from 'next/headers'
import pool from '@/lib/db'
import { getNowPaymentsConfig } from '@/lib/nowpayments'
// POST /api/payments/create-invoice - Create a NOWPayments invoice
export async function POST(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 body = await request.json()
const { drop_id, size } = body
// Validate required fields
if (!drop_id || !size) {
return NextResponse.json(
{ error: 'Missing required fields: drop_id, size' },
{ status: 400 }
)
}
// Get drop details
const [dropRows] = await pool.execute(
'SELECT * FROM drops WHERE id = ?',
[drop_id]
)
const drops = dropRows as any[]
if (drops.length === 0) {
return NextResponse.json(
{ error: 'Drop not found' },
{ status: 404 }
)
}
const drop = drops[0]
// Check inventory availability (but don't reserve yet - will reserve when payment confirmed)
const [salesRows] = await pool.execute(
'SELECT COALESCE(SUM(size), 0) as total_fill FROM sales WHERE drop_id = ?',
[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 = size
if (drop.unit === 'kg') {
currentFillInDropUnit = currentFill / 1000
sizeInDropUnit = size / 1000
}
// Check if there's enough remaining inventory
const remaining = drop.size - currentFillInDropUnit
if (sizeInDropUnit > remaining) {
return NextResponse.json(
{ error: 'Not enough inventory remaining' },
{ status: 400 }
)
}
// Calculate price
let priceAmount = 0
if (drop.unit === 'kg') {
priceAmount = (size / 1000) * drop.ppu
} else {
priceAmount = size * drop.ppu
}
// Round to 2 decimal places
priceAmount = Math.round(priceAmount * 100) / 100
// Generate order ID
const orderId = `SALE-${Date.now()}-${drop_id}-${buyer_id}`
// Get base URL for success/cancel redirects
const baseUrl = process.env.NEXT_PUBLIC_BASE_URL ||
request.headers.get('origin') ||
'http://localhost:3420'
// Get IPN callback URL from environment variable
const ipnCallbackUrl = process.env.IPN_CALLBACK_URL
if (!ipnCallbackUrl) {
return NextResponse.json(
{ error: 'IPN_CALLBACK_URL environment variable is required' },
{ status: 500 }
)
}
// Get NOWPayments config (testnet or production)
const nowPaymentsConfig = getNowPaymentsConfig()
// Create NOWPayments invoice
const nowPaymentsResponse = await fetch(`${nowPaymentsConfig.baseUrl}/v1/invoice`, {
method: 'POST',
headers: {
'x-api-key': nowPaymentsConfig.apiKey,
'Content-Type': 'application/json',
},
body: JSON.stringify({
price_amount: priceAmount,
price_currency: nowPaymentsConfig.currency,
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}`,
}),
})
if (!nowPaymentsResponse.ok) {
const error = await nowPaymentsResponse.json()
console.error('NOWPayments error:', error)
return NextResponse.json(
{ error: 'Failed to create payment invoice', details: error },
{ status: 500 }
)
}
const invoice = await nowPaymentsResponse.json()
// Store pending order (will create sale when payment is confirmed)
const [result] = await pool.execute(
'INSERT INTO pending_orders (payment_id, order_id, drop_id, buyer_id, size, price_amount, price_currency) VALUES (?, ?, ?, ?, ?, ?, ?)',
[invoice.id, orderId, drop_id, buyer_id, size, priceAmount, nowPaymentsConfig.currency]
)
// Return invoice URL - sale will be created when payment is confirmed via IPN
return NextResponse.json({
invoice_url: invoice.invoice_url,
payment_id: invoice.id,
order_id: orderId,
}, { status: 201 })
} catch (error) {
console.error('Error creating invoice:', error)
return NextResponse.json(
{ error: 'Failed to create invoice' },
{ status: 500 }
)
}
}

View 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 })
}
}