Passing Stripe Checkout ID to Django URL

Viewed 49

The success page, which contains the download link to download a file after completing the purchase should be accessible only after having done the payment.

The idea is to pass the {CHECKOUT_SESSION_ID} to the success url. Only if the correct url .../success/?session_id={CHECKOUT_SESSION_ID} is inserted the page is accessible.

How can I pass the {CHECKOUT_SESSION_ID} to my url?

Here is my views.py file:

def success(request):
    return render(request, 'checkout/success.html')

def index(request):
    # sendMail()

    try:
        checkout_session = stripe.checkout.Session.create(
            line_items = [
                {
                    'price': 'price_1LUvcWKKYbcIekP0ZtUlCmAI',
                    'quantity': 1,
                },
            ],
        mode = 'payment',
        success_url = 'http://127.0.0.1:8000/checkout/success' + '/?session_id={CHECKOUT_SESSION_ID}',

        cancel_url = 'http://127.0.0.1:8000/create/',

        )


    except Exception as e:
        return str(e)

    return redirect(checkout_session.url, code=303)

And this is my urls.py file:

from django.urls import path
from checkout.views import *

app_name = 'checkout'

urlpatterns = [
    path('', index, name='index'),
    path('success/', success, name='success'),
]

This is the html file which I copied from stripe. It is called by a "Pay Now" button.

<!DOCTYPE html>
<html>
  <head>
    <title>Buy cool new product</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?version=3.52.1&features=fetch"></script>
    <script src="https://js.stripe.com/v3/"></script>
  </head>
  <body>
    <section>
      <div class="product">
        <img src="https://i.imgur.com/EHyR2nP.png" alt="The cover of Stubborn Attachments" />
        <div class="description">
          <h3>Stubborn Attachments</h3>
          <h5>$20.00</h5>
        </div>
      </div>
      <form action="/create-checkout-session" method="POST">
        <button type="submit" id="checkout-button">Checkout</button>
      </form>
    </section>

  </body>
</html>
1 Answers

You set well the {CHECKOUT_SESSION_ID} in the success page as a query param:

success_url = 'http://127.0.0.1:8000/checkout/success' + '/?session_id={CHECKOUT_SESSION_ID}'

When the checkout session succeeds, Stripe will fill {CHECKOUT_SESSION_ID} with the right value and redirect the user to the appropriate success_url

On your side, while defining the page /checkout/success in your application, you should get the value of the query param session_id and use in order to customize your success page,

For further details you can refer to this link: https://stripe.com/docs/payments/checkout/custom-success-page

Related