无法通过Stripe API获取客户默认支付方式问题求助
问题
我尝试通过Stripe API,先从订阅(Subscription)、再从客户档案(Customer)中获取客户的默认支付方式,代码如下:
try { $subscription = \Stripe\Subscription::retrieve($subscriptionId); $defaultPaymentMethodId = $subscription->default_payment_method; if (empty($defaultPaymentMethodId)) { $customer = \Stripe\Customer::retrieve($customerId); $defaultPaymentMethodId = $customer->invoice_settings->default_payment_method; } if (!empty($defaultPaymentMethodId)) { $paymentMethod = \Stripe\PaymentMethod::retrieve($defaultPaymentMethodId); $last4 = $paymentMethod->card->last4; $exp_year = $paymentMethod->card->exp_year; $exp_month = sprintf("%02d", $paymentMethod->card->exp_month); $brand = ucwords($paymentMethod->card->brand); $has_payment_method = true; // Set to true if a payment method is found } else { $last4 = $exp_year = $exp_month = $brand = null; // Set these to null to avoid potential issues } } catch (Exception $e) { logError('Stripe API error trying to get payment method details: ' . $e->getMessage()); }
但两种方式均返回null,尽管在Stripe后台可看到该客户已设置默认支付方式(仅支持银行卡)。其他API功能正常,仅无法获取默认支付方式,求可行排查方案。
排查方案
- 检查API版本兼容性:Stripe的
default_payment_method字段是较新API版本引入的,确认你的SDK使用的API版本不低于2019-03-14,版本过低会导致该字段不返回,需升级SDK或在请求中指定更高API版本。 - 确认支付方式关联字段:后台显示的默认支付方式可能关联的是旧版
default_source字段(对应Source对象)而非新版invoice_settings.default_payment_method,尝试获取$customer->default_source,再通过\Stripe\Source::retrieve()读取卡片信息。 - 验证订阅支付设置:直接在Stripe Dashboard查看订阅详情,确认
default_payment_method是否为空;或在API请求中添加expand[]=default_payment_method参数,确保拉取完整的关联数据。 - 检查API密钥权限:确认当前使用的Secret Key拥有读取客户、订阅的权限,避免因权限不足导致字段被过滤。
- 核对环境一致性:确保代码使用的API密钥对应的环境(测试/生产)与你查看后台的环境一致,跨环境查询会导致数据不匹配。
- 打印完整响应日志:在代码中添加日志,输出
$subscription和$customer的完整响应数据,检查是否存在目标字段及字段值是否正确。 - 确认支付方式状态:检查后台显示的默认支付方式状态是否为
active,若处于未激活、过期或无效状态,API可能不会返回该字段。
内容的提问来源于stack exchange,提问作者Kai
相关产品推荐
相关产品推荐

