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

在Stripe API创建客户新支付源并设为默认:ID获取问题咨询

解决Stripe创建支付源并设置默认的问题

我一眼就看出你代码里的两个关键问题,这正是导致你拿不到新支付源ID、没法完成默认设置的原因:

  1. 创建支付源后没保留结果:你直接把create()的结果转成数组却没赋值给变量,相当于创建完就把这个新支付源的信息丢了,自然拿不到它的ID
  2. 默认支付源赋值错误:你把客户ID($customer['id'])赋值给了default_source,这明显不对,应该用新创建的支付源专属ID

下面是修正后的代码,每一步都加了清晰注释:

\Stripe\Stripe::setApiKey($stripe_api_key);

// 1. 获取目标客户对象
$customer = \Stripe\Customer::retrieve($_SESSION['parent']['stripe_customer_id']);

// 2. 创建支付源并将结果保存到变量,这样就能直接拿到新source的ID
$newPaymentSource = $customer->sources->create([
    'source' => [
        "object" => "card",
        'exp_month' => $expire_month,
        'exp_year' => $expire_year,
        'number' => $card_number,
        'address_line1' => $billing_address1,
        'address_line2' => $billing_address2,
        'address_city' => $billing_city,
        'address_zip' => $billing_postal_code,
        'address_country' => $billing_country,
        'currency' => 'GBP',
        'cvc' => $security_code,
        'name' => $_SESSION['parent']['firstname'] . ' ' . $_SESSION['parent']['lastname']
    ]
]);

// 3. 如果勾选了设置默认,用新支付源的ID来赋值并保存
if (isset($_POST['check_default_source'])) {
    $customer->default_source = $newPaymentSource->id; // 这里用新支付源的ID,不是客户ID!
    $customer->save();
}

额外提个小提醒:Stripe现在更推荐使用Payment Methods而非旧的Sources API,如果是新项目的话,建议迁移到Payment Methods体系;要是维护旧项目,上面的代码完全能解决你的问题~

内容的提问来源于stack exchange,提问作者Clint William Theron

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:21:22