Stripe: webhook que entrega el servicio aunque el usuario no vuelva
- app/api/stripe/webhook: verifica firma (constructEventAsync) y en checkout.session.completed registra la IP de Stripe (como Django) y ENTREGA el servicio. Idempotente frente a la página de éxito. - lib/stripe.ts: claimPaidCheckout ahora es ATÓMICO (UPDATE ... WHERE fulfilled=0 + affectedRows) para evitar doble entrega entre webhook y página de éxito; nuevo recordStripeIp. - lib/fulfill.ts: fulfillCheckoutSession compartido (reclama + resuelve servicio desde metadata.service + ejecuta). checkout guarda `service` en metadata. - service-success: usa la entrega compartida y distingue entregado/ya-procesado/error. - i18n: Paid.alreadyProcessed. Requiere configurar STRIPE_WEBHOOK_SECRET en .env.local (endpoint apuntando a /api/stripe/webhook, evento checkout.session.completed). Verificado: build OK, webhook 400 sin firma / firma inválida. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -25,8 +25,9 @@ export async function POST(request: Request, { params }: { params: Promise<{ ser
|
||||
return Response.json({ success: false, error: 'invalidCharacter' })
|
||||
}
|
||||
|
||||
// Campos extra del servicio (gold_amount, destination_account...) -> metadata
|
||||
const metadata: Record<string, string> = {}
|
||||
// Campos extra del servicio (gold_amount, destination_account...) -> metadata.
|
||||
// `service` va en metadata para que el webhook sepa qué entregar sin la URL.
|
||||
const metadata: Record<string, string> = { service }
|
||||
for (const f of cfg.extraFields) {
|
||||
const v = String(body[f] ?? '').trim()
|
||||
if (!v) return Response.json({ success: false, error: 'missingFields' })
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import Stripe from 'stripe'
|
||||
import { recordStripeIp } from '@/lib/stripe'
|
||||
import { fulfillCheckoutSession } from '@/lib/fulfill'
|
||||
|
||||
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY as string)
|
||||
|
||||
/**
|
||||
* Webhook de Stripe. Verifica la firma y, en `checkout.session.completed`:
|
||||
* - registra la IP de Stripe (como Django),
|
||||
* - ENTREGA el servicio (idempotente vía claim atómico), de modo que el pago se
|
||||
* cumple aunque el usuario cierre el navegador antes de volver a la web.
|
||||
*/
|
||||
export async function POST(request: Request) {
|
||||
const secret = process.env.STRIPE_WEBHOOK_SECRET
|
||||
const sig = request.headers.get('stripe-signature')
|
||||
if (!secret || !sig) return Response.json({ success: false, message: 'missingSignature' }, { status: 400 })
|
||||
|
||||
const payload = await request.text()
|
||||
let event: Stripe.Event
|
||||
try {
|
||||
event = await stripe.webhooks.constructEventAsync(payload, sig, secret)
|
||||
} catch {
|
||||
return Response.json({ success: false, message: 'invalidSignature' }, { status: 400 })
|
||||
}
|
||||
|
||||
if (event.type === 'checkout.session.completed') {
|
||||
const session = event.data.object as Stripe.Checkout.Session
|
||||
const ip = (request.headers.get('x-forwarded-for') || '').split(',')[0].trim() || '0.0.0.0'
|
||||
await recordStripeIp(session.id, ip)
|
||||
// Entrega best-effort; los errores no deben provocar reintentos infinitos de Stripe.
|
||||
try {
|
||||
await fulfillCheckoutSession(session.id)
|
||||
} catch {
|
||||
/* el reclamo atómico impide dobles entregas; se puede reintentar desde la web */
|
||||
}
|
||||
}
|
||||
|
||||
return Response.json({ success: true })
|
||||
}
|
||||
Reference in New Issue
Block a user