DEV Community

Cover image for Calcular Frete dos Correios usando PHP 8.1
Jilcimar Fernandes
Jilcimar Fernandes

Posted on

10 1

Calcular Frete dos Correios usando PHP 8.1

Este é um exemplo de classe em PHP para que você consiga simular os valores de frete. Após precisar realizar o cálculo de frete em um Checkout de Pagamento, vi que na internet os códigos que tinham para utilizar o serviço dos Correios eram antigos e a maioria não funcionava bem.

<?php

//namespace ......;

class FreightCalculate
{
    public function __construct(
        private string $code, //41106 - PAC , 40010 - SEDEX
        private string $originZipCode,
        private string $destinationZipCode,
        private int $weight,
        private int $length,
        private int $height,
        private int $width, //Min 10
        private array $response = [],
    ) {
        $url = 'http://ws.correios.com.br/calculador/CalcPrecoPrazo.aspx';

        if ($length < 16) {
            $this->length = 16;
        }

         $params = [
            'nCdEmpresa' => '',
            'sDsSenha' => '',
            'sCepOrigem' => $this->originZipCode,
            'sCepDestino' => $this->destinationZipCode,
            'nVlPeso' => $this->weight, //kg
            'nCdFormato' => '1',  //1 para caixa / pacote e 2 para rolo/prisma.
            'nVlComprimento' => $this->length,
            'nVlAltura' => $this->height,
            'nVlLargura' => $this->width,
            'nVlDiametro' => '0',
            'sCdMaoPropria' => 'n',
            'nVlValorDeclarado' => '0',
            'sCdAvisoRecebimento' => 'n',
            'StrRetorno' => 'xml',
            'nCdServico' =>  $this->code,
        ];

        $params = http_build_query($params);

        $curl = curl_init($url . '?' . $params);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $data = curl_exec($curl);
        $data = simplexml_load_string($data);

        foreach ($data->cServico as $service) {
            if ($service->Erro == 0) {
                $this->response['code'] = $service->Codigo ;
                $this->response['value'] = $service->Valor;
                $this->response['deadline'] = $service->PrazoEntrega ;
            }
        }
    }

    public function getValue(): float
    {
        return float $this->response['value'];
    }

    public function getDeadline(): int
    {
        return (int) $this->response['deadline'];
    }

    public function getCode(): int
    {
        return (int) $this->response['deadline'];
    }
}
Enter fullscreen mode Exit fullscreen mode

Esta é a classe que você pode imnportar no seu projeto.

Como usar?

Para usar basta instanciar a classe e chamar os métodos de acordo com a sua necessidade.

$frete = new FreightCalculate('41106','59945000', '59158400', 1, 5, 5, 10);

...

 $frete->getValue();

...

$frete->getDeadline();
Enter fullscreen mode Exit fullscreen mode

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry 🕒

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (2)

Collapse
 
fernandouicode profile image
Fernando-ui-code

Olá. Tudo bem? Você presta suporte para inclusao dessa função em um sistema? Gostaria de incluir essa função no meu sistema, mas sou muito iniciante

Collapse
 
jilcimar profile image
Jilcimar Fernandes

Olá @fernandouicode , fala comigo pelo telegram que eu posso te ajudar @jilcimar ou me manda o seu contato no e-mail jilcimar.fernandes0267@gmail.com

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay