简体   繁体   中英

How to retrieve a stripe subscription id after a checkout session in a django project?

Here is my problem. I made a stripe subscription for my django project, and I used the checkout session method. I would like to retrieve the stripe subscription id, after the payment, to put it on my customer model, so I can make a cancel subscription method for the customer, because the method given by stripe require to have this id:

stripe.Subscription.modify(
  *sub_id*,
  cancel_at_period_end=True
)

or

stripe.Subscription.delete(*sub_id*)

The problem is that I can't find the id anywhere else than in my stripe account, where I have every informations I can need, but I can't find how to retrieve it through code after the payment has been done. I need to fill the field 'stripe_sub_id' in my customer model so i can make the cancel method work.

Here is the method that creates the checkout session

@csrf_exempt
def create_checkout_session(request):
    if request.method == 'GET':
        domain_url = 'http://127.0.0.1:8000/'
        stripe.api_key = settings.STRIPE_SECRET_KEY
        try:
            checkout_session = stripe.checkout.Session.create(
                success_url=domain_url + 'projets/success?session_id={CHECKOUT_SESSION_ID}',
                cancel_url=domain_url + 'projets/cancelled/',
                payment_method_types=['card'],
                mode='subscription',
                line_items=[
                    {
                        'price': sub_price_id,
                        'quantity': 1,
                    }
                ]
            )

            return JsonResponse({'sessionId': checkout_session['id']})
        except Exception as e:
            return JsonResponse({'error': str(e)})

And here is my script to activate the session

//Get stripe publishable key
fetch("/projets/config/")
.then((result) => { return result.json(); })
.then((data) => {
  // Initialize Stripe.js
  const stripe = Stripe(data.publicKey);
  console.log('fetch 1 reached'); //console check
  //Event handler
  document.querySelector("#payBtn").addEventListener("click", () => {
      // Get Checkout Session ID
      fetch("/projets/create-checkout-session/")
      .then((result) => { return result.json(); })
      .then((data) => {
        console.log(data);
        // Redirect to Stripe Checkout
        return stripe.redirectToCheckout({sessionId: data.sessionId})
      })
      .then((res) => {
          console.log(res);
      });
  });
});

Hope I gave enough informations, thanks in advance for your assistance.

While you should always listen to checkout.session.completed webhooks to take internal actions, you can also optionally receive the Checkout session ID in the success_url using a custom query parameter .

With this ID, you can then retrieve the session from your server and use expansion to include the subscription details with expand[]=subscription .

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