Fady's Cube
Fady's Cube

Reputation: 318

How to execute code whenever a Stripe session has been paid

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.

Upvotes: 0

Views: 262

Answers (2)

codename_duchess
codename_duchess

Reputation: 921

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

Upvotes: 1

Pretpark
Pretpark

Reputation: 383

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.

Upvotes: 0

Related Questions