|
1 | 1 | import { NextResponse } from 'next/server' |
| 2 | +import Stripe from 'stripe' |
| 3 | +import { sanityWriteClient } from '@/lib/sanity-write-client' |
2 | 4 |
|
3 | 5 | /** |
4 | 6 | * Stripe webhook handler for sponsor invoices. |
5 | 7 | * |
6 | | - * STUBBED — needs STRIPE_SECRET_KEY and STRIPE_WEBHOOK_SECRET |
7 | | - * |
8 | | - * Will handle: |
| 8 | + * Handles: |
9 | 9 | * - invoice.paid → update sponsorLead status to 'paid', assign to next video |
10 | | - * - invoice.payment_failed → update sponsorLead stripePaymentStatus to 'failed' |
11 | | - * |
12 | | - * TODO: Wire up Stripe webhook verification and event handling |
| 10 | + * - invoice.payment_failed → update sponsorLead status back to 'negotiating' |
13 | 11 | */ |
| 12 | + |
| 13 | +/** Lazy Stripe client — only created when actually needed */ |
| 14 | +let _stripe: Stripe | null = null |
| 15 | +function getStripeClient(): Stripe { |
| 16 | + if (!_stripe) { |
| 17 | + if (!process.env.STRIPE_SECRET_KEY) { |
| 18 | + throw new Error('STRIPE_SECRET_KEY not set') |
| 19 | + } |
| 20 | + _stripe = new Stripe(process.env.STRIPE_SECRET_KEY) |
| 21 | + } |
| 22 | + return _stripe |
| 23 | +} |
| 24 | + |
14 | 25 | export async function POST(request: Request) { |
15 | 26 | try { |
16 | 27 | const body = await request.text() |
| 28 | + const sig = request.headers.get('stripe-signature') |
17 | 29 |
|
18 | | - // TODO: Verify Stripe webhook signature |
19 | | - // const sig = request.headers.get('stripe-signature') |
20 | | - // const event = stripe.webhooks.constructEvent(body, sig!, process.env.STRIPE_WEBHOOK_SECRET!) |
| 30 | + if (!sig) { |
| 31 | + console.error('[SPONSOR] Missing stripe-signature header') |
| 32 | + return NextResponse.json({ error: 'Missing signature' }, { status: 400 }) |
| 33 | + } |
21 | 34 |
|
22 | | - console.log('[SPONSOR] Stripe webhook received (stubbed):', { |
23 | | - contentLength: body.length, |
| 35 | + if (!process.env.STRIPE_WEBHOOK_SECRET) { |
| 36 | + console.error('[SPONSOR] STRIPE_WEBHOOK_SECRET not set') |
| 37 | + return NextResponse.json({ error: 'Webhook secret not configured' }, { status: 500 }) |
| 38 | + } |
| 39 | + |
| 40 | + // Verify webhook signature |
| 41 | + const stripe = getStripeClient() |
| 42 | + let event: Stripe.Event |
| 43 | + try { |
| 44 | + event = stripe.webhooks.constructEvent(body, sig, process.env.STRIPE_WEBHOOK_SECRET) |
| 45 | + } catch (err) { |
| 46 | + console.error('[SPONSOR] Webhook signature verification failed:', err) |
| 47 | + return NextResponse.json({ error: 'Invalid signature' }, { status: 400 }) |
| 48 | + } |
| 49 | + |
| 50 | + console.log('[SPONSOR] Stripe webhook received:', { |
| 51 | + type: event.type, |
| 52 | + id: event.id, |
24 | 53 | timestamp: new Date().toISOString(), |
25 | 54 | }) |
26 | 55 |
|
27 | | - // TODO: Handle events |
28 | | - // switch (event.type) { |
29 | | - // case 'invoice.paid': { |
30 | | - // const invoice = event.data.object |
31 | | - // // Find sponsorLead by stripeInvoiceId |
32 | | - // // Update status to 'paid' |
33 | | - // // Update stripePaymentStatus to 'paid' |
34 | | - // // Assign to next available video |
35 | | - // break |
36 | | - // } |
37 | | - // case 'invoice.payment_failed': { |
38 | | - // const invoice = event.data.object |
39 | | - // // Find sponsorLead by stripeInvoiceId |
40 | | - // // Update stripePaymentStatus to 'failed' |
41 | | - // break |
42 | | - // } |
43 | | - // } |
| 56 | + switch (event.type) { |
| 57 | + case 'invoice.paid': { |
| 58 | + const invoice = event.data.object as Stripe.Invoice |
| 59 | + console.log('[SPONSOR] Invoice paid:', invoice.id) |
| 60 | + |
| 61 | + // Find the sponsorLead by stripeInvoiceId in Sanity |
| 62 | + const lead = await sanityWriteClient.fetch( |
| 63 | + `*[_type == "sponsorLead" && stripeInvoiceId == $invoiceId][0]`, |
| 64 | + { invoiceId: invoice.id } |
| 65 | + ) |
| 66 | + |
| 67 | + if (!lead) { |
| 68 | + console.warn('[SPONSOR] No sponsorLead found for invoice:', invoice.id) |
| 69 | + break |
| 70 | + } |
| 71 | + |
| 72 | + // Update status to 'paid' |
| 73 | + await sanityWriteClient |
| 74 | + .patch(lead._id) |
| 75 | + .set({ |
| 76 | + status: 'paid', |
| 77 | + stripePaymentStatus: 'paid', |
| 78 | + }) |
| 79 | + .commit() |
| 80 | + |
| 81 | + console.log('[SPONSOR] Updated sponsorLead to paid:', lead._id) |
| 82 | + |
| 83 | + // Find next available automatedVideo (status script_ready or later, no sponsorSlot assigned) |
| 84 | + const availableVideo = await sanityWriteClient.fetch( |
| 85 | + `*[_type == "automatedVideo" && status in ["script_ready", "media_ready", "ready_to_publish"] && !defined(bookedSlot)][0]{ |
| 86 | + _id, |
| 87 | + title, |
| 88 | + status |
| 89 | + }` |
| 90 | + ) |
| 91 | + |
| 92 | + if (availableVideo) { |
| 93 | + // Assign the lead to the video via bookedSlot |
| 94 | + await sanityWriteClient |
| 95 | + .patch(availableVideo._id) |
| 96 | + .set({ |
| 97 | + bookedSlot: { |
| 98 | + _type: 'reference', |
| 99 | + _ref: lead._id, |
| 100 | + }, |
| 101 | + }) |
| 102 | + .commit() |
| 103 | + |
| 104 | + console.log('[SPONSOR] Assigned lead to video:', { |
| 105 | + leadId: lead._id, |
| 106 | + videoId: availableVideo._id, |
| 107 | + videoTitle: availableVideo.title, |
| 108 | + }) |
| 109 | + } else { |
| 110 | + console.warn('[SPONSOR] No available video found for lead:', lead._id) |
| 111 | + } |
| 112 | + |
| 113 | + break |
| 114 | + } |
| 115 | + |
| 116 | + case 'invoice.payment_failed': { |
| 117 | + const invoice = event.data.object as Stripe.Invoice |
| 118 | + console.log('[SPONSOR] Invoice payment failed:', invoice.id) |
| 119 | + |
| 120 | + // Find the sponsorLead by stripeInvoiceId in Sanity |
| 121 | + const lead = await sanityWriteClient.fetch( |
| 122 | + `*[_type == "sponsorLead" && stripeInvoiceId == $invoiceId][0]`, |
| 123 | + { invoiceId: invoice.id } |
| 124 | + ) |
| 125 | + |
| 126 | + if (!lead) { |
| 127 | + console.warn('[SPONSOR] No sponsorLead found for failed invoice:', invoice.id) |
| 128 | + break |
| 129 | + } |
| 130 | + |
| 131 | + // Update sponsorLead status back to 'negotiating' |
| 132 | + await sanityWriteClient |
| 133 | + .patch(lead._id) |
| 134 | + .set({ |
| 135 | + status: 'negotiating', |
| 136 | + stripePaymentStatus: 'failed', |
| 137 | + }) |
| 138 | + .commit() |
| 139 | + |
| 140 | + console.log('[SPONSOR] Updated sponsorLead to negotiating (payment failed):', lead._id) |
| 141 | + break |
| 142 | + } |
| 143 | + |
| 144 | + default: |
| 145 | + console.log('[SPONSOR] Unhandled webhook event type:', event.type) |
| 146 | + } |
44 | 147 |
|
45 | 148 | return NextResponse.json({ received: true }) |
46 | 149 | } catch (error) { |
|
0 commit comments