【问题标题】:How to update Stripe subscription quantity? (Node.js)如何更新 Stripe 订阅数量? (Node.js)
【发布时间】:2021-11-19 13:17:56
【问题描述】:

我正在尝试更新已创建的 Stripe 订阅数量。但我不断收到此错误:

"error": {
    "message": "Invalid array",
    "param": "items",
    "type": "invalid_request_error"
  }

我首先检索 Stripe 订阅,更新值,然后发布更新的值。代码如下:

const subscription = await stripe.subscriptions.retrieve(
  stripe_sub_id
);

subscription.items.data[0].quantity = newCount;

stripe.subscriptions.update(
    stripe_sub_id,
    {items: { data: subscription.items.data }}
)

我做错了什么?如何更新 items.data 数组中“数量”的值?

【问题讨论】:

    标签: javascript node.js stripe-payments


    【解决方案1】:

    由于 Stripe API 的工作方式,您实际上不能仅仅改变 items.data 并直接传递它(检索调用中返回的项目格式与 POST 时参数的格式不同,它们是不同)。

    因此,您实际上需要编写更多自定义代码/业务逻辑来为您想要的更改显式创建 params 对象。可能是这样的。

    const subscription = await stripe.subscriptions.retrieve(
      stripe_sub_id
    );
    
    let IdOfPriceToUpdate = "price_xxx";
    let newQuantity = 5;
    
    let updatedItemParams = subscription.items.data.
        filter(item => item.price != IdOfPriceToUpdate). // find what to change
        map(item => {return { id:item.id, quantity:newQuantity}}) // change it
    
    await stripe.subscriptions.update(
        stripe_sub_id,
        {items: updatedItemParams}
    ) 
    

    https://stripe.com/docs/billing/subscriptions/upgrade-downgrade#changing

    【讨论】:

    • 有趣!所以我走在正确的轨道上......您的答案还删除了额外的嵌套层(在data 下。)但是您也只是在输入上设置 ID 和更新的数量字段。直到!
    • 顺便说一句,没有理由(也许在语义上更好)你所有的let 不能在答案中是constIdOfPriceToUpdate 来自哪里? filter 应该是 item.price.id !== IdOfPriceToUpdate 吗?
    • @karliekko 谢谢!
    • @MattMorgan IdOfPriceToUpdate 只是一个占位符,因为您可能会从业务逻辑中调用此类代码,您拥有想要增加数量的 Stripe Price ID 并将其传入. 当然我可以使用const 和双等号,不过这只是一个快速的sn-p!
    • 另请注意,我在map 中返回的是stripe.com/docs/api/subscriptions/… 的形状,即它必须看起来像那里的对象(ID 是订阅项目ID si_xxx) .代码是找到使用您要查找的 Price 的 SubscriptionItem,然后更新该项目以拥有您想要的 quantity(这是在 Stripe 中完成的,但是 API 的这个特定部分非常棘手理解)。
    猜你喜欢
    • 2019-02-15
    • 2017-08-20
    • 2020-08-02
    • 2021-10-24
    • 1970-01-01
    • 2016-12-17
    • 2019-09-09
    • 2017-01-24
    • 1970-01-01
    相关资源
    最近更新 更多