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

请求修改Stripe Payment Intent代码以支持订阅及额外字段

解决方案

首先明确:Stripe的Payment Intent仅用于单次收款,月度自动扣费需要使用「订阅(Subscription)」体系,核心涉及Customer、Price、Subscription三个核心对象,以下是适配需求的完整代码及说明:

完整修改后的代码

// 初始化Stripe(请替换为你的API秘钥)
\Stripe\Stripe::setApiKey('你的Stripe秘钥');

// 1. 创建Stripe客户对象,同步姓名、邮箱、地址(这些字段会直接显示在Stripe后台客户详情中)
$customer = \Stripe\Customer::create([
    'name' => $name, // 用户姓名
    'email' => $email, // 用户邮箱
    'address' => [
        'line1' => $address_line1, // 地址第一行(如街道门牌号)
        'line2' => $address_line2, // 地址第二行(如公寓号,可选)
        'city' => $address_city, // 城市
        'postal_code' => $address_postal_code, // 邮政编码
        'country' => $address_country, // 国家代码(如GB代表英国)
    ],
    'metadata' => [
        'order_id' => $invID, // 原订单ID
        'product_title' => $product_title, // 产品标题
    ],
]);

// 2. 创建订阅价格(若已有固定月度套餐的价格ID,可跳过此步骤直接使用已有ID)
$price = \Stripe\Price::create([
    'currency' => 'gbp',
    'unit_amount' => $obj1, // 月度扣费金额,注意是最小货币单位(如10英镑需填1000)
    'recurring' => [
        'interval' => 'month', // 扣费周期:月度
    ],
    'product_data' => [
        'name' => $product_title, // 产品名称,会显示在用户账单及Stripe后台
    ],
]);

// 3. 创建订阅,绑定客户与价格,开启自动扣费
$subscription = \Stripe\Subscription::create([
    'customer' => $customer->id,
    'items' => [
        ['price' => $price->id], // 关联上述价格(或已有价格ID)
    ],
    'payment_behavior' => 'default_incomplete', // 处理支付方式缺失的场景
    'payment_settings' => [
        'save_payment_method' => 'on_subscription', // 保存支付方式用于后续自动扣费
    ],
    'expand' => ['latest_invoice.payment_intent'], // 展开关联的支付意向,用于前端完成首次支付
]);

// 若需前端处理支付,可将此client_secret返回给前端
$clientSecret = $subscription->latest_invoice->payment_intent->client_secret;

关键说明

  • 客户信息存储:姓名、邮箱、地址直接存入Stripe Customer的原生字段(而非仅metadata),在Stripe后台可直接查看完整客户信息,无需额外提取。
  • 订阅价格复用:如果你的月度套餐是固定的,建议直接在Stripe后台手动创建Price并获取ID,代码中直接使用该ID即可,无需每次创建。
  • 自动扣费逻辑:订阅创建后,Stripe会在每个周期自动发起扣费,前提是客户的支付方式有效且未过期。
  • 首次支付处理:前端需收集用户支付方式(如信用卡),通过返回的client_secret完成首次支付,后续扣费将自动使用保存的支付方式。

内容的提问来源于stack exchange,提问作者Mark David

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 10:35:18