Integrating Stripe in Rails app

时间:2015-09-01 22:04:29

标签: ruby-on-rails stripe-payments

I am trying to create a custom form with stripe, and while it all appears to be submitting, when I check my dashboard in Stripe, although I do see a record of the transaction - I do not see the amount or any reference to the cc coming through. With that said, I am not quite sure what I SHOULD be seeing in the dashboard. But I am pretty sure I am doing something wrong. Here is the code to my form:

<div class="container">
<div class="row Row one">
    <div class="col-sm-12 col-md-10">
       <%= form_for @project, url: project_charges_path, :html => {:id => "payment-form"}, method: 'post' do |f| %>

            <%= f.hidden_field :user_id, :value => current_user.id %>
            <%= f.hidden_field :@project_id, :value => @project.id %>

            <div class= "field">
              <%= label_tag :card_number, "Credit Card Number" %><br>
              <%= text_field_tag :card_number, nil, name: nil %><br>
            </div>

            <div class= "field">
              <%= label_tag :card_code, "Security Code (cvc)" %><br>
              <%= text_field_tag :card_code, nil, name: nil %><br>
            </div>

            <div class= "field">
              <%= label_tag :card_month, "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"}%>
            </div>

            <div class= "actions">
              <%= f.submit("Submit") %>
            </div>

            <div id="stipe-error">
              <%= flash[:error] %> 
            </div>

      <% end %> 
    </div>
</div>
<!-- <div class="row"></div> -->

and here is my charges controller:

class ChargesController < ApplicationController

    def new
        @project = Project.find(params[:project_id])
    end

    def create

         @project = Project.find(params[:project_id])
         binding.pry
          # Amount in cents, this is being read and recorded in stripe dashboard
          @amount = 500
          customer = Stripe::Customer.create(
            :email => 'helloWorld@stripe.com',
            :card  => params[:stripeToken]
          )

          charge = Stripe::Charge.create(
            :customer    => customer.id,
            :amount      => @amount,
            :description => 'Rails Stripe customer',
            :currency    => 'usd'
          )

              @payment = Payment.create({
                user_id: current_user.id,
                project_id: @project,
                amount: @amount
                })
              @payment.save

    rescue Stripe::CardError => e
      flash[:error] = e.message
    end

    # private
    # def charges_params
    #   params.require(:payment).permit(:comments, :user_id, :project_id)
    # end

end

Per a tutorial I have also included some javascript in my application.js:

