Subscriptions with stripe
Code examples use the stripe ruby gem. Most of the links are to stripe's documentation.
To start, create some plans.
Stripe::Plan.create :id => 'your-plan-id', ...There are a bunch of attributes you can provide to the plan. If you leave off
required ones, #create will raise. If you try to create a plan with an id that
stripe already knows about, #create will raise.
The only part of a plan you can update is the name.
Use stripe.js to convert credit card information into a token, client-side.
The structure returned by stripe includes an id element. Send this to your app.
Server-side, use the token to create a customer. Or update the customer if you already created one.
customer = Stripe::Customer.create :card => token_id, ...
keep_a_copy_of customer.id
# or
customer = Stripe::Customer.retrieve customer_id
customer.card = token_id
customer.saveThere are a bunch of attributes you can store for a customer, but none of them are required.
It's pretty easy to set up or change a customer's plan. The code looks the same, if the customer already exists.
customer = Stripe::Customer.retrieve customer_id
customer.update_subscription :plan => 'your-plan-id'There are other useful options, like prorating a changed subscription.
Also, this will raise if there isn't a card or token set on the customer. You can
check to see if the customer has a card set with customer[:active_card].
If a customer cancels, you should cancel the subscription with stripe.
customer = Stripe::Customer.retrieve customer_id
customer.cancel_subscription if customer[:subscription]Note the use of customer[:subscription] to check if the customer has
an active subscription. This is how you should do it because customer.subscription
and customer.cancel_subscription will raise an error if there is not an active subscription.
Most dates are represented as integers, which you can convert to times with Time.at stripe_date. (Note: I'm not sure that this puts the time in the right time zone.)
The customer object has several interesting pieces of information. Attributes are
accessible via [] or named attribute methods (e.g. customer[:name] or customer.name). The advantage of [] is that it returns nil if the attribute is not defined (as opposed to the attribute method's behavior of raising an error).
On Customer:
subscriptionis the subscription information, if the customer is subscribed to a plan.active_cardis the active credit card information for the customer.next_recurring_chargeis available, and has anamountanddatestring.
On Subscription:
start,current_period_start, andcurrent_period_endstatusis'active'if the subscription is active