· 2 min read
Screencast: Abrechnungen in Rails mit Stripe
Downloads in verschiedenen Formaten:
Resourcen:
Gemfile
[ruby] gem ‘stripe’ [/ruby]
config/initializers/stripe.rb
[ruby] Stripe.api_key = “tGaNWsIG3Qy6zvXB8wv4rEcizJpSXjF4” STRIPE_PUBLIC_KEY = “pk_KcSyS2qPWdT5SdrwkQg0vNSyhZgqP” [/ruby]
layouts/application.html.erb
[html] <%= javascript_include_tag “https://js.stripe.com/v1/”, “application” %> <%= tag :meta, :name => “stripe-key”, :content => STRIPE_PUBLIC_KEY %> [/html]
subscriptions/new.html.erb
[html] <%= f.hidden_field :stripe_card_token %>
app/assets/javascripts/subscriptions.js.coffee
[javascript]
jQuery -> Stripe.setPublishableKey($(‘meta[name=“stripe-key”]‘).attr(‘content’)) subscription.setupForm()
subscription = setupForm: -> $(‘#new_subscription’).submit -> $(‘input[type=submit]‘).attr(‘disabled’, true) if $(‘#card_number’).length subscription.processCard() false else true processCard: -> card = number: $(‘#card_number’).val() cvc: $(‘#card_code’).val() expMonth: $(‘#card_month’).val() expYear: $(‘#card_year’).val() Stripe.createToken(card, subscription.handleStripeResponse) handleStripeResponse: (status, response) -> if status == 200 $(‘#subscription_stripe_card_token’).val(response.id) $(‘#new_subscription’)[0].submit() else $(‘#stripe_error’).text(response.error.message) $(‘input[type=submit]‘).attr(‘disabled’, false) [/javascript]
controllers/subscriptions_controller.rb
[ruby] def create @subscription = Subscription.new(params[:subscription]) if @subscription.save_with_payment redirect_to @subscription, :notice => “Thank you for subscribing!” else render :new end end [/ruby]
models/subscription.rb
[ruby] attr_accessor :stripe_card_token
def save_with_payment if valid? customer = Stripe::Customer.create(description: email, plan: plan_id, card: stripe_card_token) self.stripe_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 [/ruby]
bash
[bash] rails g migration add_stripe_to_subscriptions stripe_customer_token:string rake db:migrate [/bash]