Hello, good morning, everyone!
Friends, I'm trying to create a plugin for a new delivery method for WooCommerce, in case I'm using the TNT webservice.
This is the first time I try to create a plugin, so I'm following the instructions in this link: link
The difficulty I am facing is that it is calculating as soon as I add a product to the cart, the right one would appear only after the customer calculates the freight, as it depends on the zip code.
Another problem I am having, maybe due to the first one, is that I can not get the zip code entered in the freight calculation, in the array $parameters
the key cepDestino
should receive the value of the zip informed and then calculate the freight .
Thanks in advance for all the help!
Follow the code.
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
function np_shipping_method_init() {
if ( ! class_exists( 'NP_TNT_Shipping_Method' ) ) {
class NP_TNT_Shipping_Method extends WC_Shipping_Method {
/**
* Constructor for your shipping class
*
* @access public
* @return void
*/
public function __construct() {
$this->id = 'np_tnt_envio'; // Id for your shipping method. Should be uunique.
$this->method_title = __( 'Entrega pela TNT Mercúrio' ); // Title shown in admin
$this->method_description = __( 'Envio pela TNT Mercúrio' ); // Description shown in admin
$this->enabled = $this->get_option( 'enabled' );
$this->title = $this->get_option( 'title' );
$this->ceporigem = $this->get_option( 'ceporigem' );
$this->login = $this->get_option( 'login' );
$this->nridentrem = $this->get_option( 'nridentificacaorem' );
$this->insestrem = $this->get_option( 'inscestadualrem' );
$this->init();
}
/**
* Init your settings
*
* @access public
* @return void
*/
function init() {
// Load the settings API
$this->init_form_fields(); // This is part of the settings API. Override the method to add your own settings
$this->init_settings(); // This is part of the settings API. Loads settings you previously init.
// Save settings in admin if you have any defined
//add_action('woocommerce_update_options_shipping_methods', array(&$this, 'process_admin_options'));
add_action('woocommerce_update_options_shipping_'.$this->id,array( $this, 'process_admin_options'));
}
/**
* Define settings field for this shipping
* @return void
*/
function init_form_fields() {
$this->form_fields = array(
'enabled' => array(
'title' => __( 'Ativar' ),
'type' => 'checkbox',
'description' => __( 'Ativar este método.' )
),
'title' => array(
'title' => __( 'Título' ),
'type' => 'text',
'description' => __( 'Título do método de entrega' ),
'default' => __( 'Envio TNT' )
),
'ceporigem' => array(
'title' => __( 'Cep de origem' ),
'type' => 'text',
'description' => __( 'Title to be display on site' )
),
'login' => array(
'title' => __( 'Login' ),
'type' => 'text',
'description' => __( 'Title to be display on site' )
),
'nridentificacaorem' => array(
'title' => __( 'Número de identificação do Remetente' ),
'type' => 'text',
'description' => __( 'Title to be display on site' )
),
'inscestadualrem' => array(
'title' => __( 'Inscrição Estadual do Remetente' ),
'type' => 'text',
'description' => __( 'Title to be display on site' )
),
);
}
/**
* sanitizar cep
*
*/
/**
* calculate_shipping function.
*
* @access public
* @param mixed $package
* @return void
*/
public function calculate_shipping( $package ) {
ini_set("soap.wsdl_cache_enabled", "0");
$dimensoes = 0;
foreach ( $package['contents'] as $item_id => $values ) {
$_product = $values['data'];
$dimensoes = $dimensoes + (($_product->length * $_product->width * $_product->height * $values['quantity']));
}
$pesoreal = (($dimensoes * 250)/1000000);
$valortotal_carrinho = WC()->cart->get_cart_contents_total();
$parameters = array('calculaFrete' => array('in0' => array(
'cdDivisaoCliente' => 1,
'cepDestino' => '04180112',//aqui deve vir o cep digitado pelo cliente
'cepOrigem' => $this->ceporigem,
'login' => $this->login,
'nrIdentifClienteDest' => '00000000000',
'nrIdentifClienteRem' => $this->nridentrem,
'nrInscricaoEstadualDestinatario' => '0000000000000',
'nrInscricaoEstadualRemetente' => $this->insestrem,
'psReal' => $pesoreal,
'senha' => '',
'tpFrete' => 'C',
'tpPessoaDestinatario' => 'F',
'tpPessoaRemetente' => 'J',
'tpServico' => 'RNC',
'tpSituacaoTributariaDestinatario' => 'CO',
'tpSituacaoTributariaRemetente' => 'CO',
'vlMercadoria' => $valortotal_carrinho,
)));
$reponse = null;
try {
$soap = new SoapClient('http://ws.tntbrasil.com.br/servicos/CalculoFrete?wsdl');
$call = $soap->__soapCall('calculaFrete', $parameters);
$out = (array) $call->out;
$errors = (array) $out['errorList'];
$response = array(
'errorList' => array(),
'nmDestinatario' => $out['nmDestinatario'],
'nmMunicipioDestino' => $out['nmMunicipioDestino'],
'nmMunicipioOrigem' => $out['nmMunicipioOrigem'],
'nmRemetente' => $out['nmRemetente'],
'nrDDDFilialDestino' => $out['nrDDDFilialDestino'],
'nrDDDFilialOrigem' => $out['nrDDDFilialOrigem'],
'nrTelefoneFilialDestino' => $out['nrTelefoneFilialDestino'],
'nrTelefoneFilialOrigem' => $out['nrTelefoneFilialOrigem'],
'prazoEntrega' => $out['prazoEntrega'],
'vlDesconto' => $out['vlDesconto'],
'vlICMSubstituicaoTributaria' => $out['vlICMSubstituicaoTributaria'],
'vlImposto' => $out['vlImposto'],
'vlTotalCtrc' => $out['vlTotalCtrc'],
'vlTotalFrete' => $out['vlTotalFrete'],
'vlTotalServico' => $out['vlTotalServico'],
);
$custo = $out['vlTotalFrete'];
} catch ( Exception $e ){
echo'Não conseguimos nos conectar à TNT, por favor tente novamente mais tarde.';
}
$rate = array(
'id' => $this->id,
'label' => $this->title,
'cost' => $custo,
'calc_tax' => 'per_item'
);
// Register the rate
$this->add_rate( $rate );
}
}// classe
}// if verifica se classe existe
}// função
add_action( 'woocommerce_shipping_init', 'np_shipping_method_init' );
function add_np_shipping_method( $methods ) {
$methods['np_tnt_envio'] = 'NP_TNT_Shipping_Method';
return $methods;
}
add_filter( 'woocommerce_shipping_methods', 'add_np_shipping_method' );
}// if verifica se woocommerce esta instalado