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

如何在CodeIgniter PHP中配置含安装费的Stripe月度订阅

CodeIgniter中配置Stripe月度订阅(含月中注册安装费)

需求梳理

  • 每月固定收取29.99美元订阅费,扣费日期为用户注册当日
  • 用户月中注册时,首笔账单需额外收取50美元一次性安装费,与当月订阅费合并支付
  • 后续每月自动在注册日扣取29.99美元

代码修改与完整实现

确保已在CodeIgniter中正确集成Stripe PHP SDK,按以下逻辑实现:

<?php
// 1. 创建或复用产品(建议提前在Stripe后台创建,也可代码创建)
$product = \Stripe\Product::create([
    'name' => 'Monthly Plan Home Internet',
]);

// 2. 创建月度订阅价格(单位为分,29.99美元=2999分)
$subscriptionPrice = \Stripe\Price::create([
    'unit_amount' => 2999,
    'currency' => 'usd',
    'recurring' => ['interval' => 'month'],
    'product' => $product->id,
]);

// 3. 创建一次性安装费价格(50美元=5000分,非循环类型)
$setupFeePrice = \Stripe\Price::create([
    'unit_amount' => 5000,
    'currency' => 'usd',
    'product' => $product->id,
]);

// 4. 创建客户(使用Stripe推荐的payment_method替代旧版source)
$customer = \Stripe\Customer::create([
    'email' => $email,
    'payment_method' => $token,
    'invoice_settings' => [
        'default_payment_method' => $token,
    ],
]);

// 5. 构建订阅参数,判断是否添加安装费
$subscriptionParams = [
    'customer' => $customer->id,
    'items' => [
        ['price' => $subscriptionPrice->id],
    ],
    'payment_behavior' => 'default_incomplete',
    'expand' => ['latest_invoice.payment_intent'],
];

// 示例:以注册日不是当月1号作为"月中注册"判断标准,可按需调整逻辑
$currentDay = date('j');
if ($currentDay != 1) {
    $subscriptionParams['add_invoice_items'] = [
        ['price' => $setupFeePrice->id],
    ];
}

// 6. 创建订阅
$subscription = \Stripe\Subscription::create($subscriptionParams);

// 返回关键信息给前端(可选)
echo json_encode([
    'subscription_id' => $subscription->id,
    'client_secret' => $subscription->latest_invoice->payment_intent->client_secret ?? null
]);
?>

关键说明

  • 价格区分:订阅费设为recurring循环类型,安装费为一次性非循环价格,需分别创建
  • API规范:使用payment_method替代旧版source,符合Stripe最新API要求,同时设置默认支付方式便于后续自动扣费
  • 安装费触发:通过日期判断逻辑决定是否添加一次性发票项,首笔账单自动合并订阅费与安装费,后续仅收取订阅费
  • 支付容错:payment_behavior设为default_incomplete,避免支付失败直接取消订阅,提升用户支付体验

内容的提问来源于stack exchange,提问作者Hassan Javaid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 21:10:29