在WooCommerce 3.3中使用Google Map API进行结帐距离计算 [英] Checkout distance Calculation Using Google Map API in WooCommerce 3.3

查看:62
本文介绍了在WooCommerce 3.3中使用Google Map API进行结帐距离计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发布了 类似的问题几个月后 ,我就在那里得到了解决.直到Woocommerce版本3.1.2都运行良好.我一直在更新到最新版本的WooCommerce,希望该问题能够得到解决.

I posted a similar problem a few months back and I have been helped out there to solve it. It was working fine until Woocommerce version 3.1.2. I have been updating to latest version of WooCommerce hoping the problem will be solved.

我要根据客户结帐时的billing_area(自定义下拉菜单)与卖家的billing_city(在用户个人资料中设置)的值之间的差额添加动态费用.我正在使用的代码如下-

I am adding dynamic fees based on the difference between customer's billing_area (customized dropdown) on checkout and the value of seller's billing_city (set in user profile). The code I was using as below -

这是运行jQuery脚本,以获取更改后的billing_area的值:

This is the jQuery Script that runs to get the value of billing_area as changed:

add_action( 'woocommerce_after_checkout_form', 'custom_checkout_jquery_script', 10 );
function custom_checkout_jquery_script() {
    ?>
    <script type="text/javascript">
        (function($){
            $( 'form.checkout' ).on( 'change', '#billing_area', function(){
                var location = $('#billing_area option:selected').val();
                document.cookie="cusarea="+location;

                // Browser console output (Just for testing)
                function readCookie(n){ for(var r=n+"=",t=document.cookie.split(";"),e=0;e<t.length;e++){
                    for(var i=t[e];" "==i.charAt(0);)i=i.substring(1,i.length);
                    if(0==i.indexOf(r))return i.substring(r.length,i.length)}return null}
                $('body').trigger('update_checkout');
                console.log('Selected Area: '+location+' | Cookie: '+readCookie("cusarea"));

                //$('#order_review').load(document.URL +  ' #order_review');
                //window.location.reload(true)
            });
        })(jQuery);
        </script>
    <?php
}

这是计算费用的代码:

add_action( 'woocommerce_cart_calculate_fees', 'distance_shipping_fee', 30, 1 );
function distance_shipping_fee( $wc_cart ){

    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

    if( empty($_COOKIE ['cusarea']) ) return;
    else $cookie = $_COOKIE ['cusarea'];

    // Encoding the customer's location for Google API
    $customer_area = rawurlencode( $cookie );

    // Getting billing city of vendors
    foreach( $wc_cart->get_cart() as $cart_item ){
        $vendor_id = get_post_field( 'post_author', $cart_item['product_id'] );
        $vendors[$vendor_id] = get_user_meta($vendor_id, 'billing_city', true);
    }

    foreach( $vendors as $vend_loc){

        // Setting Google API URL ##
        $gapi_key = MY_APY; // Set HERE your google api key
        $shippingurl = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=$vend_loc";
        $shippingurl .= "+dhaka+bangladesh&destinations=$customer_area+dhaka+bangladesh&key=$gapi_key";

        // Now fetching json response from googleapis:
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $shippingurl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $response = json_decode(curl_exec($ch), true);

        // If google responds with a status of OK: Extract the distance text:
        if($response['status'] == "OK")
            $dist = $response['rows'][0]['elements'][0]['distance']['text'];

        $dist_array[] = preg_replace("/[^0-9\.]/", '', $dist);
    }


    // Get the bigger distance
    $dist_ance = max($dist_array);
    $dist_abs = abs ($dist_ance);

    if ( $dist_abs < 5) {        
        $wc_cart->add_fee( "Delivery - Distance Rate", 10 , true);
        } else {
        $wc_cart->add_fee( "Delivery - Distance Rate", 20 , true);
     }
}

问题是-它不再起作用.

Problem is - It's not working anymore.

如果我转储该值,它将为我返回$dist_abs的值(类似于5.4,即卖方位置与客户区域之间的距离).但是,不向购物车添加任何费用.

If I dump the value, it returns me the value of $dist_abs (something like 5.4 which is the distance between seller's location and customer's area). But, no fee is added to the cart.

