代码之家  ›  专栏  ›  技术社区  ›  Jiew Meng

如何使用stripe nodejs sdk获得更多的客户源?

  •  1
  • Jiew Meng  · 技术社区  · 7 年前

    我只能通过get customer api获得前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中的某个地方有一个函数?

    3 回复  |  直到 7 年前
        1
  •  2
  •   koopajah MKumar    7 年前

    当您通过API检索客户对象时,stripe将返回 sources 属性,它是列表对象。这个 data 属性将是一个包含最多10个源的数组。

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

    例如,如果您的客户有35个来源,您将得到第一页(10),然后呼叫列表得到10个以上(20),然后再得到10个以上(30),最后一个呼叫将只返回5个来源(35),并且 有更多的 会是假的。

    要减少通话次数,还可以设置 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

        2
  •  1
  •   derpirscher    7 年前

    快速查看 sources 在stripe节点包中,似乎有一个 stripe.customers.listSources 方法,它采用 customerId 作为参数并请求正确的URL。我想它的工作原理和 listCards method . 但是我在文档中找不到它,所以你必须把它当作一个未记录的功能…但也许这只是文档中的一个错误。你可以联系支持部门。我们在一个旧项目中使用了Stripe,他们很感激对他们文档的任何输入。

        3
  •  1
  •   jpunk11    7 年前

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

    查看文档 here

    要注意的重要部分是 .自动包装机 :

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