Closed sebosfato closed 9 months ago
acredito que pode ser pela interação com o plugin da dhl que eu to ajudando a adaptar pra woocommerce
segue o código caso possa ajudar a sacar qual o problema… o plugin ainda não ta muito perfeito mas ja funciona só que quando o debug ta ligado ele mostra 3 ou 4 vezes o tempo de entrega… mas com debug desligado roda ok… mas me parece que desligando ele não gera aquela linha a mais no plugin do correio por algum motivo acho que ta dando algum conflito…
`
<?php
if ( ! defined( 'ABSPATH' ) ) { exit; }
const did=0;
if (!class_exists('WC_Shipping_Method')) { require_once ABSPATH . 'wp-content/plugins/woocommerce/includes/abstracts/abstract-wc-shipping-method.php'; }
if (!class_exists('DHL_Rating_Method')) {
class DHL_Rating_Method extends WC_Shipping_Method { // Your class definition here /* function dhlexpress_is_woocommerce_active() {
$wc_active = (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins'))));
if ($wc_active) {
return $wc_active;
} else {
if (is_multisite()) {
// WordPress multisite detected
$wc_active = (array_key_exists('woocommerce/woocommerce.php', apply_filters('active_plugins', get_site_option('active_sitewide_plugins'))));
}
}
return $wc_active;
}
*/ public function construct($instance_id = 0) { $this -> id = $instance_id > 0 ? $instance_id . '_dhl_shipping' : 'dhl_shipping'; $this -> method_title = __('DHL Express Shipping Rates' , 'dhl_shippping'); $this -> method_description = esc_html('Display live shipping rates at checkout' , 'dhl_shippping'); $this->title =__('DHL Shipping','dhl-shipping'); // $this->method_type = 'shipping';
$this -> apikey = "";
$this -> enabled = "yes";
$this->instance_id = absint($instance_id);
$this->supports = array(
'shipping-zones',
'instance-settings',
'instance-settings-modal',
);
add_action('woocommerce_update_options_shipping_' . $this->id, array($this, 'process_admin_options'));
$this -> init();
}
public function init() {
$this -> init_settings();
$this -> init_form_fields();
$settings = get_option('woocommerce_' . $this->instance_id . '_dhl_shipping_' . $this->instance_id . '_settings', array());
$this->apikey = isset($settings['apikey']) ? $settings['apikey'] : ''; // Use the saved API key
$this->enabled = isset($settings['enabled']) ? $settings['enabled'] : 'yes';
// $this->apikey = get_option('apikey'); // Replace 'dhlexpress_apikey' with the actual option name
// $this->enabled = get_option('enabled', 'yes'); // Replace 'dhlexpress_enabled' with the actual option name
add_action('woocommerce_update_options_shipping_' . $this->id . '_' . $this->instance_id, array($this, 'process_admin_options'));
$this->add_dhl_delivery_forecast_action();
//add_filter('woocommerce_shipping_' . $this->id, array($this, 'process_admin_options'));
// add_filter('woocommerce_after_cart_item_quantity_update', array($this, 'trigger_calculate_shipping'), 10, 3);
// add_action('woocommerce_update_options_shipping_' . $this -> id, array($this, 'process_admin_options'));
}
public function process_admin_options()
{ $result = parent::process_admin_options(); return $result; }
public function trigger_calculate_shipping($cart_item_key, $quantity, $old_quantity) {
// Your logic to trigger the calculate_shipping method
$this->calculate_shipping();
}
public function init_form_fields() {
$this->instance_form_fields = array( // $this -> form_fields = array(
'apikey' => array(
'title' => __('API Key', 'dhl_shippping'),
'type' => 'text',
'description' => __('This is available under your DHL App account (Settings > API).', 'woocommerce')
),
'enabled' => array(
'type' => 'checkbox',
'label' => __('Enable rates at checkout', 'dhl_shippping'),
'default' => 'yes'
)
);
$this->form_fields = $this->get_instance_form_fields();
}
public function calculate_shipping($package = array()) {
/* if ($this -> enabled == 'no') {
return;
}
*/
$this->init_settings();
// error_log('API Key for request: ' . $this->apikey); // Add this line for debugging
try {
$address = $package['destination']['address'];
$address_2 = $package['destination']['address_2'];
$city = $package['destination']['city'];
$state = $package['destination']['state'];
$postcode = $package['destination']['postcode'];
$countrycode = $package['destination']['country'];
$counter = 0;
$itemList = '';
try {
$dimension_unit = get_option('woocommerce_dimension_unit');
foreach ($package['contents'] as $package_item) {
$product = $package_item[ 'data' ];
$productName = str_replace('"', '\\"', $product->get_title());;
$productPrice = $product->get_price();
$quantity = $package_item[ 'quantity' ];
if (($quantity > 0) && $product -> needs_shipping()) {
$weight = $product -> get_weight();
$height = 0;
$length = 0;
$width = 0;
if ($product -> has_dimensions()) {
$height = $product -> get_height();
$length = $product -> get_length();
$width = $product -> get_width();
}
$itemList .= '{
"name": "' . $productName . '",
"sku": null,
"quantity": ' . $quantity . ',
"grams": ' . $weight . ',
"height": ' . $height . ',
"width": ' . $width . ',
"length": ' . $length . ',
"price": ' . $productPrice . ',
"dimensions_unit": "' . $dimension_unit . '",
"vendor": null,
"requires_shipping": true,
"taxable": true,
"fulfillment_service": "manual"
},';
}
if ($counter == count($package['contents']) - 1) {
$itemList = rtrim($itemList, ',');
}
$counter++;
}
}
catch (Exception $e) {
// backwards compatibility - get the rates using the old way
$packageValue = $package['contents_cost'];
$packageWeight = 0;
foreach ($package['contents'] as $package_item) {
$product = $package_item['data'];
$quantity = $package_item['quantity'];
if (($quantity > 0) && $product -> needs_shipping()) {
$weight = $product -> get_weight();
$packageWeight += $weight * $quantity;
}
}
$itemList = '{
"name": "Total Items",
"sku": null,
"quantity": 1,
"grams": ' . $packageWeight . ' ,
"price": ' . $packageValue . ',
"vendor": null,
"requires_shipping": true,
"taxable": true,
"fulfillment_service": "manual"
}';
// Add DHL Express Commerce Rates Exception Logging
$wc_logger = new WC_Logger();
$wc_logger->add('DHL-Express-Commerce', $e);
}
// error_log($this -> apikey);
$url = 'https://api.starshipit.com/api/rates/shopify?apiKey=' . $this -> apikey . '&integration_type=woocommerce&version=3.0&format=json&source=DHL';
$post_data = '{
"rate": {
"destination":{
"country": "' . $countrycode . '",
"postal_code": "' . $postcode . '",
"province": "' . $state . '",
"city": "' . $city . '",
"name": null,
"address1": "' . $address . '",
"address2": "' . $address_2 . '",
"address3": null,
"phone": null,
"fax": null,
"address_type": null,
"company_name": null
},
"items":[' .
"$itemList" .
']
}
}';
$response = wp_remote_post($url, array(
'headers' => array('Content-Type' => 'application/json; charset=utf-8'),
'method' => 'POST',
'body' => $post_data,
'timeout' => 75,
'sslverify' => 0
)
);
$response_code = wp_remote_retrieve_response_code($response);
$response_body = wp_remote_retrieve_body($response);
$json_obj = json_decode($response_body);
$rates_obj = $json_obj -> {'rates'} ;
// echo($response_body);
$data = json_decode($response_body, true);
// echo $response_body;
$woocommerce_currency = get_woocommerce_currency(); if ($data && isset($data['rates'][0]['service_name'])) {
if (is_countable($rates_obj) && count($rates_obj) > 0) {
foreach($rates_obj as $rate) {
if (is_object($rate)) {
$serviceInfo = $rate->service_name;
//$serviceInfo = $data['rates'][0]['service_name'];
// Extract the service name
$serviceName = $serviceInfo;
$serviceParts = explode(' - ', $serviceName);
if (count($serviceParts) === 2) {
$serviceName = $serviceParts[0];
$deliveryTime = $serviceParts[1];
$serviceName = str_replace('NONDOC', '', $serviceName);
// echo "Service Name: $serviceName<br>";
// echo "Delivery Time: $deliveryTime<br>";
$meta_dhl_delivery = array(
'_delivery_dhl_forecast' => "Delivery Time: $deliveryTime",
);
$totalCharges = $rate ->total_price / get_option('currency_update_options_' . $woocommerce_currency);
$shipping_rate = array(
'id' => $this -> id . '_' . $rate -> {'service_code'},
'label' => 'DHL '. $serviceName,
'cost' => $totalCharges,
'calc_tax' => 'per_order',
'meta_data' => $meta_dhl_delivery
);
$this -> add_rate($shipping_rate);
}
}
}
} else {
echo "No rates available.\n";
}
} else {
echo "Invalid JSON format or missing service name.\n";
// echo $response_body;
}
} catch (Exception $e) {
// Add DHL Express Commerce Rates Exception Logging
$wc_logger = new WC_Logger();
$wc_logger->add('DHL-Express-Commerce', $e);
}
}
// Add an action to display the delivery forecast after the shipping rate.
public function add_dhl_delivery_forecast_action() {
//if (!has_action('woocommerce_after_shipping_rate', array($this, 'dhl_shipping_delivery_forecast'))) {
add_action('woocommerce_after_shipping_rate', array($this, 'dhl_shipping_delivery_forecast'), 10, 2);
// }
//add_action('woocommerce_after_shipping_rate', array($this, 'dhl_shipping_delivery_forecast'), 10, 2);
// echo "i hre";
}
/**
* Adds delivery forecast after method name.
*
* @param WC_Shipping_Rate $shipping_method Shipping method data.
*/
public function dhl_shipping_delivery_forecast($method, $index) {
$dhl_meta_data = $method->get_meta_data();
//if (isset($dhl_meta_data['_delivery_dhl_forecast'])) {
$delivery_dhl_forecast = esc_html($dhl_meta_data['_delivery_dhl_forecast']);
echo '<p><small>' . $delivery_dhl_forecast . '</small></p>';
// }
}
}
}
`
Consegui resolver era a parte de baixo do meu plugin interferindo no seu… adicionando esse isset ele parou de adicionar linhas… if (isset($ups_meta_data['_delivery_ups_forecast'])) { $delivery_ups_forecast = esc_html($ups_meta_data['_delivery_ups_forecast']); echo '
' . $delivery_ups_forecast . '
'; }Olá, poderia me ajudar com algo relacionado ao plugin? Tive um problema com atualização, mas não tenho muito conhecimento em wordpress.
Por padrão este plugin não adiciona CSS ou HTML no carrinho, essa linha não é causada por este plugin. Fechando já que não é um neste plugin.
Estou tentando aqui sumir com uma linha que aparece antes da estimativa de entrega… olhando no inspect parece um paragrafo com padding-bottom 1em
tentei tirar o p mas ai o não funciona e o texto fica grande e não shaded..
é apenas uma questão estética pois o tempo de entrega fica meio longe do valor diferente de outras cotações dos outros entregadores…
tentei descobrir pq a linha esta sendo adicionada mas não consegui..
se tiverem alguma sugestão agradeço muito !