条带javascript没有检索我需要创建费用的令牌

时间:2016-10-10 12:16:05

标签: ruby-on-rails stripe-payments

我正在尝试使用简单的条带费用处理付款,用户必须通过表单在网站上支付数量,基本上,我不知道为什么我没有收到令牌,我想我的javascript实际上没有被执行。这是代码:

This is the form placed in order#new (the form view)

    :javascript
    Stripe.setPublishableKey("<%= ENV['STRIPE_TEST_PUBLISHABLE_KEY] %>");

.container.body-content
    %h2 
        Complete order: 
        = @cart.name
    %table.table.table-items
        %tr
            %th Design name
            %th Quantity
            %th Price
        - @cart.cart_items.each do |c|
            %tr
                %td= c.design.name
                %td= c.quantity
                %td= c.design.price
        %tr
            %th Total price
            %th
            %th= @total_price
    = simple_form_for(@order, html: { role: "form", class: "cc_form" }) do |f|
        = f.simple_fields_for( :payment ) do |p|
            .row.col-md-12
                .form-group.col-md-4.no-left-padding
                    = p.input :card_number, 
                        label: "Card Number", 
                        label_html: { data: { stripe: "label" } },
                        input_html: { required: "true", data: { stripe: "number" }, class: "form-control" }
                .form-group.col-md-2
                    = p.input :card_cvv, 
                        label: "Card CVV", 
                        label_html: { data: { stripe: 'label' } },
                        input_html: { required: "true", data: { stripe: "cvv" }, class: "form-control" }
                .form-group.col-md-6
                    .col-md-12
                        = p.label :card_expires, "Card expires", data: { stripe: 'label' }
                    .col-md-3
                        = p.select :card_expires_month, options_for_select(Payment.month_options), { include_blank: 'Month' }, data: { stripe: "exp-month" }, class: "form-control", required: true
                    .col-md-3
                        = p.select :card_expires_year, options_for_select(Payment.year_options.push), { include_blank: 'Year' }, data: { stripe: "exp-year" }, class: "form-control", required: true
        = f.hidden_field :cart_id, :value => @cart.id
        = f.hidden_field_tag 'cart', @cart.id
        = f.hidden_field_tag 'total_price', @total_price
        = f.button :submit, "Pay and finish order", class: "btn btn-login"

这是orders_controller.rb:

class OrdersController < ApplicationController

    include ApplicationHelper

    def index
    end

    def new
        @order = current_user.orders.build
        @cart = Cart.find(params[:format])
        @payment = @order.build_payment
        @total_price = get_total_price_for_navigation_bar
    end

    def create
        @order = current_user.orders.build(order_params)
        @cart = Cart.find(params[:cart])
        @payment = @order.build_payment
        @payment.user_id = current_user.id
        process_payment(params[:total_price])
        if payment.save
            if @order.save
                @cart.purchased = true
                @cart.total_price = params[:total_price]
                @cart.save
                flash[:success] = "Order created"
                redirect_to orders_path
            else
                flash[:danger] = "Order couldn´t be saved, please try again"
                render :new
            end
        else
            flash[:danger] = "There was a problem processing your payment, please try again"
            render :new
        end
    end

    private
        def order_params
            params.require(:order).permit(:cart_id)
        end

        def process_payment(amount)
            #byebug
            token = params[:stripeToken]
            byebug
            # Create a charge: this will charge the user's card
            begin
              charge = Stripe::Charge.create( :amount => amount * 100, :currency => "eur", :source => token, :description => "Example charge")
            rescue Stripe::CardError => e
              # The card has been declined
            end
        end
end

并处理付款我创建了credit_card_form.js(当然在资产下 - &gt; javascripts(我还从application.js中移除了turbolink)

$(document).ready(function(){
    var show_error, stripeResponseHandler, submitHandler;

    submitHandler = function(event){
        var $form = $(event.target);
        $form.find("input[type=submit]").prop("disabled", true);

        //If stripe was correctly initialized this will create a token using the credit card info
        if(Stripe){
            Stripe.card.createToken($form, stripeResponseHandler);
        } else {
            show_error("Failed to load credit card processing functionality. Please reload this page in your browser.")
        }
        return false;
    };

    $(".cc_form").on('submit', submitHandler);

    stripeResponseHandler = function(status, response){
        var token, $form;

        $form = $('.cc_form');

        if (response.error) {
            console.log(response.error.message);
            show_error(response.error.message);
            $form.find("input[type=submit]").prop("disabled", false);
        } else {
            token = response.id;
            $form.append($('<input type="hidden" name="stripeToken">').val(token));
            $form.get(0).submit();
        }
        return false;
    };

    show_error = function(message){
        if($("#flash-messages").size() < 1){
            $('div.container.main div:first').prepend("<div id='flash-messages'></div>")
        }
        $("#flash-messages").html('<div class="alert alert-warning"><a class="close" data-dismiss="alert">x</a><div id="flash_alert">' + message + '</div></div>');
        $('.alert').delay(5000).fadeOut(3000);
        return false;
    };
});

当我尝试处理付款时,我从未收到订单#create方法中的令牌,所以我认为javascript没有执行

当我检查终端中的变量时,我发现令牌没有作为参数添加到表单中,因为我想在credit_card_form.js中附加到stripeResponseHandler中这是我在检查变量时看到的输出:

(byebug) token
nil
(byebug) params
{"utf8"=>"✓", "authenticity_token"=>"ps963bnlJwbayybIgXVAu8xQI3L6BneUK6qg5k9U9BV7XL+3M+Bl+OVJqJGNrcMHLAjhjvxOkOlhyig9Sh5Cdw==", "order"=>{"payment_attributes"=>{"card_number"=>"4012888888881881", "card_cvv"=>"123", "card_expires_month"=>"3", "card_expires_year"=>"2017"}, "cart_id"=>"9"}, "cart"=>"9", "total_price"=>"390.0", "controller"=>"orders", "action"=>"create"}
(byebug)

好吧,我不知道我是不是在做一些愚蠢的事情,或者我的方法完全错了,任何建议都会受到赞赏。

提前致谢

安东尼奥

1 个答案:

答案 0 :(得分:0)

[更新:问题解决]

几个小时后,我发现问题是什么,不是代码本身,问题实际上是HAML,正是haml解释表单id或类的方式,我不知道为什么但是我已经改变了从haml到.erb文件,正确处理客户创建和条带费用。对于我所看到的,使用形式stripeResponseHandler的haml版本没有正确执行(不要问我为什么,我不太确定,我只是知道形式没有正确更新并且令牌不包括在内作为我想要处理费用的一个参数,这就是没有成功创建费用的原因。

希望对其他人有帮助。

关心并感谢你们所有人。