请求将Stripe嵌入式Checkout Session的Flask教程适配为Django框架
Django 实现 Stripe 嵌入式 Checkout Session 支付方案
1. 环境准备与配置
- 安装 Stripe Python 依赖:
pip install stripe - 在 Django 项目的
settings.py中添加 Stripe 密钥配置:
STRIPE_SECRET_KEY = "你的Stripe秘钥" STRIPE_PUBLISHABLE_KEY = "你的Stripe公钥" STRIPE_WEBHOOK_SECRET = "你的Stripe Webhook秘钥"
2. 创建核心视图函数
2.1 渲染支付页面视图
返回包含嵌入式支付表单的页面:
from django.shortcuts import render from django.conf import settings def payment_page(request): return render(request, 'payment.html', { 'stripe_publishable_key': settings.STRIPE_PUBLISHABLE_KEY })
2.2 生成 Checkout Session API 视图
处理前端请求,创建指定 ui_mode='embedded' 的支付会话:
import stripe from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from django.conf import settings stripe.api_key = settings.STRIPE_SECRET_KEY @csrf_exempt def create_checkout_session(request): if request.method == 'POST': # 替换为实际商品/订单数据,可从请求体中获取订单ID等信息 try: session = stripe.checkout.Session.create( payment_method_types=['card'], line_items=[ { 'price_data': { 'currency': 'usd', 'product_data': {'name': '示例商品'}, 'unit_amount': 2000, # 单位为分,对应20美元 }, 'quantity': 1, }, ], mode='payment', ui_mode='embedded', return_url='http://localhost:8000/payment-success/', automatic_tax={'enabled': True}, ) return JsonResponse({'clientSecret': session.client_secret}) except Exception as e: return JsonResponse({'error': str(e)}, status=400)
2.3 支付成功页面视图
支付完成后的跳转页面:
def payment_success(request): return render(request, 'payment_success.html')
3. 配置 URL 路由
在项目 urls.py 中添加路由映射:
from django.urls import path from . import views urlpatterns = [ path('payment/', views.payment_page, name='payment_page'), path('create-checkout-session/', views.create_checkout_session, name='create_checkout_session'), path('payment-success/', views.payment_success, name='payment_success'), ]
4. 前端模板实现(payment.html)
嵌入 Stripe JS 并初始化嵌入式支付表单:
<!DOCTYPE html> <html> <head> <title>嵌入式支付</title> <script src="https://js.stripe.com/v3/"></script> </head> <body> <h1>完成支付</h1> <div id="payment-element"></div> <button id="submit-btn">确认支付</button> <div id="error-message" style="color:red;"></div> <script> const stripe = Stripe('{{ stripe_publishable_key }}'); // 请求创建支付会话 fetch("/create-checkout-session/", { method: "POST", headers: { "Content-Type": "application/json", "X-CSRFToken": "{{ csrf_token }}" }, }) .then(res => res.json()) .then(data => { const clientSecret = data.clientSecret; // 初始化支付元素 const appearance = { theme: 'stripe' }; const elements = stripe.elements({ clientSecret, appearance }); const paymentElement = elements.create('payment'); paymentElement.mount('#payment-element'); // 处理支付提交 document.getElementById('submit-btn').addEventListener('click', () => { stripe.confirmPayment({ elements, confirmParams: { return_url: "http://localhost:8000/payment-success/" }, }) .then(result => { if (result.error) { document.getElementById('error-message').textContent = result.error.message; } }); }); }); </script> </body> </html>
5. Webhook 支付状态通知(可选)
接收 Stripe 支付结果通知,更新本地订单状态:
import stripe from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from django.conf import settings stripe.api_key = settings.STRIPE_SECRET_KEY @csrf_exempt def stripe_webhook(request): payload = request.body sig_header = request.META.get('HTTP_STRIPE_SIGNATURE') event = None try: event = stripe.Webhook.construct_event( payload, sig_header, settings.STRIPE_WEBHOOK_SECRET ) except (ValueError, stripe.error.SignatureVerificationError): return HttpResponse(status=400) # 处理支付成功事件 if event['type'] == 'checkout.session.completed': session = event['data']['object'] # 此处可根据session中的metadata(如订单ID)更新本地订单状态 print(f"支付完成,Session ID: {session.id}") return HttpResponse(status=200)
在 urls.py 中添加 Webhook 路由:
path('stripe-webhook/', views.stripe_webhook, name='stripe_webhook'),
内容的提问来源于stack exchange,提问作者user6515293
相关产品推荐
相关产品推荐

