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

Laravel集成Stripe时如何从Card Element获取卡信息创建支付方式及客户

正确实现流程

Stripe Card Element的设计初衷就是为了让商户服务端完全不接触卡片敏感数据,所以你绝对不能尝试从Card Element里直接提取卡号、有效期、CVC这类参数,也不需要这么做,支付方法的创建逻辑要移到前端通过Stripe.js完成,后端只拿返回的支付方法ID做后续操作即可。

第一步:前端配置Stripe.js并创建支付方法

Card Element是Stripe托管的跨域iframe,你无法通过DOM操作读取内部的敏感卡片信息,直接调用Stripe.js提供的createPaymentMethod方法,传入Card Element实例即可自动完成支付方法创建:

// 初始化Stripe,替换为你的Stripe公钥
const stripe = Stripe('pk_test_xxxxxxxxxxxx');
const elements = stripe.elements();
// 挂载Card Element到页面节点
const cardElement = elements.create('card');
cardElement.mount('#card-element');

// 绑定表单提交事件
const form = document.getElementById('payment-form');
form.addEventListener('submit', async (event) => {
  event.preventDefault();
  // 直接传入Card Element实例创建支付方法,无需手动传敏感卡参数
  const {paymentMethod, error} = await stripe.createPaymentMethod({
    type: 'card',
    card: cardElement,
  });

  if (error) {
    // 处理卡信息校验错误,比如有效期无效、CVC位数不对等
    console.log(error.message);
    return;
  }
  // 拿到支付方法ID后,仅将ID和其他非敏感业务参数传给后端
  fetch('/你的后端处理路由', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
    },
    body: JSON.stringify({
      payment_method_id: paymentMethod.id,
      name: document.getElementById('username').value,
      email: document.getElementById('email').value
    })
  });
});

第二步:Laravel后端接收参数,创建客户并绑定默认支付方式

后端不需要处理任何卡片敏感参数,直接用前端传过来的支付方法ID调用客户创建接口即可:

// 校验参数
$validated = $request->validate([
    'payment_method_id' => 'required|string',
    'name' => 'required|string',
    'email' => 'required|email',
]);

// 创建Stripe客户并绑定默认支付方式
$customer = \Stripe\Customer::create([
    'name' => $validated['name'],
    'email' => $validated['email'],
    'payment_method' => $validated['payment_method_id'],
    'invoice_settings' => [
        'default_payment_method' => $validated['payment_method_id'],
    ],
]);

// 可将生成的客户ID存入你的用户表,方便后续发起扣款、管理支付方式
auth()->user()->update([
    'stripe_customer_id' => $customer->id,
]);

Omnipay扩展适配说明

如果你使用Omnipay的Stripe驱动,逻辑完全一致,直接传入前端生成的支付方法ID即可:

$gateway = Omnipay::create('Stripe');
$gateway->setApiKey('sk_test_xxxxxxxxxxxx');

$response = $gateway->createCustomer([
    'description' => $validated['name'],
    'email' => $validated['email'],
    'paymentMethod' => $validated['payment_method_id'],
])->send();

if ($response->isSuccessful()) {
    $customerId = $response->getCustomerReference();
    // 后续存储逻辑
}

注意事项

  • 不要尝试把任何卡片敏感信息传到你自己的服务端,否则会违反PCI合规要求,严重时会被Stripe冻结账号
  • 测试阶段可使用Stripe官方测试卡4242 4242 4242 4242,有效期填任意未来时间、CVC填任意3位数字即可完成测试流程
  • 后续如果需要发起自动扣款,直接调用Stripe接口使用存储的stripe_customer_id即可,不需要用户重复输入卡片信息

内容的提问来源于stack exchange,提问作者MARCO AURELIO YERA PARTIDA

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 08:27:00