创建客户时出现条带错误:您为' card'传递了一个空字符串

时间:2014-06-09 13:47:07

标签: ruby-on-rails ruby ruby-on-rails-4 erb stripe-payments

Stripe不接受付款,收费仍然失败。我收到了这个错误:

Started POST "/charges" for 127.0.0.1 at 2014-06-09 06:30:58 -0700
Processing by ChargesController#create as HTML
  Parameters: {"utf8"=>"√", "authenticity_token"=>"9bqk2Q6NEM1ehHDJPgncNQ3gnP0X1hQK6y6ENm3Yb1g=", "c
harge"=>{"contest_id"=>"36", "user_id"=>"", "amount"=>"12", "stripe_card_token"=>""}, "card_number"=
>"4242 4242 4242 4242", "card_code"=>"478", "button"=>""}
Stripe error while creating customer: You passed an empty string for 'card'. We assume empty values
are an attempt to unset a parameter; however 'card' cannot be unset. You should remove 'card' from y
our request or supply a non-empty value
Redirected to http://localhost:3000/
Completed 302 Found in 477ms (ActiveRecord: 0.0ms)

好像它可能没有创建条带令牌?这是怎么回事?

这是我的表格:

 <% content_for :head do %>
        <%= tag :meta, :name => "stripe-key", :content => STRIPE_PUBLIC_KEY %>
    <% end %>
    <%= form_for @charge, :html => { :class => 'form' } do |f| %>
        <div class="form-inputs">
            <div class="row">
                <%= f.hidden_field :contest_id, value: @contest.id  %>
                <%= f.hidden_field :user_id %>
                <%= f.hidden_field :amount %>
                <!-- TODO CHANGE THIS ACCORDINGLY  -->
                <%= f.hidden_field :stripe_card_token %>
                <div class="small-12 medium-6 large-2 columns">
                    <%= f.label "Amount:", class: "text-right" %>
                </div>
                <div class="small-12 medium-6 large-10 columns" style="margin-bottom: 0.5rem; margin-top: 0.5rem;">
                    <%= number_to_currency(@charge.amount, :unit => "$") %>
                </div>
                <% if @charge.stripe_card_token.present? %>
                  Credit card has been provided.
                <% else %>
                  <div class="small-12 medium-6 large-2 columns">
                    <%= label_tag :card_number, "Credit Card Number:", class: "text-right" %>
                  </div>
                  <div class="small-12 medium-6 large-10 columns">
                    <%= text_field_tag :card_number %>
                  </div>
                  <div class="small-12 medium-6 large-2 columns">
                    <%= label_tag :card_code, "Security Code on Card (CVV):", class: "text-right" %>
                  </div>
                  <div class="small-12 medium-6 large-10 columns end">
                    <%= text_field_tag :card_code %>
                  </div>
                  <div class="small-12 medium-6 large-2 columns">
                    <%= label_tag :card_month, "Card Expiration:", class: "text-right" %>
                  </div>
                  <div class="small-6 medium-3 columns">
                    <%= select_month nil, {add_month_numbers: true}, {name: nil, id: "card_month"} %>
                  </div>
                  <div class="small-6 medium-3 columns">
                    <%= select_year nil, {start_year: Date.today.year, end_year: Date.today.year+15}, {name: nil, id: "card_year"} %>
                  </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>
            <div class="row">
                <div class="form-actions small-9 small-offset-2 columns">
                    <%= button_tag :type => "button", :class => "radius" do  %>
                        <%= link_to "Back", @contest, :style => "color: white" %>
                    <% end %>
                    <%= f.button :Donate, :class => "radius" %>
                </div>
            </div>
        </div>
    <% end %>
    <% content_for :js do %>
        <%= javascript_include_tag "https://js.stripe.com/v1", "application" %> 
        <%= javascript_include_tag asset_path("stripe/stripe.js"), "application" %>
    <% end %>

这是我的收费控制器:

