backend/src/api/stripe/controllers/stripe.ts (view raw)
1import Stripe from "stripe";
2
3const STRIPE_SECRET = process.env.STRIPE_SECRET_KEY;
4const ENDPOINT_SECRET = process.env.STRIPE_ENDPOINT_SECRET;
5
6let stripe: Stripe;
7
8if (STRIPE_SECRET) stripe = new Stripe(STRIPE_SECRET);
9
10export default {
11 handleWebhook: async (ctx, next) => {
12 if (!stripe) {
13 strapi.log.warn(
14 "Stripe is not enabled for this instance. Please provide STRIPE_SECRET_KEY variable to enable it."
15 );
16 return;
17 }
18
19 try {
20 const payload = ctx.request.body[Symbol.for("unparsedBody")];
21 const sig = ctx.request.headers["stripe-signature"];
22 const event = stripe.webhooks.constructEvent(
23 payload,
24 sig,
25 ENDPOINT_SECRET
26 );
27 if (event.type === "checkout.session.completed") {
28 strapi.service("api::stripe.stripe").enableModule(event);
29 } else
30 strapi.log.warn(
31 `[Stripe] Received webhook of type ${event.type} (ignored)`
32 );
33 ctx.body = "ok";
34 } catch (err) {
35 strapi.log.error(`Webhook ${err}`);
36 ctx.status = 400;
37 ctx.body = err;
38 }
39 },
40};