使用 Braintree 自定义表单以编程方式提交

Programmatically Submit with Braintree Custom Form

我有一个位于 Bootstrap 模态中的 Braintree 自定义表单。现在,如果我在表单中放置一个提交按钮,Braintree 表单就可以正常工作。当我单击那个提交按钮时,Braintree 拦截它并运行它获取随机数的提交处理程序,然后 returns 它到 onPaymentMethodReceived 方法。到目前为止,一切都很好。但是,我想在模式底部使用一个漂亮的 Bootstrap 主题按钮来提交表单,而不是 <form> 标签本身内的提交按钮。

但是,如果我设置这样一个按钮并给它一个 click 动作 $( "#paymentForm" ).submit();,这似乎是以传统方式提交它而不是触发 Braintree 的处理程序。有没有办法以编程方式触发 Braintree 的提交处理程序?

您可以做的一件事是在表单本身中提供一个按钮,但将其隐藏。并让 bootstrap 页脚中的按钮单击真正的按钮。这将允许 Braintree 的表单提交劫持正常工作。

<form id="form" method="post" action="/checkout">
  <div id="payment-form"></div>
  <input type="submit" style="position:fixed; top:-200%;left:-200%;" id="real-btn">
</form>
<button type="submit" id="fake-btn">Pay</button>

<script type="text/javascript" src="https://js.braintreegateway.com/js/braintree-2.27.0.min.js"></script>
<script type="text/javascript">
  var clientToken = "YOUR_TOKEN_HERE";
  var fakeBtn = document.getElementById('fake-btn');
  var realBtn = document.getElementById('real-btn');

  braintree.setup(clientToken, 'dropin', {
    container: 'payment-form'
  });

  fakeBtn.addEventListener('click', function (e) {
    realBtn.click();
  });
</script>

此外,这里有一个 codepen using jQuery and Bootstrap 可以在 Bootstrap 模态中完成解决方案。

该演示使用此 Bootstrap modal example and the pre-generated client token from the Braintree docs. It uses the onPaymentMethodReceived callback 来说明标记化是成功的,但如果您只想提交表单,则对于解决方案来说不是必需的。

另一种解决方案是以编程方式单击按钮:

<form>
    <div id="braintree-container"></div>
    <input type="submit" style="display: none;">
</form>

<button>Pay</button>

<script type="text/javascript">
    $('button').click(function () {
        $('input[type=submit]').click();
    });
</script>