有时候,当服务器或站点运行缓慢时,我会看到标签(交付-距离率)出现在订单查看中,但是一旦页面正确加载,它就会消失.

谁能告诉我为什么它不再起作用了?有什么我想念的吗?

Can anyone tell me why it's not working anymore? Is there something I'm missing?

推荐答案

我已经找到了使之使用ajax而不是cookie使其工作的方法……因此,请尝试以下操作:

I have found the way to make it work using ajax instead of cookies… So try the following:

add_action( 'woocommerce_after_checkout_form', 'custom_checkout_jquery_script', 30 );
function custom_checkout_jquery_script() {
    if( ! is_checkout() ) return;
    ?>
    <script type="text/javascript">
    jQuery(function($){
        // wc_checkout_params is required to continue
        if ( typeof wc_checkout_params === 'undefined' )
            return false;

        var a = '#billing_myfield5', b = a+' option:selected';
        $( 'form.checkout' ).on( 'change', a, function(){
            console.log('Chosen area: '+$(b).html()); // To be removed (testing)

            // Ajax: send the chosen customer location to php
            $.ajax({
                type: 'POST',
                url:.ajax_url,
                data: {
                    'action': 'set_customer_area',
                    'customer_area': $(b).html(),
                },
                success: function (response) {
                    $(document.body).trigger('update_checkout');
                    console.log('Response: '+response); // To be removed (testing)
                }
            });
        });
    });
    </script>
    <?php
}

// Wordpress Ajax: Saved the selected customer location to WC_Session
add_action( 'wp_ajax_nopriv_set_customer_area', 'set_customer_area_in_wc_sessions' );
add_action( 'wp_ajax_set_customer_area', 'set_customer_area_in_wc_sessions' );
function set_customer_area_in_wc_sessions() {
    if( ! isset($_POST['customer_area']) ) return;

    // Encoding the customer's location for Google API
    $customer_area_enc = rawurlencode( $_POST['customer_area'] );

    // Set the chosen customer location in WC_Sessions
    WC()->session->set('customer_area', rawurlencode($_POST['customer_area']) );

    // To be removed (testing: Send back the data to jQuery)
    echo json_encode( WC()->session->get('customer_area' ) );

    die(); // To avoid server error 500
}

// Add a fee based on the highest distance between customer and vendors
add_action( 'woocommerce_cart_calculate_fees', 'distance_shipping_fee', 30, 1 );
function distance_shipping_fee( $cart ){
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Get Url encoded customer area that is saved in WC_Session by ajax
    $customer_area = WC()->session->get('customer_area' );

    // Only when customer area has been selected
    if( empty($customer_area) )
        return;

    // Getting billing city of vendors
    foreach( $cart->get_cart() as $cart_item ){
        $vendor_id = get_post_field( 'post_author', $cart_item['product_id'] );
        $vendors[$vendor_id] = get_user_meta($vendor_id, 'billing_city', true);
    }
    $dist_array = array();

    // Loop through vendors locations
    foreach( $vendors as $vend_loc){

        // Setting Google API URL ##
        $gapi_key = MY_APY; // Set HERE your google api key
        $shippingurl = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=$vend_loc";
        $shippingurl .= "+dhaka+bangladesh&destinations=$customer_area+dhaka+bangladesh&key=$gapi_key";

        // Now fetching json response from googleapis:
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $shippingurl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $response = json_decode(curl_exec($ch), true);

        // If google responds with a status of OK: Extract the distance text:
        if($response['status'] == "OK")
            $dist = $response['rows'][0]['elements'][0]['distance']['text'];

        $dist_array[] = preg_replace("/[^0-9\.]/", '', $dist);
    }

    // Get the bigger distance
    $distance = max ($dist_array);
    $distance = abs ($distance);

    $fee = $distance < 5 ? 10 : 20;

    if ( $distance && $fee > 0 )
        $cart->add_fee( "Delivery - Distance Rate", $fee , true);
}

代码进入您的活动子主题(或活动主题)的function.php文件中.经过测试,可以正常工作.

Code goes in function.php file of your active child theme (or active theme). Tested and works.

工作后,您将必须使用// Testing ==> To be removed

Once working, you will have to remove all related lines with // Testing ==> To be removed

这篇关于在WooCommerce 3.3中使用Google Map API进行结帐距离计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