andrewmarkle
andrewmarkle

Reputation: 241

Form submission with Stripe and Rails

I'm having a problem submitting a new customer form to stripe. If I fill out the form from top to bottom, Email, Credit Card Info, and hit submit, the form fails ("There was a problem with your credit card"). On stripes end, the email is sent but the card info is blank.

However if I fill out the credit card info first, hit submit, AND THEN fill in the Email, everything works as it should. A new subscription is made on the app and a new customer is created in stripe.

I'm sure there is something I'm doing wrong. Here's the code:

new.html.erb

<h1>Signing up for <%= @subscription.plan.name %></h1>
 <strong><%= @subscription.plan.price %></strong> per month!</p>

 <%= form_for @subscription do |f| %>
   <% if @subscription.errors.any? %>
     <div class="error_messages">
       <h2><%= pluralize(@subscription.errors.count, "error") %> prohibited this subscription from being saved:</h2>
       <ul>
       <% @subscription.errors.full_messages.each do |msg| %>
         <li><%= msg %></li>
       <% end %>
       </ul>
     </div>
   <% end %>

   <%= f.hidden_field :plan_id %>

   <%= f.hidden_field :stripe_card_token %>

   <div class="field">
     <%= f.label :email %>
     <%= f.text_field :email, "data-stripe" => "email" %>
   </div>

   <% if @subscription.stripe_card_token.present? %>
     <p>Credit card has been provided.</p>
   <% else %>
     <div class="field">
       <%= label_tag :card_number, "Credit Card Number" %>
       <%= text_field_tag :card_number, nil, name: nil, "data-stripe" => "number" %>
     </div>
     <div class="field">
       <%= label_tag :card_code, "Security Code on Card (CVV)" %>
       <%= text_field_tag :card_code, nil, name: nil, "data-stripe" => "cvc" %>
     </div>
     <div class="field">
       <%= label_tag :card_month, "Card Expiration" %>
       <%= text_field_tag :card_month, nil, name: nil, "data-stripe" => "exp-month", class: "input-mini", "placeholder" => "MM" %>
      <%= text_field_tag :card_year, nil, name: nil, "data-stripe" => "exp-year", class: "input-mini", "placeholder" => "YYYY" %>
     </div>
   <% end %>
   <div id="stripe_error">
     <noscript>JavaScript is not enabled and is required for this form. First enable it in your web browser settings.</noscript>
   </div>
   <div class="actions">
     <%= f.submit "Subscribe", class: "btn btn-primary" %>
   </div>
 <% end %>

subcriptions_controller.rb

    class SubscriptionsController < ApplicationController

  def index
    @subscriptions = Subscription.all
  end

  def show
    @subscription = Subscription.find(params[:id])
  end

  def new
    plan = Plan.find(params[:plan_id])
    @subscription = plan.subscriptions.build
  end

  def create
    @subscription = Subscription.new(subscription_params)
    if @subscription.save_with_payment
      redirect_to @subscription, :notice => "Thank you for subscribing!"
    else
      render :new
    end
  end

  private
    def subscription_params
      params.require(:subscription).permit(:plan_id, :email, :stripe_card_token)
    end
end

The model subscription.rb

class Subscription < ActiveRecord::Base
  before_save { self.email = email.downcase }
  belongs_to :plan
  validates_presence_of :plan_id
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }

  attr_accessor :stripe_card_token

  def save_with_payment
    if valid?
      customer = Stripe::Customer.create(card: stripe_card_token, email: email, plan: plan_id)
      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
end

And finally, the javascript (mostly from stripe's documentation, but slightly modified):

// This identifies your website in the createToken call below
Stripe.setPublishableKey('<%= Rails.configuration.stripe[:publishable_key] %>');

var stripeResponseHandler = function(status, response) {
  var $form = $('#new_subscription');

  if (response.error) {
    // Show the errors on the form
    $form.find('#stripe_error').text(response.error.message);
    $form.find('input[type=submit]').prop('disabled', false);
  } else {
    // token contains id, last4, and card type
    var token = response.id;
    // Insert the token into the form so it gets submitted to the server
    $form.find($('#subscription_stripe_card_token').val(token));
    // and re-submit
    $form.get(0).submit();
  }
};

jQuery(function($) {
      $('#new_subscription').submit(function(e) {
        var $form = $(this);

        // Disable the submit button to prevent repeated clicks
        $form.find('input[type=submit]').prop('disabled', true);

        Stripe.createToken($form, stripeResponseHandler);

        // Prevent the form from submitting with the default action
        return false;
      });
    });

Thanks for reading! Any help would be greatly appreciated.

Upvotes: 2

Views: 1780

Answers (1)

andrewmarkle
andrewmarkle

Reputation: 241

Okay, so I figured out what's going on here. After a lot more testing I realized that if I hit refresh on the page, and then filled out the form and submitted it, it worked every time. But, if I navigated to the subscription_path through the app, it would create an error unless you manually refreshed the page after getting there.

So...after a lot of digging around I found out that the problem is with Turbolinks. This post helped me figure out how to fix the problem: Rails 4: how to use $(document).ready() with turbo-links. From what I can gather, jQuery wasn't loading up Stripe.js because of turbo-links.

There are a couple options how to fix it.

  1. Disable turbo-links
  2. Add some code to your javascript (see link above)
  3. Add the jquery-turbolinks gem which helps jQuery play nice with turbo-links.

(I chose option 3 as it seemed to be the easiest solution).

Anyway, now the form works!

Upvotes: 4

Related Questions