Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over Stripe subscription collection

I'm currently integrating with Stripe and before I update an existing the Subscription I need to retrieve all existing subscriptions to find the correct Subscription Id.

However, when I use the Stripe PHP library I seem to be unable to iterate over the actual subscription collection.

This is how I retrieve the subscription collection:

$subscriptions = $customer->subscriptions->all();

I have also tried this, which should be the same and doesn't seem to make difference in the end result:

$subscriptions = \Stripe\Customer::retrieve( $customer->id )->subscriptions->all();

For sanity sake, after obtaining the subscription collection I echo a count() on it to see how many elements it contains:

echo count( $subscriptions );  // echos '1' which is what I expect.

When I print_r() the entire $subscriptions object I do indeed see the one existing subscription, so I have verified that it has been retrieved.

I then want to simply iterate over the collection with a foreach. This should be possible because the StripeObject (a base class for the returned collection) implements ArrayAccess:

foreach( $subscriptions as $subscription )
{
   print_r( $subscription );
}

However, this doesn't result in anything.

How do I correctly iterate over a Stripe subscription collection?

like image 830
Luke Avatar asked Mar 03 '16 23:03

Luke


1 Answers

Stripe "list" API calls return "list objects" or "collections". These objets contain an actual list in their data attribute.

In PHP, you can iterate over a collection like this:

$subscriptions = $customer->subscriptions->all();

echo count($subscriptions->data); // Number of resources returned

foreach ($subscriptions->data as $subscription) {
    // Do something with $subscription
}
like image 192
Ywain Avatar answered Oct 14 '22 01:10

Ywain