9
votes

In Rails, I'm attempting to implement a controller action which will allow a customer to change the plan they are subscribed to. Per the Stripe documentation, this can be done as follows:

customer = Stripe::Customer.retrieve("CUSTOMER_ID")
subscription = customer.subscriptions.retrieve("SUBSCRIPTION_ID")
subscription.plan = "premium_monthly"
subscription.save

I have each customer's ID saved in the user table in my Database, but I'm stuck on how to retrieve a customer's subscription ID given their customer ID. Each customer in this project will only have one subscription, how could I go about pulling this given their customer ID?

2

2 Answers

11
votes

The relevant part of the Stripe API reference suggests that upon retrieving a customer you will have access to a subscriptions attribute containing a url at which you can access a list of subscriptions.

However, on creating a subscription, Stripe will return the subscription to you with the subscription id. I would suggest storing this in your database as an attribute on the customer model (if they will only have one subscription) or, and the method I use, is to have a Subscription model in my database which stores some of the frequently accessed data and avoids pinging the Stripe API too much.

3
votes

"retrieving a customer you will have access to a subscriptions"

Was the case with the API from 2019.

Changes since API version 2019-08-14 → 2020-08-27 The subscriptions property on Customers is no longer included by default. You can expand the list but for performance reasons we recommended against doing so unless needed.

See https://stripe.com/docs/api/expanding_objects

Example code (PHP):

$stripe = new \Stripe\StripeClient(YOURSTRIPE_SECRETKEY);
$stripe_customer = $stripe->customers->retrieve($payerid, [ 'expand' => ['subscriptions'] ]);
$stripe_status = $stripe_customer->subscriptions->data[0]->status;

I am still trying to figure out the "recommended way" and will hopefully report back.