#yuyu_webhooks

1 messages ¡ Page 1 of 1 (latest)

lime basinBOT
#

👋 Welcome to your new thread!

⏲️ We'll be here soon! Typically we respond in a few minutes, but sometimes we might take a bit longer if the server is busy or if you have a particularly tricky question.

⏱️ We close idle threads, which makes them read-only. Once a thread is closed it won't be reopened, but you can always start a new thread if you have another question.

🔗 This thread will always be available, even after it's closed. You can find it again using Discord's search, or you can save this link: https://discord.com/channels/841573134531821608/1280587969887076414

📝 Have more to share? Add more details, code, screenshots, videos, etc. below.

neon folio
#
const stripe = require("stripe")(process.env.STRIPE_PRIVATE_KEY);
const endpointSecret = process.env.STRIPE_WEBHOOK_SECRET;

app.post(
  "/stripe_webhook",
  express.raw({ type: "application/json" }),
  async (request, response) => {
    const sig = request.headers["stripe-signature"];

    let event;

    try {
      event = stripe.webhooks.constructEvent(request.body, sig, endpointSecret);
    } catch (err) {
      response.status(400).send(`Webhook Error: ${err.message}`);
      return;
    }
    console.log(event);

    // Handle the event
    switch (event.type) {
      case "checkout.session.completed":
        const checkoutSessionCompleted = event.data.object;
        console.log("test");

        // Retrieve the user ID from the session metadata
        const userId = checkoutSessionCompleted.metadata.userId;

        // Fetch user profile
        let userProfile = await profileSchema.findOne({ _id: userId });
        if (userProfile) {
          const threeMonthsInMillis = 1000 * 60 * 60 * 24 * 90;
          const now = new Date();

          if (userProfile.premium) {
            const currentEndDate = new Date(userProfile.premiumEndDate);
            if (isNaN(currentEndDate)) {
              userProfile.premiumEndDate = new Date(
                now.getTime() + threeMonthsInMillis
              );
            } else {
              userProfile.premiumEndDate = new Date(
                Math.max(now.getTime(), currentEndDate.getTime()) +
                  threeMonthsInMillis
              );
            }
          } else {
            userProfile.premium = true;
            userProfile.premiumEndDate = new Date(
              now.getTime() + threeMonthsInMillis
            );
          }

          await userProfile.save();
        }
        break;
      // ... handle other event types
      default:
        console.log(`Unhandled event type ${event.type}`);
    }

    // Return a 200 response to acknowledge receipt of the event
    response.send();
  }
);```
rough crag
neon folio
#

kay thanks