Search code examples
ruby-on-railsbraintree

passing nonce to server and back to Braintree SDK


The following view is generating a proper nonce as evidenced by the alert in the javascript code.

<div class='row'>
  <div class='small-12 columns text-center'>
    <h4><%= t('proceed_to_payment') %> <%= number_to_currency(@clientorder.payment_amount) %></h4>
    <% if !@clientorder.paid? %>
      <%= form_tag transacted_clientorders_path(id: @clientorder.id), id: 'checkout' do %>
        <input type="hidden" id="nonce" name="payment_method_nonce" />
        <div id='dropin-container'></div>
        <%= submit_tag t('submit'), id: 'submit-button' %>
      <% end %>
      <script>
        $.ajax({
          method: "POST",
          url: "/transacted?id=<%= @clientorder.id %>&locale=<%= I18n.locale %>",
          data: { payment_method_nonce: payload.nonce }
        })
      </script>
      <script>
        var button = document.querySelector('#submit-button');
        braintree.dropin.create({
          authorization: "<%= @client_token %>",
          container: '#dropin-container'
          }, function (createErr, instance) {
            button.addEventListener('click', function () {
              instance.requestPaymentMethod(function (err, payload) {
                alert(payload.nonce);
                console.log(payload.nonce);
                console.log(err);
                if (err) {
                  console.log('Error', err);
                  return;
                }
             // Add the nonce to the form and submit
               document.querySelector('#nonce').value = payload.nonce;
               form.submit();
             });
            });
          });
      </script>
    <% end %>
  </div>
</div>

the controller action

  def transacted
    @result = Braintree::Transaction.sale(
      amount:  @clientorder.payment_amount,
      payment_method_nonce: params[:payment_method_nonce], 
      options: {
        submit_for_settlement: true},
      )
    if @result.transaction.status == "submitted_for_settlement"
      [...]

however does not lead to any further action. @resultis nil as an nonce is not being submitted, and in practice the amount also in not being passed for the following are the request parameters logged.

{"utf8"=>"✓",
 "authenticity_token"=>"qXjwFuI4mNRM+ZFoQ5TwvUBv58fLNVJyQVHJm/FfBdIaArbfhjJP0WirTe+7FnSl+/asJ+fY+d+JPA7xKNLP6Q==",
 "payment_method_nonce"=>"",
 "commit"=>"Submit",
 "id"=>"4",
 "locale"=>"en"}

where has this strayed from the proper path?


Solution

  • There are a few things wrong.

    1. The ajax call in that position does not get the nonce to handle
    2. Set up this way, there are going to be 2 calls to the server: the ajax call and the form call itself
    3. The consequence of item 2 is that the form call will have an empty nonce and thus will generate !result.success? and thus a hash of result.errors which should be eventually handled.

    Thus,

    <div class='row'>
    <div class='small-12 columns text-center'>
      <div id="dropin-container"></div>
      <button id="submit-button" class='button success'><%= t('proceed_to_payment') %> <%= number_to_currency(@clientorder.payment_amount) %></button>
      <script>
        var button = document.querySelector('#submit-button');
    
        braintree.dropin.create({
          authorization: '<%= @client_token %>',
          container: '#dropin-container'
        }, function (createErr, instance) {
          button.addEventListener('click', function () {
            instance.requestPaymentMethod(function (err, payload) {
              // Submit payload.nonce to your server
            $.ajax({
              method: "POST",
              url: "<%= transacted_clientorders_path(id: @clientorder.id, locale: I18n.locale) %>",
              data: { payment_method_nonce: payload.nonce }
            })
            if (err) {
              console.log('Error', err);
              return;
            }
               // Add the nonce to the form and submit
                    document.querySelector('#nonce').value = payload.nonce;
                    form.submit();
            });
          });
        });
      </script>