php - WooCommerce 结帐 - 更新运费
问题描述
我正在使用 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>
我有一个 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(); }
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 */
此函数获取 API 返回的运费,然后我将其传递给函数
/* shipping cost from sendy */ function woo_sendy_shipping_cost() { @session_start(); $shippingCost = $_SESSION['shippingCost']; WC()->cart->add_fee('Shipping ', $shippingCost); }
有人请帮助我如何在上述功能中调用运输以使其正常工作。?提前致谢。
解决方案
推荐阅读
- eclipse - 如何通过命令行重新启动或退出我的 Eclipse
- lua - 为什么使用 scipy 从 Lua 火炬和 pytorch 加载 .mat 文件后矩阵之间存在差异?
- python - Dask:在列上删除 NA?
- php - Symfony 中的注解机制——它是如何工作的?
- android-studio - Kotlin REPL:由于可能的重新分配,禁止捕获的成员值初始化
- c# - 通过 OLEDB 连接到 MySQL
- php - 在使用 PHP 中的 IF 语句更新 php 中的表格内容之前如何检查?
- c# - 为什么尝试为 MySql 创建 using 指令会产生“缺少 using 指令”错误?
- r - 在 r 中绘制没有谷歌地图 API 的城市地图
- python - 在 Python 中循环无限嵌套的字典