Last active
August 29, 2015 13:57
-
-
Save jgaskins/9533807 to your computer and use it in GitHub Desktop.
Charging customers during registration with Devise
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 Foo | |
class Application < Rails::Application | |
# Keep the credit card data out of your logs | |
config.filter_parameters += [:password, :credit_card] | |
end | |
end |
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
= form_for User.new, as: :user, url: user_registration_path do |f| | |
- # Regular user details | |
= f.fields_for :credit_card do |cc| | |
- # Regular CC details |
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
# CreditCard: wraps CC data from the client. Also works if you're using an encrypted form | |
# of the CC data. Not sure if Stripe does this, but Braintree allows it. | |
# PaymentProcessor: wraps interaction with the payment processor (Stripe, Braintree, etc). | |
# #charge: hits the payment API with card data or token | |
# PaymentProcessor::Charge: wraps the charge from the payment processor | |
# #customer_id: generated while adding the customer to the payment processor system | |
# and submitting the card data. | |
class RegistrationsController < Devise::RegistrationsController | |
def create | |
credit_card = CreditCard.new(card_params) # Wrap the CC data | |
@user = User.new | |
if @user.valid? | |
payment_processor = PaymentProcessor.new # Wrap payment processor API | |
charge = payment_processor.charge(credit_card) | |
if charge.success? | |
# charge.customer_id is the payment processor | |
@user.customer_id = charge.customer_id | |
@user.save | |
else | |
@user.errors[:base] << charge.error_messages | |
render :new | |
end | |
else | |
render :new | |
end | |
end | |
def card_params | |
@card_params ||= params[:user].delete(:credit_card) | |
end | |
end |
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
Foo::Application.routes.draw do | |
devise_for :users, controllers: { registrations: 'registrations' } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
i think it looks clean !