$('#payment-form').submit(function(event) {
    var $form = $(this);
    alert('you clicked submit');
    // Disable the submit button to prevent repeated clicks
    $form.find('button').prop('disabled', true);

    Stripe.card.createToken($form, stripeResponseHandler);

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

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

  if (response.error) {
    // Show the errors on the form
    $form.find('.payment-errors').text(response.error.message);
    $form.find('button').prop('disabled', false);
  } else {
    // response contains id and card, which contains additional card details
    var token = response.id;
    // Insert the token into the form so it gets submitted to the server
    $form.append($('<input type="hidden" name="stripeToken" />').val(token));
    // and submit
    $form.get(0).submit();
  }
}

Inside the striped dashboard I see:

enter image description here

the email comes through, but nothing concerning the amount or card. I don't expect to see the card number persay, but some reference to it, maybe just the type, or last four digits? Also in the front page of the dashboard (the area what gives a graph, I think I should be seeing the sum of the payments, even test payments, and the sum is still $0 despite having made over a dozen test payments of $5 each.

What am I missing here?

Also most of the tutorials I have come across are either really old, or PHP, which I am not familiar with. If anybody can recommend a great resource, that would really be helpful as well. I plan to use stripe for multiple projects, and would really like to UNDERSTAND it...

1 个答案:

答案 0 :(得分:1)

我可能在回复时已经很晚了,你必须已经这样做了,但以防万一这可能对其他人有所帮助。我刚刚在我的应用程序中集成了条带。我不确定你在问什么,但我认为一个有效的例子可能有所帮助。这与你所做的非常相似,我找不到出错的地方。

我正在做的是在我的用户表中保存stripe返回的customer_id。当用户保存信用卡时,扣除根据订阅计划的一定金额。您将在仪表板中的订户下的计划详细信息中看到customer_id。此外,在客户中,当您引用该customer_id时,您将看到他订阅了哪个计划。

查看:(creditcard.html.erb)

<div class="row">
  <% if flash[:error].present? %>
  <div class="col-lg-12 alert alert-danger">
    <%= flash[:error] %>
  </div>
  <% else %>
  <div class="col-lg-12" id = "payment-errors">
    <span class="payment-errors"></span>
  </div>
  <% end %>
</div>
<div>

  <%= form_tag plans_billings_chargecreditcard_path, id: "payment-form" do%>
  <div class="row">
    <div class="col-lg-3">
      <div class="form-group">
        <label>Card Number</label>
        <%= text_field_tag nil, nil, size: 20, "data-stripe": "number", class: "form-control" %>
      </div>
    </div>
    <div class="col-lg-2">
      <div class="form-group">
        <label>CVC</label>
        <%= text_field_tag nil, nil, size: 4, "data-stripe": "cvc", class: "form-control" %>

      </div>
    </div>
  </div>
  <div class="row">
    <div class="col-lg-12">
      <div class="form-group">
        <label>Expiration Date(MM/YY)</label>
        <select class="selectpicker set-width" data-live-search="true" data-stripe = "exp_month">
          <option>- Month -</option>
          <option>1</option>
          <option>2</option>
          <option>3</option>
          <option>4</option>
          <option>5</option>
          <option>6</option>
          <option>7</option>
          <option>8</option>
          <option>9</option>
          <option>10</option>
          <option>11</option>
          <option>12</option>
        </select>
        <select class="selectpicker set-width" data-live-search="true" data-stripe = "exp_year"> <!-- form-control input-lg -->
          <option>- Year -</option>
          <option>16</option>
          <option>17</option>
          <option>18</option>
          <option>19</option>
          <option>20</option>
          <option>21</option>
          <option>22</option>
          <option>23</option>
          <option>24</option>
          <option>25</option>
          <option>26</option>
        </select>
      </div>
    </div>
  </div>

  <div class="row">
    <div class="col-lg-12">
      <div class="form-group">
        <%= submit_tag "Save Card", class: "btn btn-primary" %>
      </div>
    </div>
  </div>
  <% end %>
</div>

CofeeScript :( plan_billings.coffee)

stripeResponseHandler = (status, response) ->
  # Grab the form:
  $form = $('#payment-form')
  if response.error
    # Problem!
    # Show the errors on the form:
    $('#payment-errors').addClass 'alert'
    $('#payment-errors').addClass 'alert-danger'
    $('.payment-errors').text response.error.message    
    $('.submit').prop 'disabled', false
    # Re-enable submission
  else
    # Token was created!
    # Get the token ID:
    token = response.id
    # Insert the token ID into the form so it gets submitted to the server:
    $form.append $('<input type="hidden" name="stripeToken">').val(token)
    # Submit the form:
    $form.get(0).submit()
  return

$ ->
  $form = $('#payment-form')
  $form.submit (event) ->
    # Disable the submit button to prevent repeated clicks:
    $form.find('.submit').prop 'disabled', true
    # Request a token from Stripe:
    Stripe.card.createToken $form, stripeResponseHandler
    # Prevent the form from being submitted:
    false
  return

控制器:(在PlanBilling控制器中,chargecreditcard动作)

@plan_and_billing = current_user.plan_billing
@current_plan = DataPlan.find_by(id: @plan_and_billing.data_plan_id)
token = params[:stripeToken]
if current_user.customer_id.present?
  customer = Stripe::Customer.retrieve(current_user.customer_id)
  customer.sources.create(source: token)
  redirect_to plans_billings_planbilling_path
else
  customer = Stripe::Customer.create( :source => token, plan: YOUR_PLAN_ID_YOU_HAVE_INYOUR__DASHBOARD  )
  @credit_card = current_user.update(customer_id: customer.id)
  redirect_to plans_billings_planbilling_path
end
rescue Stripe::CardError => e
  flash[:error] = e.message
  redirect_to plans_billings_creditcard_path

控制器中发生的事情是,当用户没有卡并且他保存卡的详细信息时,卡将被保存并且您提到的计划的价格将被扣除。如果他已经保存了信用卡并保存了另一张信用卡,那么该卡只会保存在仪表板中的详细信息中。新卡将不收取费用。它只是为了向该客户保存新的信用卡。

我还有很长的路要走,当然这可能不是一个非常好的代码,但这只是你可能会发现有用的基本功能。如果有人尝试并面临一些问题,我会很乐意提供帮助。另外,如果有人能指导我更好地编写代码,我将不胜感激。干杯:)