You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求Django电商网站集成Stripe自定义支付流程的样板代码

Django 集成 Stripe 自定义支付流程样板代码

1. 准备工作

  • 安装 Stripe SDK:pip install stripe
  • 在 Django 设置文件中配置密钥:
    # settings.py
    STRIPE_SECRET_KEY = "你的Stripe秘钥"
    STRIPE_PUBLISHABLE_KEY = "你的Stripe公钥"
    STRIPE_WEBHOOK_SECRET = "你的Stripe Webhook密钥(可选)"
    

2. 视图代码(views.py)

from django.shortcuts import render
from django.http import JsonResponse
import stripe
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt

stripe.api_key = settings.STRIPE_SECRET_KEY

def payment_page(request):
    return render(request, 'payment.html', {
        'STRIPE_PUBLISHABLE_KEY': settings.STRIPE_PUBLISHABLE_KEY
    })

def create_checkout_session(request):
    if request.method != 'POST':
        return JsonResponse({'error': '仅支持POST请求'}, status=405)
    
    # 替换为你的实际订单数据
    try:
        checkout_session = stripe.checkout.Session.create(
            payment_method_types=['card'],
            line_items=[
                {
                    'price_data': {
                        'currency': 'usd',
                        'product_data': {'name': '你的商品名称'},
                        'unit_amount': 2999,  # 单位为分,即29.99美元
                    },
                    'quantity': 1,
                }
            ],
            mode='payment',
            success_url=request.build_absolute_uri('/payment/success/'),
            cancel_url=request.build_absolute_uri('/payment/cancel/'),
        )
        return JsonResponse({'sessionId': checkout_session.id})
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=400)

def payment_success(request):
    return render(request, 'success.html')

def payment_cancel(request):
    return render(request, 'cancel.html')

# 接收Stripe支付结果通知的Webhook(可选但推荐)
@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 JsonResponse({'status': 'error'}, status=400)

    # 处理支付完成事件
    if event['type'] == 'checkout.session.completed':
        session = event['data']['object']
        # 这里可添加逻辑:更新订单状态、发送确认邮件等
        print(f"订单 {session.id} 支付完成")

    return JsonResponse({'status': 'success'})

3. URL 配置(urls.py)

from django.urls import path
from . import views

urlpatterns = [
    path('payment/', views.payment_page, name='payment_page'),
    path('payment/create-session/', views.create_checkout_session, name='create_checkout_session'),
    path('payment/success/', views.payment_success, name='payment_success'),
    path('payment/cancel/', views.payment_cancel, name='payment_cancel'),
    path('payment/stripe-webhook/', views.stripe_webhook, name='stripe_webhook'),
]

4. 模板文件

payment.html

<!DOCTYPE html>
<html>
<head>
    <title>完成支付</title>
    <script src="https://js.stripe.com/v3/"></script>
</head>
<body>
    <h2>请完成支付</h2>
    <button id="pay-btn">立即支付</button>

    <script>
        const stripe = Stripe('{{ STRIPE_PUBLISHABLE_KEY }}');
        const payBtn = document.getElementById('pay-btn');

        payBtn.addEventListener('click', async () => {
            const response = await fetch('/payment/create-session/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': '{{ csrf_token }}'
                }
            });
            const data = await response.json();
            if (data.error) {
                alert('创建支付会话失败:' + data.error);
                return;
            }
            const { error } = await stripe.redirectToCheckout({ sessionId: data.sessionId });
            if (error) alert(error.message);
        });
    </script>
</body>
</html>

success.html

<!DOCTYPE html>
<html>
<head>
    <title>支付成功</title>
</head>
<body>
    <h1>支付成功!</h1>
    <p>感谢你的购买,我们将尽快处理你的订单。</p>
</body>
</html>

cancel.html

<!DOCTYPE html>
<html>
<head>
    <title>支付取消</title>
</head>
<body>
    <h1>支付已取消</h1>
    <p>你可以返回重新尝试支付。</p>
    <a href="{% url 'payment_page' %}">返回支付页面</a>
</body>
</html>

5. 关键注意事项

  • 替换代码中的密钥、商品名称、金额为你的实际业务数据
  • 生产环境必须使用 HTTPS 协议,Stripe 不允许非安全环境下的支付请求
  • Webhook 需要在 Stripe 后台配置对应的公网 URL,用于接收支付状态通知

内容的提问来源于stack exchange,提问作者CharlieMcGuire

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 07:35:22