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

如何用Laravel Cashier通过price_ids数组从Stripe批量获取指定价格?

如何从Stripe批量获取指定ID的价格数据

问题背景

你需要一次性从Stripe获取多个指定price_id的价格数据,现有代码框架如下:

$stripe = Cashier::stripe();

$priceIds = [
    'price_1Ow....', 
    'price_12lsd...'
];

// do something...

你之前尝试用lookup_keys参数调用prices->all()但无法正常运行:

$stripe = Cashier::stripe();
$prices = $stripe->prices->all(
    [
        'lookup_keys' => $priceIds
    ]
);

核心问题

lookup_keys是价格对象的自定义标识字段,和price_id不是同一个属性,所以直接传入price_id数组会返回空或错误结果。

正确实现方式

方式1:批量检索(兼容多数API版本,推荐)

通过循环调用单个价格的检索接口,同时处理异常避免流程中断:

$stripe = Cashier::stripe();
$priceIds = [
    'price_1Ow....', 
    'price_12lsd...'
];

$prices = [];
foreach ($priceIds as $id) {
    try {
        $price = $stripe->prices->retrieve($id);
        $prices[] = $price;
    } catch (\Stripe\Exception\ApiErrorException $e) {
        // 可根据需求处理异常,比如记录日志或跳过失败项
        error_log("获取价格{$id}失败:" . $e->getMessage());
    }
}

// $prices数组存储所有成功获取的价格对象

方式2:使用ids参数(需API版本≥2023-10-16)

如果你的Stripe API版本已升级到2023-10-16或更高,可直接用ids参数一次性查询:

$stripe = Cashier::stripe();
$priceIds = [
    'price_1Ow....', 
    'price_12lsd...'
];

$prices = $stripe->prices->all([
    'ids' => $priceIds,
    'limit' => count($priceIds) // 确保返回所有指定价格
]);

// 结果存储在$prices->data中

注意事项

  • 循环调用时需注意Stripe的API速率限制,避免短时间内请求过多导致限流。
  • 使用ids参数前,需确认当前Stripe API版本符合要求,可通过Cashier配置或Stripe控制台查看。
  • 无论哪种方式,都建议添加异常处理逻辑,避免单个价格获取失败影响整体流程。

内容的提问来源于stack exchange,提问作者Md. Zayed Hassan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 22:07:51