Home > Net >  Retrieve stripe session id at success page
Retrieve stripe session id at success page

Time:04-25

I am using stripe with django and I want to pass some information I received from the checkout session to success page.

After reading the documentation https://stripe.com/docs/payments/checkout/custom-success-page#modify-success-url I modified success url to

MY_DOMAIN = 'http://127.0.0.1:8000/orders'

success_url=MY_DOMAIN   '/success?session_id={CHECKOUT_SESSION_ID}',
cancel_url=YOUR_DOMAIN   '/cancel/',
            metadata={
                "price_id": price_id,
                
                }
            )

def Success(request):
    session = stripe.checkout.Session.retrieve('session_id')
    return render(request, 'orders/success.html')

But this gives me an error:

Invalid checkout.session id: session_id

If I manually put instead of "session_id" the actual id that is printed in the url everything works fine.

So my question is what should I write instead of 'session_id' in order to retrieve the session?

CodePudding user response:

When using the prebuilt checkout page, you provide Stripe with the success url to send the user to when they successfully complete a payment. This is done like so:

checkout_session = stripe.checkout.Session.create(
                        line_items=[{'price': price, 'quantity': 1}],
                        payment_method_types=['card'],
                        mode='payment',
                        success_url="http://yoursite.com/order/success?session_id={CHECKOUT_SESSION_ID}"
                        cancel_url=domain   cancelURL,
                    )

return redirect(checkout_session.url)

This will create a Stripe checkout session and send the user to it. Once the user successfully pays, Stripe will send them to the success_url you provided and put in the correct checkout session id.

You will have to use webhooks to get the data you want, save it to your database, and then query the database in the success page view. Getting the checkout session id from the success page URL will depend on if you are using a GET like in the example above or as part of the URL like https://yoursite.com/order/12345. If you use the GET method, see here for more info.

  • Related