Chargify API Ruby Wrapper – Dealing with Prorations
If you are looking for a post about software documentation or customer support then move along. This one is all about Ruby code.
We recently switched our billing system for ScreenSteps Live over to Chargify. There were a variety of reasons (the main one being how they take over the process of keeping the customers’ billing information up to date, a major pain in a SaaS product). One of the great features is their support of automatic proration of accounts when they upgrade.
What we wanted to accomplish was the following. Say for example we have a user that has a Solo account at $19/month. Half-way through their billing cycle they want to add two more users and upgrade to a Basic plan ($57/month). When they perform that upgrade we want two things to happen:
-
They should be billed a pro-rated amount for the difference in the plans:
(new_ammount - old_ammount) * percentage_of_plan_time_until_next_billing
In this case that would be ($57-$19) * 50% (since they were halfway through their billing cycle) - On the next normal billing date we want them to be charged the full amount for the new plan they have selected (in this case $57).
The Chargify API makes this very easy and they have a great Ruby wrapper for their API so doing this in Rails should be easy right? Well, it wasn’t immediately apparent to me how to accomplish this so I thought I would share how we did it.
Here are some examples of using the Ruby wrapper for the Chargify code taken from their gem:
# Create a subscription from a customer reference
subscription = Chargify::Subscription.create(
:customer_reference => 'moklett',
:product_handle => account_type,
:credit_card_attributes => { :first_name => "Michael",
:last_name => "Klett",
:expiration_month => 1,
:expiration_year => 2020,
:full_number => "1"
}
)
# Lookup up existing Subscription using the Customer's reference
Chargify::Subscription.find_by_customer_reference('moklett')
To upgrade a subscription you simply call:
subscription = Chargify::Subscription.find_by_customer_reference('moklett')
subscription.product_handle = 'new_account_type'
subscription.save
But that won’t add a pro-rated charge to the users’ account. After a search through the API docs I figured out how do this via the Ruby wrapper.
subscription = Chargify::Subscription.find_by_customer_reference('moklett')
subscription.post(:migrations, :product_handle => new_account_type)
The post command creates a post to a nested migrations resource under the subscription resource. This isn’t part of the Chargify gem, it is just built into ActiveResource. Probably obvious to a lot of people but wasn’t to me so I thought I would post about it.
Want to Learn More About ScreenSteps Desktop?
ScreenSteps makes it fast and simple to talk in pictures.
Learn more and download a free ScreenSteps trial for Mac and Windows