class ChargesController < ApplicationController

    def new
      @contest = Contest.find(params[:id])
      @charge = Charge.new(amount: params[:amount])
    end

    def create
      @charge = Charge.new(charges_params)
      if @charge.save_with_payment(@charge)
        redirect_to root_path, :notice => "Contribution was recorded succesfully!"
      else
        redirect_to root_path, :notice => "Transaction was not able to be recorded"
      end
    end

    def charges_params
        params.require(:charge).permit(:stripe_card_token, :contest_id, :user_id, :amount)
    end

end

我的收费模式:

class Charge < ActiveRecord::Base

    attr_accessor :stripe_card_token

    belongs_to :contest
    belongs_to :user

    def save_with_payment(charge)
      if valid?
        Stripe::Charge.create(
          :amount => (charge.amount.to_i)*100,
          :currency => "usd",
          :card => stripe_card_token);
        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

3 个答案:

答案 0 :(得分:0)

很可能看起来stripe_card_token为空白

:card => stripe_card_token

尝试将其更改为

:card => charge.stripe_card_token

答案 1 :(得分:0)

stripe_card_token空白无关,您的服务器当前处于PCI范围,因为它正在接收卡号和CVV代码。如果你正在使用Stripe,这可能不是你想要的。

来自Stripe Getting Started docs

  

注意表示敏感卡数据的输入字段(数字,CVC,   到期月份和年份)没有&#34;名称&#34;属性。这个   在提交表单时阻止他们访问您的服务器。

Rails标记助手默认生成名称属性。在这种情况下,这是不可取的。

您可以通过为namevalue传递nil并定义某种标识符来覆盖此行为:

<%= text_field_tag nil, nil, 'data-stripe' => 'card_number' %>

在这里,我使用了Stripe目前推荐的data-stripe,但您也可以使用id属性(如他们推荐的旧教程)。

回到原来的问题,问题出在您的Charge模型中,您可以在其中覆盖Active Record并屏蔽数据库中的数据:

class Charge < ActiveRecord::Base

    attr_accessor :stripe_card_token     # Don't do this!
绝不应在数据库列上使用

attr_accessor。 Active Record提供自己的访问器,以便从数据库中提取数据;通过在此处声明访问者,您可以使用Ruby的基本功能替换Active Record的功能:

irb(main):001:0> Charge.first
  Charge Load (0.3ms)  SELECT  "charges".* FROM "charges"   ORDER BY "charges"."id" ASC LIMIT 1
=> #<Charge id: 1, stripe_card_token: "0xdeadbeef", created_at: "2014-06-11 14:27:40", updated_at: "2014-06-11 14:27:40">
irb(main):002:0> c.stripe_card_token
=> nil

话虽如此,您开始使用的Railscast已有近三年的历史,违反了各地的最佳实践,并使用了一个过时的API端点。一旦您更正了模型,您最好不要使用Stripe的当前教程和文档来启动表单和JavaScript。

答案 2 :(得分:-1)

我遇到了同样的问题 我的 subscription.js.coffee:

jQuery ->
  Stripe.setPublishableKey($('meta[name="stripe-key"]').attr('content'))
  subscription.setupForm()

subscription =
  setupForm: ->
    $('#new_subscription').submit (e) ->
      $('input[type=submit]').attr('disabled', true)
      subscription.processCard()
      return false

  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)
      false

正如您所看到的,当用户按下submit按钮时,会引发函数$('#new_subscription').submit (e)。提交函数中几乎存在所有条纹魔法。

在我的情况下,有时候不会引发提交功能,因此会将空stripe_card_toke参数发送到您的服务器。

奇怪的行为是由Rails turbolinks设施引起的 我用这样的方式解决了它:

  1. 添加到 Gemfile 一行:
    gem 'jquery-turbolinks'
  2. 添加到清单 application.js 一行:
    //= require jquery.turbolinks
    所以我的 application.js 看起来像是:
  3. //= require jquery
    //= require jquery.turbolinks
    //= require jquery_ujs
    //= require turbolinks
    //= require bootstrap
    //= require jquery_nested_form
    //= require_tree .