Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify for which user the stripe webhook route has been called?

I am trying to implement a stripe subscription to my web app. I am using the stripe checkout session for this purpose.

I followed the stripe documentation https://stripe.com/docs/billing/subscriptions/build-subscriptions?ui=checkout

Whenever the checkout is completed checkout.session.completed event is fired. During this event I want to set subscriptionStatus from false to true in my database. But I am unable to identify for which user the /webhooks route has been called.

Here is my code:

export const postStripeWebhook = async (req: ExtendedRequest, res: Response) => {
    let data;
    let eventType;
    let event = req.body;
    const webhookSecret = "web hook secret provided by stripe";
    if (webhookSecret) {
        let signature = req.headers["stripe-signature"];

        try {
            event = stripe.webhooks.constructEvent(req.body, signature , webhookSecret);
        } catch (err) {
            console.log(`⚠️  Webhook signature verification failed.`);  //This part is throwing the error
            return res.sendStatus(400);
        }
        
        data = event.data;
        eventType = event.type;
    } else {
       
       
        data = req.body.data;
        eventType = req.body.type;
    }
    let subscription;

    switch (eventType) {
         
       case checkout.session.completed:
       
           //Logic to update subscriptionStatus of the user in the database 

       break;


       //other events are handles




    }

    res.sendStatus(200);
};

Please guide me on how to identify the user.

like image 544
Pawan Avatar asked Sep 19 '25 13:09

Pawan


1 Answers

Under subscription mode, customer ID can be found under customer parameter in checkout.session.completed event. You can then use Customer Retrieval API to find the customer information.

Alternatively, you can create a Customer first, then set it in customer parameter when creating a Checkout Session. This allows you to identify the user with customer parameter in checkout.session.completed event afterwards.

like image 102
yuting Avatar answered Sep 23 '25 11:09

yuting