Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 | 1x 1x 1x 1x 1x 1x 1x 13x 13x 1x 1x 1x 1x 13x 13x 1x 1x 1x 1x 1x 1x 14x 14x 14x 14x 1x 1x 1x 13x 13x 14x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 14x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 14x 4x 3x 14x 14x 2x 2x 14x 14x 1x 1x 14x 14x 2x 2x 14x 14x 1x 1x 14x 14x 1x 14x 10x 10x 14x 1x 1x 1x 1x 1x 1x 14x 1x 1x 1x 1x 4x 4x 4x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 4x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { logger } from "@/lib/logging";
import Stripe from "stripe";
// Lazy initialization
let stripeClient: Stripe | null = null;
function getStripe(): Stripe {
if (!stripeClient) {
const key = process.env.STRIPE_SECRET_KEY;
if (!key) {
throw new Error("STRIPE_SECRET_KEY is not configured");
}
stripeClient = new Stripe(key);
}
return stripeClient;
}
/**
* Stripe webhook handler
* Processes payment events from Stripe
*/
export async function POST(request: NextRequest) {
const body = await request.text();
const signature = request.headers.get("stripe-signature");
if (!signature) {
logger.warn("Missing stripe-signature header", { category: "API" });
return NextResponse.json({ error: "Missing signature" }, { status: 400 });
}
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
if (!webhookSecret) {
logger.error("STRIPE_WEBHOOK_SECRET not configured", new Error("Missing configuration"), { category: "API" });
return NextResponse.json(
{ error: "Webhook not configured" },
{ status: 500 }
);
}
let event: Stripe.Event;
try {
event = getStripe().webhooks.constructEvent(body, signature, webhookSecret);
} catch (err) {
const message = err instanceof Error ? err.message : "Invalid signature";
logger.error(`Signature verification failed: ${message}`, err instanceof Error ? err : new Error(message), { category: "API" });
return NextResponse.json({ error: "Invalid signature" }, { status: 400 });
}
logger.info(`Received event: ${event.type}`, {
category: "API",
eventId: event.id});
try {
switch (event.type) {
case "payment_intent.succeeded":
await handlePaymentSuccess(event.data.object as Stripe.PaymentIntent);
break;
case "payment_intent.payment_failed":
await handlePaymentFailure(event.data.object as Stripe.PaymentIntent);
break;
case "payment_intent.canceled":
await handlePaymentCanceled(event.data.object as Stripe.PaymentIntent);
break;
case "charge.refunded":
await handleRefund(event.data.object as Stripe.Charge);
break;
case "charge.dispute.created":
await handleDispute(event.data.object as Stripe.Dispute);
break;
default:
logger.info(`Unhandled event type: ${event.type}`, { category: "API" });
}
return NextResponse.json({ received: true });
} catch (error) {
logger.error("Error processing webhook", error instanceof Error ? error : new Error(String(error)), { category: "API" });
return NextResponse.json(
{ error: "Webhook processing failed" },
{ status: 500 }
);
}
}
/**
* Handle successful payment
*/
async function handlePaymentSuccess(paymentIntent: Stripe.PaymentIntent) {
const orderId = paymentIntent.metadata?.orderId;
if (!orderId) {
logger.warn("Payment succeeded but no orderId in metadata", {
category: "API",
paymentIntentId: paymentIntent.id});
return;
}
logger.info(`Payment succeeded for order ${orderId}`, {
category: "API",
paymentIntentId: paymentIntent.id,
amount: paymentIntent.amount});
try {
await prisma.order.update({
where: { id: parseInt(orderId, 10) },
data: {
status: "PROCESSING",
updatedAt: new Date()}});
logger.info(`Order ${orderId} status updated to PROCESSING`, { category: "API" });
} catch (error) {
logger.error(`Failed to update order ${orderId}`, error instanceof Error ? error : new Error(String(error)), { category: "API" });
throw error;
}
}
/**
* Handle failed payment
*/
async function handlePaymentFailure(paymentIntent: Stripe.PaymentIntent) {
const orderId = paymentIntent.metadata?.orderId;
const failureMessage =
paymentIntent.last_payment_error?.message || "Payment failed";
logger.warn(`Payment failed for order ${orderId}`, {
category: "API",
paymentIntentId: paymentIntent.id,
failureMessage});
if (orderId) {
try {
await prisma.order.update({
where: { id: parseInt(orderId, 10) },
data: {
status: "CANCELLED",
updatedAt: new Date()}});
logger.info(`Order ${orderId} marked as CANCELLED`, { category: "API" });
} catch (error) {
logger.error(`Failed to update order ${orderId}`, error instanceof Error ? error : new Error(String(error)), { category: "API" });
}
}
}
/**
* Handle canceled payment
*/
async function handlePaymentCanceled(paymentIntent: Stripe.PaymentIntent) {
const orderId = paymentIntent.metadata?.orderId;
logger.info(`Payment canceled for order ${orderId}`, {
category: "API",
paymentIntentId: paymentIntent.id});
if (orderId) {
try {
await prisma.order.update({
where: { id: parseInt(orderId, 10) },
data: {
status: "CANCELLED",
updatedAt: new Date()}});
} catch (error) {
logger.error(`Failed to update order ${orderId}`, error instanceof Error ? error : new Error(String(error)), { category: "API" });
}
}
}
/**
* Handle refund
*/
async function handleRefund(charge: Stripe.Charge) {
const paymentIntentId = charge.payment_intent;
logger.info(`Refund processed`, {
category: "API",
chargeId: charge.id,
paymentIntentId,
amountRefunded: charge.amount_refunded});
// If fully refunded, you might want to update order status
if (charge.refunded && paymentIntentId) {
// Retrieve the payment intent to get the orderId
try {
const paymentIntent = await getStripe().paymentIntents.retrieve(
paymentIntentId as string
);
const orderId = paymentIntent.metadata?.orderId;
if (orderId) {
await prisma.order.update({
where: { id: parseInt(orderId, 10) },
data: {
status: "CANCELLED",
updatedAt: new Date()}});
logger.info(`Order ${orderId} marked as CANCELLED due to refund`, { category: "API" });
}
} catch (error) {
logger.error("Failed to process refund order update", error instanceof Error ? error : new Error(String(error)), { category: "API" });
}
}
}
/**
* Handle dispute
*/
async function handleDispute(dispute: Stripe.Dispute) {
logger.warn(`Dispute created`, {
category: "API",
disputeId: dispute.id,
chargeId: dispute.charge,
amount: dispute.amount,
reason: dispute.reason});
// You should notify admins about disputes
// In a real app, send email/Slack notification here
}
|