
本文解释为何 stripe 旧版 checkout(modal 弹窗)无法正确响应测试卡(如 4000000000000002),并指出根本原因是未使用用户输入生成的 `stripetoken`,而是错误地复用了已有客户(customer)的默认支付方式。
你遇到的问题非常典型——Stripe 测试卡在旧版 Checkout 中“全部成功”,并非 Stripe 服务异常,而是集成逻辑存在关键缺陷。
? 根本原因:未使用实时输入的支付凭证
你的前端代码通过 checkout.js 正确弹出支付弹窗,并在用户输入卡号(如 4000000000000002)后,Stripe 会生成一个一次性、代表该次输入的 stripeToken(例如 tok_1Pabc...),并通过 POST 提交到你的服务端。但你在后端代码中却完全忽略了它:
'customer' => $_POST['customer_id'], // ❌ 错误:复用已有 customer 的默认卡
这意味着:
✅ Stripe 收到了请求;
✅ 但实际扣款的是 customer_id 对应客户早已绑定的某张有效测试卡(比如 4242424242424242);
❌ 用户在弹窗中输入的卡号、有效期、CVC 全部被丢弃,自然无法触发 card_declined 等预期错误。
正确做法是:使用 stripeToken 创建新支付意图,或将其附加到客户后再扣款。以下是修复后的服务端逻辑(推荐方式):
try {
// ✅ 正确:使用前端传来的 stripeToken 创建 Charge
$charge = \Stripe\Charge::create([
'amount' => 1000,
'currency' => 'usd',
'source' => $_POST['stripeToken'], // ← 关键!不是 customer_id
'description' => 'Single Credit Purchase'
]);
} catch (\Stripe\Exception\CardException $e) {
// ✅ 现在能捕获真实卡拒绝(如 card_declined, insufficient_funds)
$errors[] = $e->getError()->message;
} catch (\Stripe\Exception\RateLimitException $e) {
$errors[] = 'Too many requests. Please try again later.';
} catch (\Stripe\Exception\InvalidRequestException $e) {
$errors[] = 'Invalid parameters: ' . $e->getMessage();
} catch (\Stripe\Exception\AuthenticationException $e) {
$errors[] = 'Authentication failed. Check your secret key.';
} catch (\Stripe\Exception\ApiConnectionException $e) {
$errors[] = 'Network error. Please check your connection.';
} catch (\Stripe\Exception\ApiErrorException $e) {
$errors[] = 'Stripe API error: ' . $e->getMessage();
}⚠️ 注意:source 参数优先级高于 customer。若同时传入 source 和 customer,Stripe 会忽略 customer 并直接对 token 扣款——这正是你所需的行为。
? 为什么不应继续使用旧版 Checkout?
Stripe 官方已正式弃用(deprecated)checkout.js(v2),自 2020 年起不再维护,且存在严重限制:
- ❌ 不支持 SCA(Strong Customer Authentication)/3D Secure 2 —— 在欧盟、英国等地区将导致合规失败;
- ❌ 无内置账单地址验证、动态 CVC 检查等现代风控能力;
- ❌ 前端样式不可定制,移动端体验差;
- ❌ 测试卡行为不一致(如你所见),调试困难。
✅ 推荐迁移方案:使用 Stripe Elements + Confirm Card Payment
现代标准实践是:
- 前端用 Elements 构建自定义支付表单;
- 调用 stripe.createToken() 或 stripe.confirmCardPayment() 获取 payment_method;
- 后端调用 PaymentIntent::create() + confirm(),完整支持 SCA、测试卡、错误分类。
简要示例(前端):
const { paymentMethod, error } = await stripe.confirmCardPayment(clientSecret, {
payment_method: {
card: cardElement,
billing_details: { email: userEmail }
}
});
if (error) {
console.error('Decline reason:', error.code); // e.g., "card_declined"
} else {
console.log('Success!', paymentMethod);
}✅ 总结
| 问题现象 | 正确归因 | 解决动作 |
|---|---|---|
| 所有测试卡均“成功” | 后端未使用 stripeToken,误扣客户默认卡 | 将 source => $_POST['stripeToken'] 替换 customer => ... |
| 无法捕获 insufficient_funds 等错误 | 错误的异常类型捕获(旧 SDK 类名已废弃) | 使用 \Stripe\Exception\CardException 等新命名空间异常 |
| 长期技术风险 | checkout.js 已弃用,不支持 SCA | 立即规划迁移到 Stripe Elements + Payment Intents |
? 小贴士:Stripe 测试卡仅在 source 或 payment_method 上下文中生效。一旦绑定为 customer.default_source,它就变成“真实卡”,不再触发模拟拒绝。务必确保每次测试都使用全新 token。
立即检查你的表单是否提交了 stripeToken,并在服务端打印 $_POST 验证其存在——这是排查该问题最快的第一步。










