首页 文章

结帐页面中的Woocommerce付款方式检测

提问于
浏览
0

我正在使用woocommerce插件和wointommerce的braintree扩展付款 . 我已经支持woocommerce braintree的卡和paypal支付结账 . 我试图弄清楚如何知道用户在用户实际结账和付款之前选择了哪个支付网关 . 任何 hookswoocommercebraintree 下找到信用卡单选按钮或paypal付款单选按钮都会被检查付款 .

但是我知道我们可以在成功付款后检测用于特定订单的网关,但我希望在结账页面中付款完成之前选择的网关信息 . 任何帮助?

1 回答

  • 0

    您可以在结帐页面上使用一些基本的JavaScript检测所选的付款方式,并通过挂钩到 woocommerce_checkout_update_order_review 操作来运行您的自定义代码 .

    首先,您还应该将JS代码放在结帐页面,结帐模板或主题的页眉/页脚中,以便您可以检测用户何时更改了付款方式选项并在此之后运行您自己的代码 .

    JS代码:

    jQuery(document).ready( function() {
    
        jQuery( "#payment_method_bacs" ).on( "click", function() {
            jQuery( 'body' ).trigger( 'update_checkout' );
        });
    
        jQuery( "#payment_method_paypal" ).on( "click", function() {
            jQuery(document.body).trigger("update_checkout");
        });
    
        jQuery( "#payment_method_stripe" ).on( "click", function() {
            jQuery(document.body).trigger("update_checkout");
        });
    
    });
    

    请注意,对于您处于活动状态的每种付款方式,您应添加'Click'事件 . 它为您提供了在触发自定义代码时进行微调的选项 . 要防止单击事件到 run ONLY ONCE ,您应该在第一个下面添加下一个JS代码块 .

    jQuery( document ).ajaxStop(function() {
    
        jQuery( "#payment_method_bacs" ).on( "click", function() {
            jQuery(document.body).trigger("update_checkout");
        });
    
        jQuery( "#payment_method_paypal" ).on( "click", function() {
            jQuery(document.body).trigger("update_checkout");
        });
    
        jQuery( "#payment_method_stripe" ).on( "click", function() {
            jQuery(document.body).trigger("update_checkout");
        });
    });
    

    它只是在ajax之后触发的相同代码 . 在两个JS代码块中添加 you are actually use 的付款选项 .

    之后,您将自定义的PHP代码挂钩到结帐,如下所示:

    if ( ! function_exists( 'name_of_your_function' ) ) :
        function name_of_your_function( $posted_data) {
    
            // Your code goes here
    
         }
    
    endif;
    
    add_action('woocommerce_checkout_update_order_review', 'name_of_your_function');
    

    此代码可以放在functions.php中 .

    以下是完整的PHP代码,可在结帐页面上选择特定付款选项时检测并运行:

    function name_of_your_function( $posted_data) {
    
        global $woocommerce;
    
        // Parsing posted data on checkout
        $post = array();
        $vars = explode('&', $posted_data);
        foreach ($vars as $k => $value){
            $v = explode('=', urldecode($value));
            $post[$v[0]] = $v[1];
        }
    
        // Here we collect payment method
        $payment_method = $post['payment_method'];
    
        // Run code custom code for each specific payment option selected
        if ($payment_method == "paypal") {
            // Your code goes here
        }
    
        elseif ($payment_method == "bacs") {
            // Your code goes here
        }
    
        elseif ($payment_method == "stripe") {
            // Your code goes here
        }
    }
    
    add_action('woocommerce_checkout_update_order_review', 'name_of_your_function');
    

    我希望这有帮助!这是在结帐页面上运行所有自定义逻辑的一个非常强大的选项!

相关问题