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

如何将dj-stripe与stripe.js集成并生成客户端密钥?

dj-stripe 结合 Stripe.js/Elements 实现支付流程

正确的集成路径

核心逻辑和Stripe官方推荐方案一致,dj-stripe仅做Django层面的封装,完整流程如下:

  1. 通过dj-stripe创建/关联Stripe客户(Customer)
  2. 后端用dj-stripe生成PaymentIntent并获取客户端密钥(client_secret)
  3. 前端用Stripe.js加载Elements组件,传入client_secret收集支付信息并完成支付
  4. 配置Stripe Webhook,通过dj-stripe接收支付状态更新

生成客户端密钥的具体实现

dj-stripe的PaymentIntent模型完全封装了Stripe官方API的对应功能,直接创建实例并关联客户即可拿到client_secret。

后端Django代码示例

假设你已经为用户关联了dj-stripe的Customer实例:

from djstripe.models import Customer, PaymentIntent
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt  # 测试环境临时用,生产需用CSRF防护

@csrf_exempt
def create_payment_intent(request):
    # 从当前用户获取绑定的Stripe客户(需提前为用户创建/关联Customer)
    customer = request.user.djstripe_customer

    # 创建PaymentIntent,金额单位为最小货币单位(如美元用分)
    payment_intent = PaymentIntent.objects.create(
        amount=1000,  # 等价于10美元
        currency="usd",
        customer=customer,
        payment_method_types=["card"]  # 指定支持的支付方式
    )

    # 返回客户端密钥给前端
    return JsonResponse({"client_secret": payment_intent.client_secret})

如果还未为用户创建Customer,可先执行:

from djstripe.models import Customer

# 为当前登录用户创建绑定的Stripe客户
customer = Customer.objects.create(subscriber=request.user)

前端Stripe.js/Elements代码示例

首先加载Stripe.js:

<script src="https://js.stripe.com/v3/"></script>
<div id="card-element"></div>
<form id="payment-form">
  <input type="text" id="billing-name" placeholder="持卡人姓名">
  <button type="submit">完成支付</button>
</form>

然后编写支付逻辑:

// 用你的Stripe公钥初始化
const stripe = Stripe('pk_test_你的公钥');
const elements = stripe.elements();

// 挂载卡片输入组件
const cardElement = elements.create('card');
cardElement.mount('#card-element');

// 处理表单提交
const form = document.getElementById('payment-form');
form.addEventListener('submit', async (event) => {
  event.preventDefault();

  // 调用后端接口获取client_secret
  const response = await fetch('/create-payment-intent/', { method: 'POST' });
  const data = await response.json();

  // 确认卡片支付
  const { error, paymentIntent } = await stripe.confirmCardPayment(
    data.client_secret,
    {
      payment_method: {
        card: cardElement,
        billing_details: {
          name: document.getElementById('billing-name').value
        }
      }
    }
  );

  if (error) {
    // 显示支付错误信息
    alert(error.message);
  } else {
    // 支付成功后的处理(如跳转成功页)
    if (paymentIntent.status === 'succeeded') {
      window.location.href = '/payment-success/';
    }
  }
});

关键注意事项

  • 务必配置Stripe Webhook:在Stripe后台设置webhook端点为你的Django项目的/djstripe/webhook/,并在Django的settings.py中设置DJSTRIPE_WEBHOOK_SECRET,用于接收支付状态更新(比如支付成功、失败等)。
  • 生产环境要移除csrf_exempt,前端请求时需携带CSRF令牌。
  • dj-stripe的PaymentIntent模型会自动同步Stripe端的状态,你可以通过查询该模型获取支付的最新状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 13:45:32