【问题标题】:Stripe javascript not retrieving the token I need to create a chargeStripe javascript没有检索我需要创建费用的令牌
【发布时间】:2016-10-14 17:06:59
【问题描述】:

我正在尝试使用简单的条带费用来处理付款,用户必须通过表格在网站上支付一定数量,基本上,我不知道为什么我没有取回令牌,我想我的 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 的付款(当然在 assets -> javascripts 下(我还从 application.js 中删除了 turbolinks)

$(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;
    };
});

当我尝试处理付款时,我从未在 order#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)

好吧,我不知道我是不是看到了什么愚蠢的东西,或者我的方法完全错误,任何建议都将不胜感激。

提前致谢

安东尼奥

【问题讨论】:

  • 我认为第一步是向您的submitHandler 添加一些日志记录,以确保它实际被调用。

标签: ruby-on-rails stripe-payments


【解决方案1】:

[更新:问题已解决]

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

希望对其他人有所帮助。

问候和感谢你们。

【讨论】:

    猜你喜欢
    • 2018-03-19
    • 1970-01-01
    • 2019-06-06
    • 2013-06-21
    • 2018-03-22
    • 2014-02-22
    • 2018-09-13
    • 2016-07-02
    • 2017-09-28
    相关资源
    最近更新 更多