lf_celine
lf_celine

Reputation: 673

Retrieve customer ID in stripe during checkout

I have a Stripe checkout and I want to retrieve the customer ID if it'a success. I followed the Stripe tutorial but it doesn't work for me (The checkout works well but I can't retrieve the customer ID to add it to my User database)

My code:

router.post("/create-checkout-session", ensureAuthenticated, async (req, res) => {
    const { priceId } = req.body;

    // See https://stripe.com/docs/api/checkout/sessions/create
    // for additional parameters to pass.
    try {
      const session = await stripe.checkout.sessions.create({
        mode: "subscription",
        payment_method_types: ["card"],
        line_items: [
          {
            price: priceId,
            // For metered billing, do not pass quantity
            quantity: 1,
          },
        ],
        // {CHECKOUT_SESSION_ID} is a string literal; do not change it!
        // the actual Session ID is returned in the query parameter when your customer
        // is redirected to the success page.
        success_url: 'http://localhost:3000/fr/premiereconnexion?session_id={CHECKOUT_SESSION_ID}',
        cancel_url: 'https://localhost:3000/fr/erreursouscription',
      });
    
      res.send({
        sessionId: session.id,
        customerID: session.customer
      });
    }
    catch (e) {
    res.status(400);
    return res.send({
      error: {
        message: e.message,
      }
    });
  }
  }
});

Upvotes: 6

Views: 5408

Answers (2)

nackjicholson
nackjicholson

Reputation: 4839

Using the stripe Java API, I found a method on com.stripe.param.checkout.SessionCreateParams.Builder.setCustomerCreation. If you give it a value from the enum com.stripe.param.checkout.SessionCreateParams.CustomerCreation.ALWAYS then it will give you a customer id on the session when you retrieve it.

Upvotes: 0

Zhi Kai
Zhi Kai

Reputation: 1587

How are you retrieving the Customer ID?

You should process the success_url by extracting the query params and retrieving session_id through an API call to Stripe to obtain the customer: https://stripe.com/docs/api/checkout/sessions/retrieve. So you should have a get(...) route for the success_url route.

Alternatively, listen to the checkout.session.completed webhook event.

Upvotes: 5

Related Questions