PHP code example of lucasbrito-wdt / correios
1. Go to this page and download the library: Download lucasbrito-wdt/correios library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
lucasbrito-wdt / correios example snippets
use Correios\Facades\Correios;
use Correios\DTOs\Preco\CotacaoPrecoRequestDTO;
// CEP
$endereco = Correios::cep()->consultar('58015-430');
echo $endereco->logradouro;
// Cotação de frete
$cotacao = Correios::preco()->cotar(
CotacaoPrecoRequestDTO::fromArray([
'coProduto' => '03220', // SEDEX
'cepOrigem' => '58015430',
'cepDestino' => '01001000',
'psObjeto' => 1500, // gramas
'comprimento'=> 30,
'largura' => 20,
'altura' => 10,
])
);
echo "Frete: R$ {$cotacao->pcFinal}";
// Prazo
$prazo = Correios::prazo()->calcular('03220', '58015430', '01001000');
echo "Prazo: {$prazo->prazoEntrega} dias úteis";
// Rastreio
$objeto = Correios::rastro()->rastrear('BR123456789BR');
echo $objeto->ultimoEvento()->descricao;
echo $objeto->foiEntregue() ? 'Entregue!' : 'Em trânsito';
use Correios\Services\PrecoService;
class CalcularFreteAction
{
public function __construct(
private readonly PrecoService $precoService,
) {}
public function __invoke(CotacaoPrecoRequest $request): CotacaoPrecoResponseDTO
{
$dto = CotacaoPrecoRequestDTO::fromArray($request->validated());
return $this->precoService->cotar($dto);
}
}
$resultados = Correios::preco()->cotarLote([
CotacaoPrecoRequestDTO::fromArray([...]),
CotacaoPrecoRequestDTO::fromArray([...]),
// ...
]);
use Correios\DTOs\PrePostagem\PrePostagemRequestDTO;
$pre = Correios::prePostagem()->criar(
PrePostagemRequestDTO::fromArray([
'codigoServico' => '03220',
'pesoGramas' => 1500,
'dimensoes' => ['altura' => 10, 'largura' => 20, 'comprimento' => 30],
'remetente' => [...],
'destinatario' => [...],
'itens' => [
['descricao' => 'Camiseta personalizada', 'quantidade' => 1, 'valor' => 89.90],
],
'numeroNotaFiscal' => '12345',
'chaveNotaFiscal' => '35200114200166000187550010000000071123456789',
])
);
echo "Código: {$pre->codigoObjeto}";
// Gerar PDF da etiqueta
$rotulo = Correios::prePostagem()->gerarRotulo($pre->id);
namespace App\Correios;
use Correios\Services\AbstractCorreiosService;
class MeuServiceCustom extends AbstractCorreiosService
{
protected function basePath(): string
{
return '/meu-endpoint/v1';
}
public function minhaOperacao(array $payload): array
{
return $this->post('/operacao', $payload);
}
}
$this->app->singleton(MeuServiceCustom::class, fn ($app) => new MeuServiceCustom(
$app->make(\Correios\Http\Client\CorreiosHttpClient::class)
));
bash
php artisan vendor:publish --tag=correios-config