acts_as_billable :plugin, :through = :rails
At Collective Idea, we're developing several apps that take credit card payments. (We've previously blogged about sorting through this whole mine-field of credit card processing.) One of the ideas we came up with early on was using the magic of Ruby and Rails plugins to extract the billing and credit card processing logic into something that is reusable.
We started with ActiveMerchant, a handy little library developed for Shopify by JadedPixel. ActiveMerchant is great for abstracting the credit card processing API, but you still need to figure out what to charge for, how much, how often, and be able to pull up a history of payments.
Welcome to acts\_as\_billable
, a plugin we're working on that we think will remove some of the complexity from online billing and payments. To illustrate how it will work, here is an example.
class User < ActiveRecord::Base
belongs_to :plan
acts_as_billable :plan, :frequency => :monthly
end
class Plan < ActiveRecord::Base
has_many :users
end
When a user signs up for your super-duper-new-app, they can choose a plan. That plan determines what features they get, and how much they pay to use your app. So, the user should be billed (well charged, but chargable just doesn't sound as nice) each month for the plan.
Another example:
class User < ActiveRecord::Base
has_many :registrations
acts_as_billable :event, :through => :registrations
end
class Registration < ActiveRecord::Base
belongs_to :user
belongs_to :event
end
class Event < ActiveRecord::Base
has_many :registrations
end
A user can register for events, which requires a payment. Users should then be billed for each event that they register for.
So what does acts\_as\_billable
really do? Several things:
- It adds temporary fields for the credit card information and kicks off the processing through ActiveMerchant when a record is saved. So when an event is created, if the event costs money, it makes the API calls to process the credit card, returning errors if it fails.
- It adds validations for the credit card information, and validates that the credit card processed successfully.
-
It adds polymorphic associations from the billable class (
User
in this case) toExchange
(transactions) andInvoice
. This gives you access to a record of all the user's payments.
We're pretty excited about what this plugin can do so far, and how easy it will make it for us to do more apps that require online payments. We intend to release this plugin as open source when we get it to a usable state. I'm sure there's a lot we could do with it that we haven't thought of, so we'd love some feedback.