在 Rails 应用程序中集成 Stripe [英] Integrating Stripe in Rails app

查看:36
本文介绍了在 Rails 应用程序中集成 Stripe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个带有 Stripe 的自定义表单,虽然这一切似乎都在提交,但当我在 Stripe 中查看我的仪表板时,虽然我确实看到了交易记录 - 我没有看到金额或任何参考到 cc 通过.话虽如此,我不太确定我应该在仪表板中看到什么.但我很确定我做错了什么.这是我表单的代码:

<div class="row 第一行"><div class="col-sm-12 col-md-10"><%= form_for @project, url: project_charges_path, :html =>{:id =>"payment-form"}, 方法: '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, "信用卡号" %><br><%= text_field_tag :card_number, nil, name: nil %><br>

<div class="field"><%= label_tag :card_code, "安全代码 (cvc)" %><br><%= text_field_tag :card_code, nil, name: nil %><br>

<div class="field"><%= label_tag :card_month, "过期" %><%= 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 class="actions"><%= f.submit("提交") %>

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

<%结束%>

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

这是我的收费控制器:

class ChargesController <应用控制器定义新@project = Project.find(params[:project_id])结尾定义创建@project = Project.find(params[:project_id])绑定.撬# 以美分为单位的金额,正在条带仪表板中读取和记录@金额 = 500customer = Stripe::Customer.create(:email =>'helloWorld@stripe.com',:卡=>参数[:stripeToken])充电 = 条纹::充电.创建(:客户 =>顾客ID,:金额=>@数量,:描述 =>'Rails Stripe 客户',:货币=>'美元')@payment = Payment.create({user_id: current_user.id,project_id: @project,金额:@金额})@payment.save救援 Stripe::CardError =>电子flash[:error] = e.message结尾# 私人的# def charge_params# params.require(:payment).permit(:comments, :user_id, :project_id)# 结尾

结束

根据教程,我还在 application.js 中包含了一些 javascript:

