Created
October 28, 2013 04:27
-
-
Save lleger/7191444 to your computer and use it in GitHub Desktop.
**Simple Stripe Subscription Concern** To use, simply drop this in `app/models/concerns`, include it in the model you want to search (`include Subscription`) and declare the `plan_for_stripe` and `description_for_stripe` helper methods. Use `save_with_payment` in place of `save` when creating a new resource with billing details; similarly, use `…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Subscription | |
extend ActiveSupport::Concern | |
included do | |
attr_accessor :billing_card_token | |
end | |
def save_with_payment | |
if valid? | |
customer = ::Stripe::Customer.create(email: email, | |
description: description_for_stripe, | |
plan: plan_for_stripe, | |
card: billing_card_token) | |
self.billing_customer_token = customer.id | |
save! | |
end | |
rescue ::Stripe::InvalidRequestError => e | |
logger.error "Stripe error while creating customer: #{e.message}" | |
errors.add :base, "There was a problem with your credit card." | |
false | |
end | |
def update_payment | |
if valid? | |
customer = ::Stripe::Customer.new(billing_customer_token) | |
customer.email = email | |
customer.description = description_for_stripe | |
customer.card = billing_card_token | |
customer.save | |
end | |
rescue ::Stripe::InvalidRequestError => e | |
logger.error "Stripe error while updating customer: #{e.message}" | |
errors.add :base, "There was a problem with your credit card." | |
false | |
end | |
def delete_from_stripe | |
customer = ::Stripe::Customer.new(billing_customer_token) | |
customer.delete | |
rescue ::Stripe::InvalidRequestError => e | |
logger.error "Stripe error while deleting customer: #{e.message}" | |
errors.add :base, "There was a problem with your account." | |
false | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment