389dac68c4
- 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>
40 lines
1.5 KiB
TypeScript
40 lines
1.5 KiB
TypeScript
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 })
|
|
}
|