Is it possible to get a count of subscribers for a plan from the Stripe API?

[亡魂溺海] 提交于 2019-12-06 12:14:52

There's no direct call for this, but it's easy enough to accomplish.

The "List all customers" API call (StripeCustomerService's List() method in Stripe.Net) returns the full JSON object for each customer, including their subscription and plan information. You can easily iterate through that and build your list of subscriber counts.

Note that if you have a lot of users, you'll have to retrieve the customer list in chunks. The API call is capped at 100 records (with a default of 10) and accepts an offset. For easy traversal of the list, the count property in Stripe's JSON response is the total number of customer records.

So for a basic outline, your strategy would be:

  1. Request 100 records via List()
  2. Calculate the number of additional requests required
  3. Process the initial 100 records
  4. Request 100 records via List(), offset by 100 * iteration
  5. Process the current 100 records
  6. Repeat 4 & 5 until records are exhausted

I found that this works: (sorry, this is PHP)

$subscriptions = \Stripe\Subscription::all(array('limit' => 1, 'plan' => 'plan-name-here', 'status' => 'trialing|active|past_due|unpaid|all', 'include[]' => 'total_count'));
echo $subscriptions->total_count;

I understand that you're implementing this for .NET, but here's a sample Ruby implementation:

limit = 100
iterations = (Stripe::Customer.all.count / limit).round # round up to the next whole iteration
last_customer = nil

iterations.times do 
  Stripe::Customer.all(limit: limit, starting_after: last_customer).each do |customer|

    # Do stuff to customer var

    last_customer = customer # save the last customer to know the offset
  end
end

If you're using Stripe.net package, you can use StripeSubscriptionService to get list of subscriptions for a plan. So you don't need to iterate through all customers.

var planService = new StripePlanService();
var planItems = planService.List(new StripeListOptions()
{
  Limit = 10 // maximum plans to be returned
});

foreach(var planItem in planItems)
{
  var subscriptionService = new StripeSubscriptionService();
  var stripeSubscriptions = subscriptionService.List(new StripeSubscriptionListOptions
  {
    PlanId = planItem.Id
  });

  // Do your calculation here
}

They have a better documentation for .NET in their site now. You can find the complete information here https://stripe.com/docs/api/dotnet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!