Created
May 11, 2016 06:08
-
-
Save sicktastic/db50b861b47919c2d18478cdb4d599db to your computer and use it in GitHub Desktop.
Donation controller and payment model that accepts one time or recurring donations through Stripe.
This file contains hidden or 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
class DonationsController < ApplicationController | |
def create | |
@customer = Customer.find_or_create_by_email(params[:stripeEmail], params[:stripeToken], params[:stripeName]) | |
new_payment | |
if @payment.save && @payment.charge | |
@payment.delay_until(1.minutes.from_now).email_payer | |
redirect_to page_path('thanks') | |
end | |
rescue Stripe::CardError => e | |
flash[:error] = e.message | |
redirect_to donations_errors_path | |
end | |
private | |
def new_payment | |
@payment = Payment.new( | |
email: params[:stripeEmail], | |
amount: params[:amount], | |
currency: 'usd', | |
customer: @customer, | |
description: params[:description], | |
monthly_donation: params[:monthlyDonation], | |
donation_form_id: params[:donationID], | |
uuid: SecureRandom.uuid | |
) | |
end | |
end |
This file contains hidden or 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
class Payment < ActiveRecord::Base | |
belongs_to :customer | |
def to_param | |
uuid | |
end | |
def charge | |
if monthly_donation | |
charge_monthly | |
else | |
charge_one_time | |
end | |
end | |
def email_payer | |
PaymentMailer.payment_receipt(self).deliver | |
end | |
protected | |
def charge_monthly | |
stripe_plan = Stripe::Plan.create( | |
:amount => self.amount.to_i * 100, | |
:interval => 'month', | |
:name => 'Online Monthly Donation' + ' - ' + self.customer.email, | |
:currency => 'usd', | |
:id => SecureRandom.hex, | |
:metadata => { | |
'plan_description' => self.description, | |
'donation_form_id' => self.donation_form_id, | |
} | |
) | |
self.update_attributes(is_charged: true, stripe_plan_id: stripe_plan.id) | |
customer.stripe_customer.subscriptions.create( | |
:plan => stripe_plan.id | |
) | |
return true | |
end | |
def charge_one_time | |
begin | |
charge = Stripe::Charge.create( | |
:customer => self.customer.stripe_customer_id, | |
:amount => self.amount.to_i * 100, | |
:description => self.description, | |
:currency => 'usd', | |
:metadata => { | |
'donation_form_id' => self.donation_form_id, | |
'frequency_type' => 'one_time', | |
'uuid' => self.uuid | |
} | |
) | |
self.update_attributes(is_charged: true, stripe_charge_id: charge.id) | |
return true | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment