简体   繁体   中英

How to Cancel Subscription created thought Checkout Session Stripe API

I have created a recurring product on stripe, and creating a checkout session and it's working fine and creating a subscription for me that i can see on the dashboard.

this is my code

        checkout_session = stripe.checkout.Session.create(
            success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}',
            cancel_url=domain_url + 'cancelled/',
            payment_method_types=['card'],
            mode='subscription',
            line_items=[
                {
                    'quantity': 1,
                    'price': 'price_1HLDRqCHEV6ur4mXq36yVF1D',
                }
            ]
        )

I want to provide a facility to user that they can cancle their subscription that they have made through checkout session, but it can be cancelled through subscription id only, but i am not getting any subscription id from the checkout session.

How can i allow the user to cancle their subscription that they made through checkout session ?

When you create a subscription using Stripe Checkout, the subscription will only be created and available after your user's have gone through the Checkout flow. What this means is that when you initially create the Checkout Session the session object's subscription property will be null .

As soon as your user's complete the checkout flow, Stripe will emit a checkout.session.completed event containing the newly created subscription ID which you can use to cancel the subscription. To listen for these events you need to create a webhook endpoint, which is really no different than creating any other HTTP endpoint on your site. Here are some examples that you can reference:

Once you have an endpoint setup to listen for the checkout.session.completed event. Stripe will send the updated session object (with the subscription ID) in the event data . From there you can save the subscription ID to your database to reference later. If your user's want to cancel the subscription you would need to call this API endpoint here:

https://stripe.com/docs/api/subscriptions/cancel?lang=python

Another simpler option would be to use the new Customer Portal which would save you from having to create a UI for your users to upgrade/cancel your existing subscriptions. Simply provide the customer's ID as shown in this guide here:

https://stripe.com/docs/billing/subscriptions/integrating-customer-portal

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM