Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/253.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php WooCommerce结帐-更新运输成本_Php_Jquery_Ajax_Wordpress_Woocommerce - Fatal编程技术网

Php WooCommerce结帐-更新运输成本

Php WooCommerce结帐-更新运输成本,php,jquery,ajax,wordpress,woocommerce,Php,Jquery,Ajax,Wordpress,Woocommerce,我正在使用Sendy API根据从Google location API管理的下拉列表中选择的位置来计算结帐页面中的运费。 除了我的运费没有计算在内,其他一切都很好。我不确定如何通过配送,因为每次选择位置时我都会得到0值。在谷歌搜索之后,我想出了这个代码分解。有人,请帮助我如何做到这一点 AJAX从API中提取运输成本 function sendy_api_script() { ?> <?php if(is_checkout()){ ?> <script type="t

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

  • 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>
    
  • 这里是我失去一切的地方。我想传递我在上面代码中存储的运费,每当选择一个位置时,API就会调用运费并显示在签出页面中。请参阅代码

    //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 */
    
  • 此函数获取API返回的运费,然后将其传递给函数

    /* shipping cost from sendy */
    
    function woo_sendy_shipping_cost() 
    {
    @session_start();
    $shippingCost = $_SESSION['shippingCost'];
    WC()->cart->add_fee('Shipping ', $shippingCost);
    }
    
  • 有人请帮助我如何在上述功能中调用shipping以使其工作。?提前谢谢

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