Home > front end >  How to execute code whenever a Stripe session has been paid
How to execute code whenever a Stripe session has been paid

Time:09-02

I am using Stripe to integrate payments in my e-commerce website and Django as a web framework and I would like to create a custom administration site to manage the store, therefore I want to create a Command model whenever a stripe session has been paid.

from .models import Command # I have a Command model

class CommandView(views.APIView):
    def post(self, request, format=None):
        try:
            checkout_session = stripe.checkout.Session.create(
                line_items=[
                    {
                        'price': 'some price id',
                        'quantity': 1,
                    },
                ],
                mode='payment',
                success_url='http://localhost:3000/success/{CHECKOUT_SESSION_ID}',
                cancel_url='http://localhost:3000/store',
                billing_address_collection='auto',
            )
            if checkout_session['payment_status'] == 'paid':
                # this will never work because the status in this view is always unpaid
            return Response({'url': checkout_session['url']})
        except Exception as e:
            return Response({'error': e})

The solution I found is to execute the code in the success_url view but I'm wondering if it's possible to pay and to avoid getting into this url like immediately closing the tab... And maybe my solution of creating a Command model to see details of a command in the administration like color of product... is wrong, can you give some advices.

CodePudding user response:

You could try using Ajax to call your view function and handle it using JQuery / Javascript.

This stackoverflow question may be able to help you further.

CodePudding user response:

The recommended way to achieve this is through webhooks. This guide on fulfilling orders is a good example.

  • Related