【问题标题】:How to get more customer sources using Stripe NodeJS SDK?如何使用 Stripe NodeJS SDK 获得更多客户来源?
【发布时间】:2018-12-22 10:49:34
【问题描述】:

我只能通过获取客户 API 获得 1st 10 的客户来源:

# stripe.customers.retrieve

{
  "id": "cus_DE8HSMZ75l2Dgo",
  ...
  "sources": {
    "object": "list",
    "data": [

    ],
    "has_more": false,
    "total_count": 0,
    "url": "/v1/customers/cus_DE8HSMZ75l2Dgo/sources"
  },
  ...
}

但是我怎样才能得到更多呢?是通过 AJAX 调用的唯一方法吗?我在想SDK中应该有一个功能?

【问题讨论】:

    标签: node.js stripe-payments


    【解决方案1】:

    当您通过 API 检索 Customer 对象时,Stripe 将返回 sources 属性,它是一个 List 对象。 data 属性将是一个数组,其中最多包含 10 个源。

    如果您希望获得比 10 个最近的资源更多的资源,则需要使用Pagination。这个想法是您将首先获得 N 个对象的列表(默认情况下为 10 个)。然后,您将通过再次请求 N 个对象但使用参数starting_after 设置为上一页中最后一个对象的 id 从 Stripe 请求下一个“页面”。您将继续这样做,直到返回页面中的has_more 属性为false,表示您已检索到所有对象。

    例如,如果您的客户有 35 个来源,您将获得第一页 (10),然后调用列表再获得 10 个 (20),然后再获得 10 个 (30),最后一次调用将仅返回 5 个来源(35) 和 has_more 将是错误的。

    要减少调用次数,您还可以将limit 设置为更高的值。在这种情况下,最大值为 100。

    代码如下所示:

    // list those cards 3 at a time
    var listOptions = {limit: 3};
    while(1) {
        var sources = await stripe.customers.listSources(
          customer.id,
          listOptions
        );
    
        var nbSourcesRetrieved = sources.data.length;
        var lastSourceId = sources.data[nbSourcesRetrieved - 1].id;
        console.log("Received " + nbSourcesRetrieved + " - last source: " + lastSourceId + " - has_more: " + sources.has_more);
    
        // Leave if we are done with pagination
        if(sources.has_more == false) {
          break;
        }
    
        // Store the last source id in the options for the next page
        listOptions['starting_after'] = lastSourceId;
    }
    

    您可以在此处查看关于 Runkit 的完整运行示例:https://runkit.com/5a6b26c0e3908200129fbb5d/5b49eabda462940012c33880

    【讨论】:

    • 但是这个使用listCards API,在我的理解中卡片和来源不一样?
    • @JiewMeng 你可以简单地使用listSources 代替,我刚刚更新了示例。
    【解决方案2】:

    快速查看stripe-node 包的sources,似乎有一个stripe.customers.listSources 方法,它以customerId 作为参数并请求正确的url。我想它的工作原理类似于listCards method。但是我在文档中找不到它,因此您必须将其视为未记录的功能……但也许这只是文档中的错误。您可以联系支持人员。我们在一个旧项目中使用了 stripe,他们感谢他们对文档的任何输入。

    【讨论】:

      【解决方案3】:

      从 stripe-node 6.11.0 开始,您可以自动分页列表方法,包括客户来源。 Stripe 为此提供了一些不同的 API 来帮助处理各种节点版本和样式。

      请参阅文档here

      需要注意的重要部分是 .autoPagingEach

      await stripe.customers.listSources({ limit: 100 }).autoPagingEach(async (source) => {
        doSomethingWithYourSource(source)
      })
      

      【讨论】:

        猜你喜欢
        • 2019-12-24
        • 2019-03-31
        • 2017-07-18
        • 2020-08-10
        • 2020-08-14
        • 1970-01-01
        • 2021-02-14
        • 1970-01-01
        • 2018-12-13
        相关资源
        最近更新 更多