Skip to content

Instantly share code, notes, and snippets.

@jgaskins
Last active August 29, 2015 13:57
Show Gist options
  • Save jgaskins/9533807 to your computer and use it in GitHub Desktop.
Save jgaskins/9533807 to your computer and use it in GitHub Desktop.
Charging customers during registration with Devise
module Foo
class Application < Rails::Application
# Keep the credit card data out of your logs
config.filter_parameters += [:password, :credit_card]
end
end
= 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
# 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
Foo::Application.routes.draw do
devise_for :users, controllers: { registrations: 'registrations' }
end
@rubyonrailstutor
Copy link

i think it looks clean !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment