使用JS v3设置Braeintree客户端 - payment_method_nonce null并且表单未提交

时间:2016-06-08 08:34:08

标签: javascript php laravel-5.2 braintree

我尝试将Braintree集成到我的Laravel 5.2应用程序中,一切都可以正常使用JS v2客户端设置,但我想将其升级到v3。 这是来自文档(我已经定制了一点):

<form id="checkout-form" action="/checkout" method="post">
  <div id="error-message"></div>

  <label for="card-number">Card Number</label>
  <div class="hosted-field" id="card-number"></div>

  <label for="cvv">CVV</label>
  <div class="hosted-field" id="cvv"></div>

  <label for="expiration-date">Expiration Date</label>
  <div class="hosted-field" id="expiration-date"></div>

  <input type="hidden" name="payment-method-nonce">
  <input type="submit" value="Pay">
</form>

<!-- Load the Client component. -->
<script src="https://js.braintreegateway.com/web/3.0.0-beta.8/js/client.min.js"></script>

<!-- Load the Hosted Fields component. -->
<script src="https://js.braintreegateway.com/web/3.0.0-beta.8/js/hosted-fields.min.js"></script>

<script>

var authorization = '{{ $clientToken }}'

braintree.client.create({
  authorization: authorization
}, function (clientErr, clientInstance) {
  if (clientErr) {
    // Handle error in client creation
    return;
  }

  braintree.hostedFields.create({
    client: clientInstance,
    styles: {
      'input': {
        'font-size': '14pt'
      },
      'input.invalid': {
        'color': 'red'
      },
      'input.valid': {
        'color': 'green'
      }
    },
    fields: {
      number: {
        selector: '#card-number',
        placeholder: '4111 1111 1111 1111'
      },
      cvv: {
        selector: '#cvv',
        placeholder: '123'
      },
      expirationDate: {
        selector: '#expiration-date',
        placeholder: '10 / 2019'
      }
    }
  }, function (hostedFieldsErr, hostedFieldsInstance) {
    if (hostedFieldsErr) {
      // Handle error in Hosted Fields creation
      return;
    }

    form.addEventListener('submit', function (event) {
      event.preventDefault();

      hostedFieldsInstance.tokenize(function (tokenizeErr, payload) {
        if (tokenizeErr) {
          // Handle error in Hosted Fields tokenization
          return;
        }

        document.querySelector('input[name="payment-method-nonce"]').value = payload.nonce;
        form.submit();
      });
    }, false);
  });
});
</script>

但是当我点击提交按钮时,没有任何反应。event.preventDefault()停止提交并生成payment_method_nonce令牌,但之后我无法提交表单,因为form.submit()不起作用

如何在event.preventDefault()之后提交表单? 或者我如何将payment_method_nonce令牌发送给我的控制器?

谢谢!

1 个答案:

答案 0 :(得分:1)

当我复制你的代码片段并尝试运行该示例时,我在控制台中获得了(index):69 Uncaught ReferenceError: form is not defined。当我添加

var form = document.getElementById('checkout-form');

它运作得很好。

最好的猜测,你只是忘了指定表单变量来引用表单dom元素。如果情况并非如此,请务必告诉我。