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

Django项目集成Stripe:PaymentIntent代码及秘钥获取咨询

Django集成Stripe收款解决方案

1. 补全PaymentIntent创建代码

Stripe的PaymentIntent是处理收款的核心对象,对应Flask示例里的intent = # ...,在Django中你需要用Stripe SDK实现这部分逻辑:

首先安装Stripe SDK:

pip install stripe

在Django视图中编写创建接口:

import stripe
from django.conf import settings
from django.http import JsonResponse

# 配置Stripe秘钥(从settings.py读取,不要硬编码)
stripe.api_key = settings.STRIPE_SECRET_KEY

def create_payment_intent(request):
    if request.method == 'POST':
        try:
            # 前端传入的金额需转换为最小货币单位(比如美元转美分,人民币转分)
            amount = int(request.POST.get('amount')) * 100
            # 创建PaymentIntent
            intent = stripe.PaymentIntent.create(
                amount=amount,
                currency='usd',  # 按需修改货币类型,如'cny'
                # 可选:添加元数据记录捐赠相关信息
                metadata={'project': 'university donation page'}
            )
            # 返回客户端秘钥给前端
            return JsonResponse({'clientSecret': intent.client_secret})
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=400)

这段代码里的stripe.PaymentIntent.create(...)就是你需要补全的核心部分,关键参数是金额、货币,可按需添加元数据。

2. 理解“用fetch获取客户端秘钥”

clientSecret是Stripe用于前后端安全交互的凭证,绝对不能硬编码在前端,必须通过后端接口动态获取。浏览器的fetch函数就是用来发送HTTP请求到你刚写的Django接口,拿到这个秘钥,再用它初始化前端支付流程。

前端示例代码(嵌入Django模板):

<script src="https://js.stripe.com/v3/"></script>
<script>
// 初始化Stripe,这里填你的Stripe公钥(不是秘钥)
const stripe = Stripe('pk_your_public_key');
const cardElement = stripe.elements().create('card');
cardElement.mount('#card-element'); // 挂载到页面的卡片输入容器

// 绑定捐赠按钮点击事件
document.getElementById('donate-btn').addEventListener('click', async () => {
    // 用fetch发送POST请求到后端接口
    const response = await fetch('/create-payment-intent/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-CSRFToken': '{{ csrf_token }}'  // Django必须携带CSRF令牌
        },
        body: `amount=${document.getElementById('donation-amount').value}`
    });
    const data = await response.json();
    
    // 用拿到的clientSecret发起支付确认
    const { error } = await stripe.confirmCardPayment(data.clientSecret, {
        payment_method: {
            card: cardElement,
            billing_details: {
                name: document.getElementById('donor-name').value
            }
        }
    });
    
    if (error) {
        // 处理支付错误
        alert(`支付失败:${error.message}`);
    } else {
        // 支付成功后的逻辑,比如跳转感谢页
        window.location.href = '/thank-you/';
    }
});
</script>

核心流程总结:

  • 用户输入捐赠金额,点击按钮
  • 前端通过fetch调用后端接口,后端创建PaymentIntent并返回clientSecret
  • 前端用clientSecret调用Stripe的支付确认接口,完成收款

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 15:21:02