Stripe Checkout with Custom Integration in Rails

后端 未结 4 1064
情歌与酒
情歌与酒 2020-12-29 07:48

I am trying to implement Stripe Checkout using the custom integration in a rails app - my checkout form shows a green checkmark saying it submitted but the payment is not be

相关标签:
4条回答
  • 2020-12-29 08:18

    Here is a working solution. Add an id to your form tag. Add a stripeToken and stripeEmail hidden field to your form tag. Then when we receive the token from Stripe we will use JavaScript to set the values of the hidden fields and submit the form by referencing their id's:

    <%= form_tag charges_path, id: 'chargeForm' do %>
      <script src="https://checkout.stripe.com/checkout.js"></script>
      <%= hidden_field_tag 'stripeToken' %>
      <%= hidden_field_tag 'stripeEmail' %>
      <button id="customButton" class="btn btn-large btn-primary">Buy Now</button>
    
      <script>
        var handler = StripeCheckout.configure({
          key: '<%= ENV["STRIPE_PUBLIC_KEY"] %>',
          image: '/assets/my_logo.png',
          token: function(token, args) { 
            document.getElementById("stripeToken").value = token.id;
            document.getElementById("stripeEmail").value = token.email;
            document.getElementById("chargeForm").submit();
          }
        });
    
        document.getElementById('customButton').addEventListener('click', function(e) { 
          // Open Checkout with further options
          handler.open({
            name: 'My Company',
            description: 'Product ($60.00)',
            amount: 60*100,
            shippingAddress: true
          });
          e.preventDefault();
        });
      </script>
    <% end %>
    

    This can be solved many ways but bare in mind this is a JavaScript problem nothing to do with Rails or Stripe really. Stripe are simply giving us the token we can do whatever we want with it with JavaScript.

    0 讨论(0)
  • 2020-12-29 08:20

    You need to finish the token callback function.

    First pass in the response from the Stripe handler as an argument and then append the token id and email as inputs to the form before submitting it: (untested)

    token: function(response) {
      var tokenInput = $("<input type=hidden name=stripeToken />").val(response.id);
      var emailInput = $("<input type=hidden name=stripeEmail />").val(response.email);
      $("form").append(tokenInput).append(emailInput).submit();
    }
    
    0 讨论(0)
  • 2020-12-29 08:25

    With the "simple integration" you can still change the text in the default blue button with the data-label attribute(eg data-label='Buy now') using the configuration options. But yeh you have to use "custom integration" to fully style the button yourself

    0 讨论(0)
  • 2020-12-29 08:45

    I think you don't want to preventDefault here, because that prevents your form from being submitted to the server. Does it submit the form to the create action when you take out e.preventDefault(); ?

    0 讨论(0)
提交回复
热议问题