|
| 1 | +import { NextResponse } from "next/server"; |
| 2 | +import Stripe from "stripe"; |
| 3 | +import { Resend } from "resend"; |
| 4 | + |
| 5 | + |
| 6 | +export async function POST(req: Request) { |
| 7 | + const stripe = new Stripe(process.env.STRIPE_SECRET_KEY || "dummy_key", { |
| 8 | + apiVersion: "2026-02-25.clover", // Adjust to the version you are using |
| 9 | + }); |
| 10 | + |
| 11 | + const body = await req.text(); |
| 12 | + const signature = req.headers.get("stripe-signature") as string; |
| 13 | + |
| 14 | + let event: Stripe.Event; |
| 15 | + |
| 16 | + try { |
| 17 | + event = stripe.webhooks.constructEvent( |
| 18 | + body, |
| 19 | + signature, |
| 20 | + process.env.STRIPE_WEBHOOK_SECRET as string |
| 21 | + ); |
| 22 | + } catch (error: any) { |
| 23 | + console.error(`Webhook signature verification failed: ${error.message}`); |
| 24 | + return new NextResponse(`Webhook Error: ${error.message}`, { status: 400 }); |
| 25 | + } |
| 26 | + |
| 27 | + // Handle the checkout session completion |
| 28 | + if (event.type === "checkout.session.completed") { |
| 29 | + const session = event.data.object as Stripe.Checkout.Session; |
| 30 | + const customerEmail = session.customer_details?.email; |
| 31 | + const paymentIntentId = session.payment_intent as string; |
| 32 | + |
| 33 | + if (!customerEmail) { |
| 34 | + console.error("No customer email found in session."); |
| 35 | + return new NextResponse("Invalid Session Data", { status: 400 }); |
| 36 | + } |
| 37 | + |
| 38 | + try { |
| 39 | + if (session.payment_status === "paid") { |
| 40 | + // Create a new license in Keygen |
| 41 | + await createLicenseForKeygen(customerEmail, session.id, paymentIntentId); |
| 42 | + } |
| 43 | + } catch (e: any) { |
| 44 | + console.error("Failed to process order:", e); |
| 45 | + // Stripe will retry the webhook if we fail. |
| 46 | + // In production, we'd log this, potentially to Sentry or PostHog |
| 47 | + return new NextResponse("Internal Server Error", { status: 500 }); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + // Return a 200 response to acknowledge receipt of the event |
| 52 | + return new NextResponse(JSON.stringify({ received: true }), { status: 200 }); |
| 53 | +} |
| 54 | + |
| 55 | +// ------------------------------------------------------------- |
| 56 | +// Core Business Logic |
| 57 | +// ------------------------------------------------------------- |
| 58 | + |
| 59 | +async function createLicenseForKeygen(email: string, sessionId: string, paymentIntentId: string) { |
| 60 | + const accountId = process.env.VITE_KEYGEN_ACCOUNT_ID; |
| 61 | + const policyId = process.env.VITE_KEYGEN_POLICY_ID; |
| 62 | + const keygenToken = process.env.KEYGEN_API_TOKEN; |
| 63 | + |
| 64 | + if (!accountId || !policyId || !keygenToken) { |
| 65 | + throw new Error("Missing Keygen configuration variables."); |
| 66 | + } |
| 67 | + |
| 68 | + // Use the undocumented global fetch inside NextJS |
| 69 | + const response = await fetch(`https://api.keygen.sh/v1/accounts/${accountId}/licenses`, { |
| 70 | + method: 'POST', |
| 71 | + headers: { |
| 72 | + 'Content-Type': 'application/vnd.api+json', |
| 73 | + 'Accept': 'application/vnd.api+json', |
| 74 | + 'Authorization': `Bearer ${keygenToken}` |
| 75 | + }, |
| 76 | + body: JSON.stringify({ |
| 77 | + data: { |
| 78 | + type: 'licenses', |
| 79 | + attributes: { |
| 80 | + name: email, |
| 81 | + metadata: { |
| 82 | + stripe_payment_id: paymentIntentId, |
| 83 | + stripe_session_id: sessionId |
| 84 | + } |
| 85 | + }, |
| 86 | + relationships: { |
| 87 | + policy: { |
| 88 | + data: { type: 'policies', id: policyId } |
| 89 | + } |
| 90 | + } |
| 91 | + } |
| 92 | + }) |
| 93 | + }); |
| 94 | + |
| 95 | + const data = await response.json(); |
| 96 | + |
| 97 | + if (!response.ok) { |
| 98 | + console.error("Keygen Error:", data); |
| 99 | + throw new Error(data.errors?.[0]?.detail || "Failed to create license on Keygen"); |
| 100 | + } |
| 101 | + |
| 102 | + // Safely extract the new key |
| 103 | + const licenseKey = data.data.attributes.key; |
| 104 | + |
| 105 | + if (!licenseKey) { |
| 106 | + throw new Error("License key generation failed!"); |
| 107 | + } |
| 108 | + |
| 109 | + console.log(`Successfully generated license for ${email}`); |
| 110 | + |
| 111 | + // Send the delivery email via Resend |
| 112 | + await sendDeliveryEmail(email, licenseKey); |
| 113 | +} |
| 114 | + |
| 115 | +async function sendDeliveryEmail(email: string, licenseKey: string) { |
| 116 | + const resend = new Resend(process.env.RESEND_API_KEY || "dummy_key"); |
| 117 | + const res = await resend.emails.send({ |
| 118 | + from: 'Smruti @ Devian <smruti@devian.app>', |
| 119 | + to: email, |
| 120 | + subject: 'Welcome to Devian Pro! Here is your license key 🚀', |
| 121 | + text: `Hey! |
| 122 | +
|
| 123 | +Thank you so much for purchasing Devian Pro. As a solo developer, your support means the world to me and directly funds the future development of the app. |
| 124 | +
|
| 125 | +Here is your lifetime license key (valid for up to 3 devices): |
| 126 | +${licenseKey} |
| 127 | +
|
| 128 | +How to activate: |
| 129 | +1. Open Devian. |
| 130 | +2. Go to Settings -> Devian Pro. |
| 131 | +3. Paste your key and click Activate. |
| 132 | +
|
| 133 | +If you run into any issues, have feature requests, or just want to say hi, reply to this email or reach out to me directly at smruti@devian.app. I read every message! |
| 134 | +
|
| 135 | +Happy building, |
| 136 | +Smruti`, |
| 137 | + }); |
| 138 | + |
| 139 | + if (res.error) { |
| 140 | + console.error("Failed to send Resend email:", res.error); |
| 141 | + throw new Error("Email delivery failed"); |
| 142 | + } |
| 143 | + |
| 144 | + console.log(`Successfully emailed license to ${email}`); |
| 145 | +} |
0 commit comments