Skip to content

Instantly share code, notes, and snippets.

@cgrusden
Created January 24, 2014 07:01
Show Gist options
  • Save cgrusden/8593240 to your computer and use it in GitHub Desktop.
Save cgrusden/8593240 to your computer and use it in GitHub Desktop.
Generate forms that have Stripe inputs along with any other inputs on the page.. Example: You have an account sign up page: rails g forms:stripe account username:string name:string email:string password:string
module Stripe
class FormsGenerator < Rails::Generators::NamedBase
source_root File.expand_path('../templates', __FILE__)
argument :forms_name, :type => :string, :default => "stripe_form"
desc "Generate Stripe.com enabled forms"
def create_stripe_form_js_coffeescript
create_file "app/assets/javascripts/#{forms_name}.js.coffee", <<-FILE
Stripe.setPublishableKey('YOUR_PUBLISHABLE_KEY');
$("#payment-form").submit((event) ->
# disable the submit button to prevent repeated clicks
$('.submit-button').attr("disabled", "disabled")
Stripe.createToken({
number: $('.card-number').val(),
cvc: $('.card-cvc').val(),
exp_month: $('.card-expiry-month').val(),
exp_year: $('.card-expiry-year').val(),
}, stripeResponseHandler)
# prevent the form from submitting with the default action
return false
)
stripeResponseHandler = (status, response) ->
if (response.error)
# re-enable the submit button
$('.submit-button').removeAttr("disabled")
#show the errors on the form
$(".payment-errors").html(response.error.message)
else
form$ = $("#payment-form")
# token contains id, last4, and card type
token = response['id']
# insert the token into the form so it gets submitted to the server
form$.append("<input type='hidden' name='stripe_token' value='" + token + "'/>")
# and submit
form$.get(0).submit()
FILE
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment