首页 > 解决方案 > WooCommerce 结帐 - 更新运费

问题描述

我正在使用 Sendy API 根据从 Google Location API 管理的下拉列表中选择的位置计算结帐页面中的运费。除了我的运费没有计算在内,其他一切都很好。我不确定如何通过运输,因为每次选择位置时我都会得到 0 值。谷歌搜索后,我想出了这个代码分解。有人,请帮助如何实现这一目标。

  1. AJAX 从 API 中提取运费

    function sendy_api_script() 
    {
    ?>
    <?php if(is_checkout()){ ?>
    <script type="text/javascript">
    jQuery( document ).ready(function( $ ) {
        $('#sendy_location').niceSelect('destroy');
    
        $(document).on('change','#sendy_location',function(){
            shipping_location_selected = $(this).val();
            cart_total = $('.cart-subtotal .woocommerce-Price-amount').text().replace("KShs","");
             $.post(ajaxurl,{
                 "action": 'update_shipping_cost',
                 "sendy_location":shipping_location_selected,
                 "cart_total":cart_total,
             },function(){
                 $('body').trigger('update_checkout');
             });
        });
    
        var input = document.getElementById('sendy_location');
        google.maps.event.addDomListener(window, 'load', input); 
    
        var options = {
            types: ['geocode'],
            componentRestrictions: {country: "ke"}
        };
    
        var autocomplete = new google.maps.places.Autocomplete(input, options);
    
        google.maps.event.addListener(autocomplete, 'place_changed', function() {
            var place = autocomplete.getPlace();
            document.getElementById('city2').value = place.name;
            document.getElementById('cityLat').value = place.geometry.location.lat();
            document.getElementById('cityLng').value = place.geometry.location.lng();
    
            //sendy api call
            var name = $('#billing_first_name').val()+' '+$('#billing_last_name').val();
            var phone = $('#billing_phone').val();
            var email = $('#billing_email').val();
            var customerLocation = $('#city2').val();
            var cityLat = $('#cityLat').val();
            var cityLng = $('#cityLng').val();
            var amountTotal = $('#amounttotal').val();
            var pickupdate = $('#pickupdate').val();
            var requestToken = $('#randomvalue').val();
    
            /* distance calculation between customer pickup point and Kericho Gold dispatch location */
            var dispatchNairobi = 'Nairobi, Kenya';
            var dispatchMombasa = 'Mombasa, Kenya';
    
            // var source = 'Nairobi, Kenya';
            var destination = customerLocation;
    
            var service = new google.maps.DistanceMatrixService();
            service.getDistanceMatrix({
                origins: [dispatchNairobi],
                destinations: [destination],
                travelMode: google.maps.TravelMode.DRIVING,
                unitSystem: google.maps.UnitSystem.METRIC,
                avoidHighways: false,
                avoidTolls: false
            }, function (response, status) {
                if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
                    var distanceNairobi = response.rows[0].elements[0].distance.value;
                    var durationNairobi = response.rows[0].elements[0].duration.text;
    
                    $("#nairobiDistance").val(distanceNairobi).change();
    
                } else {
                    alert("An error occured.");
                }
            });
    
            service.getDistanceMatrix({
                origins: [dispatchMombasa],
                destinations: [destination],
                travelMode: google.maps.TravelMode.DRIVING,
                unitSystem: google.maps.UnitSystem.METRIC,
                avoidHighways: false,
                avoidTolls: false
            }, function (response, status) {
                if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
                    var distanceMombasa = response.rows[0].elements[0].distance.value;
                    var durationMombasa = response.rows[0].elements[0].duration.text;
    
                    $("#mombasaDistance").val(distanceMombasa).change();
    
                } else {
                    alert("An error occured.");
                }
            });             
    
            /* end */
            jQuery('input#mombasaDistance').on( 'change', function(){
                if( $("#mombasaDistance").val() < $("#nairobiDistance").val() )
                {
                    var dispatchLocation = dispatchMombasa;
                    var dispatchLat = '-4.0350145';
                    var dispatchLong = '39.5962225';    
    
                    console.log(dispatchLocation);
                }
                else if($("#nairobiDistance").val() < $("#mombasaDistance").val())
                {
                    var dispatchLocation = dispatchNairobi;
                    var dispatchLat = '-1.3028618';
                    var dispatchLong = '36.7073099';
    
                    console.log(dispatchLocation);
                }
    
                $.ajax({
    
               data:{
    "action": 'sendyapicall',
    "security": "wc_checkout_params.update_order_review_nonce",
    "command": "request",
    "data": {
        "api_key": "API-Key",
        "api_username": "username",
        "vendor_type": 1,
        "from": {
          "from_name": "dispatchLocation",
          "from_lat": "dispatchLat",
          "from_long": "dispatchLong",
          "from_description": ""
        },
        "to": {
          "to_name": customerLocation,
          "to_lat": cityLat,
          "to_long": cityLng,
          "to_description": ""
        },
        "recepient": {
            "recepient_name": name,
            "recepient_phone": phone,
            "recepient_email": email,
            "recepient_notes": ""
        },
        "delivery_details": {
          "pick_up_date": pickupdate,
          "collect_payment": {
            "status": false,
            "pay_method": 0,
            "amount": amountTotal
          },
                              "return": true,
     "note": " Sample note",
      "note_status": true,
      "request_type": "quote"
    }
    },
    "request_token_id": requestToken
    },
    changeOrigin: true,
    type: 'POST',
    url:ajaxurl,
    success: function(response){
    var responseData = JSON.parse(''+response+'');
    
    if(responseData.success == false)
    {
        $("html, body").animate({ scrollTop: 0 }, "slow");
        $('.sendy-errors').html('An error occured. Please refresh the page and try again.');
    }
    else
    {
        console.log('success');
    
        location.reload();
    
        console.log(responseData.response.body);
    }
    },
    dataType: 'html',
    error: function(response){
    $("html, body").animate({ scrollTop: 0 }, "slow");
    $('.sendy-errors').html('An error occured. Please refresh the page and 
    try again.');
    }
    });
    
    
    
    
            });
        });
    });
    </script>
    

  2. 我有一个 ID 为 sendy_location 的文本输入字段,它使用 Google 的 Places API 来自动完成位置。在输入时,获取纬度和经度并将它们传递给 API。这是处理请求的代码。

    function foo(){
    if ( empty( $_POST['data']['to']["to_lat"] ) || empty( $_POST['data'] 
    ['to']["to_long"] ) ) 
    {
    wp_die( 'You have to select from the list suggested for you' );
    }
    
       $post_data = wp_unslash( array( 'data' => $_POST['data'] ) );
       $post_data['command'] = wp_unslash( $_POST['command'] );
       $post_data['security'] = wp_unslash( $_POST['security'] );
       $post_data['request_token_id'] = wp_unslash( $_POST['request_token_id'] 
       );
    
      // var_dump(json_encode( $post_data ));exit;
    
      $api_url = 'https://apitest.sendyit.com/v1/';
    
      $response = wp_remote_post( $api_url, array(
      'headers' => array(
    'Content-Type' => 'application/json',
    ),
    'body'    => json_encode( $post_data ),
     ) );
    
     if ( is_wp_error( $response ) ) 
     {
     // var_dump(wp_send_json( $response->get_error_message() ));exit;
     echo json_encode(array( 'success' => false, 'response' => $response- 
     >get_eror_message() ));
     exit;
     }
     else 
     {
     $data = json_decode($response["body"]);
     $shippingCost = $data->data->amount;
     session_start();
     $_SESSION['shippingCost'] = $shippingCost;
    
     // var_dump($shippingCost);exit;
    
     echo json_encode(array( 'success' => true, 'response' => $response ));
    
    }
    wp_die();
     }
    
  3. Here is where I lose everything.I want to pass the shipping cost I stored in the above code that whenever a location is selected the shipping is called by the API and displayed in the checkout page.See the code

    //make api call to update Shipping cost
    
    function update_shipping_cost() 
    {
    if ( empty( $_POST['sendy_location']) ) 
    {
        wp_die( 'You have to select from the location dropdown' );
    }
    
    $shipping_location = $_POST['sendy_location'];
    $cart_total = str_replace(",","",$_POST['cart_total']);
    $cart_total = floatval($cart_total);
    
    
    if (empty($shipping_location) ) 
    {
        echo json_encode(array( 'success' => false, 'response' => $response->get_error_message() ));
        exit;
    }
    else 
    {
        //this is where I want to call the shipping cost. currently it's displaying zero
        {
            session_start();
            $_SESSION['shippingCost'] = $shippingCost;
            echo json_encode(array( 'success' => true, 'response' => $response ));
    
    
    }
    
    wp_die();
    }
    
    /* end */
    
  4. 此函数获取 API 返回的运费,然后我将其传递给函数

    /* shipping cost from sendy */
    
    function woo_sendy_shipping_cost() 
    {
    @session_start();
    $shippingCost = $_SESSION['shippingCost'];
    WC()->cart->add_fee('Shipping ', $shippingCost);
    }
    

有人请帮助我如何在上述功能中调用运输以使其正常工作。?提前致谢。

标签: phpjqueryajaxwordpresswoocommerce

解决方案


推荐阅读