· 2 min read

Screencast: Abrechnungen in Rails mit Stripe

Downloads in verschiedenen Formaten:

mp4 m4v webm ogg

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 %>

<%= f.label :email %> <%= f.text\_field :email %>
<% if @subscription.stripe\_card\_token.present? %> Credit card has been provided. <% else %>
<%= label\_tag :card\_number, "Credit Card Number" %> <%= text\_field\_tag :card\_number, nil, name: nil %>
<%= label\_tag :card\_code, "Security Code on Card (CVV)" %> <%= text\_field\_tag :card\_code, nil, name: nil %>
<%= label\_tag :card\_month, "Card Expiration" %> <%= select\_month nil, {add\_month\_numbers: true}, {name: nil, id: "card\_month"} %> <%= select\_year nil, {start\_year: Date.today.year, end\_year: Date.today.year+15}, {name: nil, id: "card\_year"} %>
<% end %>
\[/html\]

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]

Back to Blog