$('#payment-form').submit(function(event) {var $form = $(this);alert('你点击了提交');//禁用提交按钮以防止重复点击$form.find('button').prop('disabled', true);Stripe.card.createToken($form, stripeResponseHandler);//防止表单使用默认操作提交返回假;});功能条带响应处理程序(状态,响应){var $form = $('#payment-form');如果(响应.错误){//在表单上显示错误$form.find('.payment-errors').text(response.error.message);$form.find('button').prop('disabled', false);} 别的 {//响应包含 id 和 card,其中包含额外的卡片详细信息var token = response.id;//将令牌插入到表单中,以便将其提交给服务器$form.append($('<input type="hidden" name="stripeToken"/>').val(token));//并提交$form.get(0).submit();}}

在条纹仪表板内我看到:

电子邮件通过了,但与金额或卡无关.我不希望看到卡号,而是对它的一些参考,也许只是类型,或者最后四位数字?同样在仪表板的首页(给出图表的区域,我想我应该看到付款的总和,甚至是测试付款,尽管已经进行了十多次测试付款,每笔 5 美元,但总和仍然是 0 美元.

我在这里遗漏了什么?

此外,我遇到的大多数教程要么是非常老的,要么是我不熟悉的 PHP.如果有人可以推荐一个很好的资源,那也真的很有帮助.我打算在多个项目中使用 Stripe,并且真的很想了解它...

解决方案

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

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

查看:(creditcard.html.erb)

<% if flash[:error].present?%><div class="col-lg-12 alert alert-danger"><%= flash[:error]%>

<%其他%><div class="col-lg-12" id = "payment-errors"><span class="payment-errors"></span>

<%结束%>

<div><%= form_tagplans_billings_chargecreditcard_path, id: "payment-form" do%><div class="row"><div class="col-lg-3"><div class="form-group"><label>卡号</label><%= text_field_tag nil, nil, size: 20, "data-stripe": "number", class: "form-control" %>

<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 class="row"><div class="col-lg-12"><div class="form-group"><label>失效日期(MM/YY)</label><select class="selectpicker set-width" data-live-search="true" data-stripe = "exp_month"><option>-月-</option><option>1</option><option>2</option><选项>3</选项><选项>4</选项><option>5</option><option>6</option><option>7</option><option>8</option><option>9</option><option>10</option><选项>11</选项><option>12</option></选择><select class="selectpicker set-width" data-live-search="true" data-stripe = "exp_year"><!-- form-control input-lg --><option>-年份-</option><选项>16</选项><选项>17</选项><option>18</option><option>19</option><option>20</option><选项>21</选项><option>22</option><option>23</option><option>24</option><option>25</option><option>26</option></选择>

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

<%结束%>

咖啡脚本:(plan_billings.coffee)

stripeResponseHandler = (status, response) -># 抓取表格:$form = $('#payment-form')如果 response.error# 问题!# 在表单上显示错误:$('#payment-errors').addClass 'alert'$('#payment-errors').addClass 'alert-danger'$('.payment-errors').text response.error.message$('.submit').prop 'disabled', false# 重新启用提交别的# 令牌已创建!# 获取令牌ID:令牌 = response.id# 将令牌 ID 插入表单,以便将其提交给服务器:$form.append $('<input type="hidden" name="stripeToken">').val(token)# 提交表单:$form.get(0).submit()返回$ ->$form = $('#payment-form')$form.submit(事件)-># 禁用提交按钮以防止重复点击:$form.find('.submit').prop 'disabled', true# 从 Stripe 请求令牌:Stripe.card.createToken $form, stripeResponseHandler# 防止表单被提交:错误的返回

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

@plan_and_billing = current_user.plan_billing@current_plan = DataPlan.find_by(id: @plan_and_billing.data_plan_id)令牌 = params[:stripeToken]如果 current_user.customer_id.present?customer = Stripe::Customer.retrieve(current_user.customer_id)customer.sources.create(来源:令牌)重定向到plans_billings_planbilling_path别的customer = Stripe::Customer.create(:source => 令牌,计划:YOUR_PLAN_ID_YOU_HAVE_INYOUR__DASHBOARD)@credit_card = current_user.update(customer_id: customer.id)重定向到plans_billings_planbilling_path结尾救援 Stripe::CardError =>电子flash[:error] = e.message重定向到plans_billings_creditcard_path

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

在这方面我还有很长的路要走,当然这可能不是一个很好的代码,但这只是您可能会觉得有用的非常基本的事情.如果有人尝试并面临一些问题,我很乐意提供帮助.另外,如果有人能指导我改进此代码,我将不胜感激.干杯:)

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:

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

解决方案

I might be very late in replying and you must have already done this but just in case this might help some else. I have just integrated stripe in my app. I am not sure what you are asking but i think a working example might help. This is very similar to what you have done and i can't find what's going wrong.

What i'm doing is saving customer_id returned by stripe in my user table. When the user saves the credit card, a certain amount according to the subscription plan is deducted. You will see the customer_id in your plan details under the subscribers in the dashboard. Also, in the customers, When you refer that customer_id, you'll see what plan he's subscribed to.

View: (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

Controller: (in PlanBilling controller, chargecreditcard action)

@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

What's happening in controller is that when a user has no card and he saves the card details, the card is saved and the Price of the plan you have mentioned is deducted. And if he already has a credit card saved, and saving another one, the card will only be saved as you'll see in his details in the dashboard. The new card will not be charged. Its just for saving new credit card to that customer.

I still have a long way to go in this, and of course this might not be a very good code, but this is just very basic thing you might find helpful. In case someone tries it out and faces some prob, i'll be glad to help. Also, I'll be grateful if someone can guide me to make this code better. Cheers :)

这篇关于在 Rails 应用程序中集成 Stripe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