'how to fetch subscriptoin information from stripe response

i use the following line of code to get customer information.

$customer = Stripe_Customer::retrieve($customer->id);

i am getting the response from stripe correctly. here is the response when i print_r($customer->subscriptions);

Stripe_List Object
(
    [_apiKey:protected] => sk_test_LteiEDqVirhMuUt3IzzxUHkU
    [_values:protected] => Array
        (
            [object] => list
            [data] => Array
                (
                    [0] => Stripe_Subscription Object
                        (
                            [_apiKey:protected] => sk_test_LteiEDqVirhMuUt3IzzxUHkU
                            [_values:protected] => Array
                                (
                                    [id] => sub_7SLD31Rqg3Qi5Z

my question is how to get subscription id(which is sub_7SLD31Rqg3Qi5Z here). i have tried to get it by $customer->subscriptions['data']['id'] but no luck.

any help is highly appreciated.



Solution 1:[1]

$customer->subscriptions['data'] is a list, so you need to access it by index. This is because a customer can have more than one subscription.

Here is how you could retrieve the ID for every subscription:

for($i = 0; $i < $customer->subscriptions->total_count; $i++) {
  $subscription = $customer->subscriptions->data[$i];
  echo $subscription->id;
}

A few unrelated notes:

  • You should use echo instead of print_r() to output Stripe objects. echo will display the nicely formatted JSON representation.

  • Because you used print_r(), your question includes your secret API key. Even if it's "just" the test key, you should never reveal secret API keys. You should edit your question to mask the API key (replace it with something like sk_test_...), and head to your dashboard to roll out a new secret test key (by clicking on the small "recycle" icon next to the key).

Solution 2:[2]

Below code will give you all subscriptions by customer ID.

$stripe = new \Stripe\StripeClient(YOUR_STRIPE_SECRET);

$customer = $stripe->customers->retrieve(
    $stripeCustomerId,
    ['expand' => ['subscriptions']]
);

$subscriptions = data_get($customer, 'subscriptions.data');

// to get all subscription IDs
$subscriptionIds = data_get($customer, 'subscriptions.data.*.id');

Hope it will help.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ywain
Solution 2 khatri rohan