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

Stripe订阅会话创建:多价格产品的用户选择方案咨询

实现用户选择产品对应价格的Stripe订阅方案

你的现有代码已经具备接收前端传入priceId的能力,只需要补充前端价格选择界面和后端价格合法性校验,就能支持多价格选择场景,具体步骤如下:

1. 后端获取目标产品的所有价格列表

先通过Stripe的Price API获取对应产品下的所有有效价格,返回给前端用于展示选择。示例代码(C#):

// 替换为你的目标产品ID
var targetProductId = "prod_xxxxxx";

var priceOptions = new PriceListOptions
{
    Product = targetProductId,
    Active = true, // 只获取激活状态的价格
    Limit = 100
};

var service = new PriceService();
StripeList<Price> prices = await service.ListAsync(priceOptions);

// 将价格列表转换为前端需要的格式(比如包含priceId、金额、货币、地区描述)
var priceSelectOptions = prices.Data.Select(p => new 
{
    Id = p.Id,
    DisplayText = $"{p.UnitAmountDecimal / 100} {p.Currency.ToUpper()} ({p.Metadata["region"] ?? "通用"})"
}).ToList();

// 返回给前端(比如通过API接口或视图模型)
return Json(priceSelectOptions);

2. 前端渲染价格选择控件

把后端返回的价格列表渲染成用户可选择的控件,比如下拉框或单选按钮:

<!-- 下拉框示例 -->
<label for="priceId">选择订阅方案:</label>
<select id="priceId" name="priceId" required>
    <!-- 后端渲染的选项 -->
    @foreach(var option in Model.PriceSelectOptions)
    {
        <option value="@option.Id">@option.DisplayText</option>
    }
</select>

3. 后端校验传入的priceId合法性

为了防止恶意传入其他产品的priceId,在创建会话前添加校验逻辑:

var selectedPriceId = Request.Form["priceId"];
var priceService = new PriceService();
Price selectedPrice = await priceService.GetAsync(selectedPriceId);

// 校验该价格属于目标产品
if(selectedPrice.Product != targetProductId)
{
    // 返回错误提示,比如跳转错误页或返回JSON错误
    return BadRequest("无效的订阅方案");
}

// 原有的会话创建逻辑
var options = new SessionCreateOptions
{
    SuccessUrl = successUrl,
    CancelUrl = cancelUrl,
    Mode = "subscription",
    AllowPromotionCodes = true,
    LineItems = new List<SessionLineItemOptions>
    {
        new SessionLineItemOptions
        {
            Price = selectedPriceId,
            Quantity = 1,
        },
    }
};

var sessionService = new SessionService();
Session session = await sessionService.CreateAsync(options);

其他可选优化

  • 可以根据用户的IP自动识别地区,默认选中对应地区的价格,提升用户体验
  • 在价格的Metadata中存储地区、套餐类型等信息,方便前端展示更清晰的描述

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 16:35:28