4

I am creating a Stripe subscription with Laravel cashier. I have successfully created a subscription in Stripe with metadata. How to retrieve all subscriptions (with metadata) of a customer.?

Below is the code that creates the subscription

$request->user()->newSubscription('main', $plan->stripe_plan)->withMetadata(['wcda_reference' => $reference])->create($request->stripeToken);

Tried below code to retrieve but its listing from my database - not from Stripe API

$request->user()->subscriptions();
mujuonly
  • 11,370
  • 5
  • 45
  • 75

2 Answers2

4

You can try this:

$request->user()->asStripeCustomer()->subscriptions;

It returns a list of user's subscriptions.

Here is the Stripe API doc of the response: https://stripe.com/docs/api/customers/retrieve

Hafez Divandari
  • 8,381
  • 4
  • 46
  • 63
  • What happens if a user cancels a subscription and never renews it? Will this subscription appear in this list? And how do I check if a user has an active subscription right now? – Tyoma Inagamov Apr 09 '21 at 20:41
  • 1
    @TyomaInagamov it returns a list of [subscription objects](https://stripe.com/docs/api/subscriptions/object) if any. it also includes canceled ones: `subscription->status === 'canceled'`. – Hafez Divandari Apr 10 '21 at 20:56
  • Thanks for your time. It really helped me out! – Tyoma Inagamov Apr 11 '21 at 07:51
  • By the way, I've found a bug that if user wants to buy a subscription after he immediately cancelled it, it doesn't show up at `$user->asStripeCustomer()->subscriptions`. However, the payment succeeded and at stripe dashboard I can see that user has an active subscription. What should I do? – Tyoma Inagamov Apr 11 '21 at 09:56
1
$all_subs_ids = [];
$allSubs = \Stripe\Subscription::all(['limit' => 10, 'status' => 'active']); foreach($allSubs->autoPagingIterator() as $allSub) {
    array_push($all_subs_ids, $allSub->id);
}
S.I.
  • 3,250
  • 12
  • 48
  • 77
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 17 '22 at 19:59