我正在尝试将条形定制支付流集成到我的Django ecom网站中,因为PayPal不是很好,但是python的docs (https://stripe.com/docs/payments/quickstart?lang=python)在烧瓶框架中。有谁在Django (视图、模板等)中有处理简单事务的样板代码吗?
发布于 2022-10-17 18:09:28
在理论上是,唯一需要改变的是代码的烧瓶部分,并将其转换为Django视图。
其余的html+js+css应该能够被复制+粘贴(特别是因为html是由Stripe动态创建的)
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
注意:您可能还必须更改.js中的两个URLS以匹配您的django。他们有什么"/create-payment-intent"
+ "http://localhost:4242/checkout.html"
(不知道为什么第二个是完整的url,但记住要使端口正确)
这将是您所包含的URL所显示的最基本的部分,您仍然需要弄清楚如何将items
放到checkout.html
中,动态地将它们传递到页面+最后发送到POST,然后重做calculate_order_amount(items)
。
发布于 2022-10-18 08:08:06
为了理解如何使用Stripepayement,我将分享我的GIT,其中包含了条付款,您可以参考
https://github.com/KBherwani/BookManagement/
https://stackoverflow.com/questions/74100476
复制相似问题