Интеграция потока платежей Stripe в django

Я пытаюсь интегрировать поток пользовательских платежей stripe в мой Django ecom сайт, так как PayPal не так хорош, но документация (https://stripe.com/docs/payments/quickstart?lang=python) для python находится во фреймворке flask. Есть ли у кого-нибудь шаблонный код для обработки простой транзакции для этого в Django (представления, шаблон и т.д.)

В теории, единственное, что нужно изменить, это часть кода flask и изменить его на Django view(s).
Остальное, html+js+css, должно быть возможно скопировать + вставить (особенно потому, что html динамически создается Stripe JS)

views.py

from django.shortcuts import render
from django.http import HttpResponse

# The GET checkout form
#
# urlpattern: 
#   path('checkout', views.checkout, name='checkout'),
def checkout(request):
    return render(request, 'checkout.html')

# The POST checkout form
#
# urlpattern: 
#   path('create-payment-intent', views.create_payment, name='create_payment'),
def create_payment(request):
    if request.method == 'POST':
        import json
        try:
            data = json.loads(request.POST)

            def calculate_order_amount(items):
                # Replace this constant with a calculation of the order's amount
                # Calculate the order total on the server to prevent
                # people from directly manipulating the amount on the client
                return 1400

            # this api_key could possibly go into settings.py like:
            #   STRIPE_API_KEY = 'sk_test_4eC39HqLyjWDarjtT1zdp7dc'
            #
            # and fetched out with:
            #   from django.conf import settings
            #   stripe.api_key = settings.STRIPE_API_KEY

            import stripe
            stripe.api_key = 'sk_test_4eC39HqLyjWDarjtT1zdp7dc'

            # Create a PaymentIntent with the order amount and currency
            intent = stripe.PaymentIntent.create(
                amount=calculate_order_amount(data['items']),
                currency='usd',
                automatic_payment_methods={
                    'enabled': True,
                },
            )
            return HttpResponse(
                json.dumps({'clientSecret': intent['client_secret']}),
                content_type='application/json'
            )
        except Exception as e:

            # Just return the 403 and NO error msg
            #   Not sure how to raise a 403 AND return the error msg
            from django.http import HttpResponseForbidden
            return HttpResponseForbidden()

            # OR you could return just the error msg
            #   but the js would need to be changed to handle this
            return HttpResponse(
                json.dumps({'error': str(e)}),
                content_type='application/json'
            )

    # POST only View, Raise Error
    from django.http import Http404
    raise Http404

Примечание: Возможно, вам также придется изменить два URL в .js, чтобы они соответствовали URL вашего django. Что у них есть "/create-payment-intent" + "http://localhost:4242/checkout.html" (не уверен, почему второй - полный url, но не забудьте правильно указать порт)


Это просто голые основы, которые показывает ваш URL, который вы включили, вам все еще нужно выяснить, как получить items в checkout.html, динамически передать их на страницу + в конечном итоге в POST, а затем повторить calculate_order_amount(items)

Для понимания работы со Stripepayement я делюсь своим GIT URL, в который интегрирован stripe payment, вы можете посмотреть

     https://github.com/KBherwani/BookManagement/ 
Вернуться на верх