使用 Braintree 的 onPaymentMethodReceived 调用 asp.net 按钮的 OnClick

Calling OnClick of asp.net button with Braintree's onPaymentMethodReceived

我正在使用他们的自定义表单进行 Braintree 集成。在提交表单之前,我想先 运行 对其他表单字段进行一些自定义验证。根据他们的 documentation 我正在使用 onPaymentMethodReceived 回调,这样我可以在回发之前先检查页面是否有效。我的表单按钮有一个服务器端 onclick 处理程序 (lnkBuyNow_Click)。

<asp:Button ValidationGroup="purchaseval" ID="lnkBuyNow" OnClick="lnkBuyNow_Click" runat="server" Text="Complete order"></asp:Button>

我面临的问题是,如果我调用 $('<%= lnkBuyNow.ClientID %>').click() Braintree 再次调用 onPaymentMethodReceived 函数,这会阻止页面回发并陷入循环。建议的方法是使用 $form.submit(),但是如果我这样做,那么我将丢失服务器上的 onclick 处理程序——这是我需要的。下面是我用来初始化 Braintree 和回调函数的代码

braintree.setup('<%= braintreeClientToken %>', 'custom', {id: 'form1', onPaymentMethodReceived: braintreeResponseHandler});

function braintreeResponseHandler(response) {
    var $form = $('#form1');
    Page_ClientValidate();
    if (Page_IsValid) {                    
        var token = response.nonce;
        // Insert the token into the form so it gets submitted to the server
        $form.append($('<input type="hidden" name="payment_method_nonce" />').val(token));
        // and submit                      
        //$('#<%= lnkBraintreeDummy.ClientID %>').click();//This would allow the lnkBuyNow_Click of the button to fire on the server
        $form.submit();//This works as expected but now lnkBuyNow_Click does not get fired.
    }                
};

两个问题

  1. 如果页面有效,是否有办法绕过 Braintree 的事件处理程序,以便我可以调用 $('<%= lnkBuyNow.ClientID %>').click()
  2. 如果不是,有没有办法让 .NET 认为在使用 $form.submit()
  3. 时点击了按钮

我想通了。 Braintree 有一个 teardown method 其中

will clean up any DOM nodes, event handlers, popups and/or iframes that have been created by the integration

这意味着我可以删除按钮点击的事件处理程序,可以直接调用按钮的点击。

我最后做的是这样的:

var braintreeCheckout;
function braintreeResponseHandler(response) {
    var $form = $('#form1');
    Page_ClientValidate();
    if (Page_IsValid) {                    
        var token = response.nonce;
        braintreeCheckout.teardown(function () {
            braintreeCheckout = null;
            $form.append($('<input type="hidden" name="payment_method_nonce" />').val(token));                  
            $("#<%= lnkBuyNow.ClientID %>").click();                        
        });

    }                
};

braintree.setup('<%= braintreeClientToken %>', 'custom', {
    id: 'form1', 
    onPaymentMethodReceived: braintreeResponseHandler,
    onReady: function (integration) {
        braintreeCheckout = integration;
    }
});