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

如何通过Stripe API关联Price/Product与PaymentLink?

问题描述

我正在尝试构建一个如图所示的订阅页面:
Payment Layout

我已实现GetPrices方法用于获取Stripe价格,且已包含Price对应的Product信息:

public StripeList<Price> GetPrices()
{
    StripeConfiguration.ApiKey = Options.SecretKey;

    var service = new PriceService();

    var priceListOption = new PriceListOptions
    {
        Limit = 3,
        Active = true
    };

    priceListOption.AddExpand("data.product");

    return service.List(options: priceListOption);
}

同时我还实现了GetPaymentLinks方法,可返回指定数量的PaymentLinks:

public StripeList<PaymentLink> GetPaymentLinks(int count)
{
    StripeConfiguration.ApiKey = Options.SecretKey;

    var paymentLinkListOptions = new PaymentLinkListOptions
    {
        Limit = count,
        Active = true
    };

    var service = new PaymentLinkService();

    return service.List(paymentLinkListOptions);
}

但我无法找到Price/Product与PaymentLinks之间的关联方式。我可以遍历Prices列表展示名称、描述和价格,但需要在“立即购买”按钮中使用对应的PaymentLink,请问通过Stripe API能否实现该需求?

解决方案

可以实现,通过Stripe API的字段扩展功能,就能获取Payment Link与Price/Product的关联关系,具体步骤如下:

1. 修改GetPaymentLinks方法,扩展关联字段

在获取Payment Links时,添加对line_items.price以及price.product的扩展,这样就能拿到每个Payment Link关联的Price和Product信息:

public StripeList<PaymentLink> GetPaymentLinks(int count)
{
    StripeConfiguration.ApiKey = Options.SecretKey;

    var paymentLinkListOptions = new PaymentLinkListOptions
    {
        Limit = count,
        Active = true
    };

    // 扩展获取line_items对应的price,以及price关联的product
    paymentLinkListOptions.AddExpand("data.line_items.price");
    paymentLinkListOptions.AddExpand("data.line_items.price.product");

    var service = new PaymentLinkService();

    return service.List(paymentLinkListOptions);
}

2. 建立Price与Payment Link的映射关系

在业务逻辑中,将获取到的Prices和Payment Links通过Price ID进行关联,生成映射字典,方便后续渲染页面时快速查找:

var prices = GetPrices();
var paymentLinks = GetPaymentLinks(3);

// 构建Price ID到Payment Link URL的映射字典
var priceToPaymentLinkMap = new Dictionary<string, string>();
foreach (var link in paymentLinks.Data)
{
    // 假设每个订阅场景的Payment Link仅关联一个Price,若有多个可根据业务调整
    if (link.LineItems?.Data != null && link.LineItems.Data.Any())
    {
        var targetPrice = link.LineItems.Data.First().Price;
        priceToPaymentLinkMap[targetPrice.Id] = link.Url;
    }
}

// 遍历Prices渲染页面,同时匹配对应的Payment Link
foreach (var price in prices.Data)
{
    var product = price.Product as Product;
    // 查找当前Price对应的Payment Link URL
    priceToPaymentLinkMap.TryGetValue(price.Id, out var paymentLinkUrl);

    // 这里可以用以下数据渲染订阅卡片:
    // product.Name(产品名称)、product.Description(产品描述)
    // price.UnitAmountDecimal(价格)、paymentLinkUrl(立即购买按钮跳转链接)
}

补充方案:通过Metadata关联

如果在创建Payment Link时,预先给它添加metadata(比如存入price_id或product_id),也可以直接通过Metadata字段进行匹配,这种方式更灵活,适合复杂业务场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 12:35:26