• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

chico-rei / correios-php / 18169498141

01 Oct 2025 04:54PM UTC coverage: 5.322% (-0.005%) from 5.327%
18169498141

push

github

Matheus Marques
Handle Correios error message

0 of 2 new or added lines in 1 file covered. (0.0%)

57 of 1071 relevant lines covered (5.32%)

0.06 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/src/Client.php
1
<?php
2

3
namespace ChicoRei\Packages\Correios;
4

5
use ChicoRei\Packages\Correios\Exception\CorreiosAPIException;
6
use ChicoRei\Packages\Correios\Exception\CorreiosClientException;
7
use ChicoRei\Packages\Correios\Model\Token;
8
use ChicoRei\Packages\Correios\Request\CorreiosRequest;
9
use GuzzleHttp\Client as Guzzle;
10
use GuzzleHttp\Exception\ClientException;
11
use GuzzleHttp\Exception\GuzzleException;
12
use GuzzleHttp\Exception\RequestException;
13
use GuzzleHttp\Exception\ServerException;
14
use Psr\Http\Message\ResponseInterface;
15
use Psr\SimpleCache\CacheInterface;
16
use Psr\SimpleCache\InvalidArgumentException;
17

18
class Client
19
{
20
    /**
21
     * Correios Web Service API Url
22
     */
23
    const API_URL = 'https://api.correios.com.br';
24

25
    /**
26
     * Correios Web Service Sandbox API Url
27
     */
28
    const API_SANDBOX_URL = 'https://apihom.correios.com.br';
29

30
    private Account $authorization;
31

32
    private CacheInterface $cacheDriver;
33

34
    private Guzzle $guzzle;
35

36
    private ?ResponseInterface $lastResponse;
37

38
    private ?string $tokenCacheKey = null;
39

40
    /**
41
     * @param Account $authorization
42
     * @param array $guzzleOptions
43
     * @param CacheInterface $cacheDriver
44
     */
45
    public function __construct(Account $authorization, CacheInterface $cacheDriver, array $guzzleOptions)
46
    {
47
        $this->authorization = $authorization;
×
48
        $this->cacheDriver = $cacheDriver;
×
49
        $this->tokenCacheKey = 'cr_correios_tk_'.implode('_', [
×
50
                $this->authorization->getUsername() ?? '',
×
51
                $this->authorization->getContract() ?? '',
×
52
                $this->authorization->getPostcard() ?? '',
×
53
            ]);
×
54

55
        $this->guzzle = new Guzzle(array_merge($guzzleOptions, [
×
56
            'base_uri' => $this->authorization->isSandbox() ? self::API_SANDBOX_URL : self::API_URL,
×
57
            'http_errors' => true,
×
58
            'headers' => [
×
59
                'Content-Type' => 'application/json',
×
60
                'Accept' => 'application/json',
×
61
            ],
×
62
        ]));
×
63
    }
64

65
    /**
66
     * @param CorreiosRequest $request
67
     * @return array
68
     * @throws CorreiosClientException
69
     * @throws CorreiosAPIException
70
     */
71
    public function sendRequest(CorreiosRequest $request)
72
    {
73
        try {
74
            $payload = $request->getPayload();
×
75
            $query = $request->getQuery();
×
76

77
            $this->lastResponse = $this->guzzle->request(
×
78
                $request->getMethod(),
×
79
                $request->getPath(),
×
80
                [
×
81
                    'query' => Util::cleanArray($query),
×
82
                    'headers' => [
×
83
                        'Authorization' => 'Bearer '. $this->getToken()->getToken()
×
84
                    ],
×
85
                    'json' => Util::cleanArray($payload)
×
86
                ]
×
87
            );
×
88

89
            return $this->handleResponse($this->lastResponse);
×
90
        } catch (ServerException | ClientException $exception) {
×
91
            $this->lastResponse = $exception->getResponse();
×
NEW
92
            $response = $this->handleResponse($this->lastResponse);
×
93

94
            throw new CorreiosAPIException(
×
NEW
95
                $response['msgs'][0] ?? $exception->getMessage(),
×
96
                $exception->getCode(),
×
97
                $exception->getRequest(),
×
98
                $exception->getResponse()
×
99
            );
×
100
        } catch (GuzzleException | RequestException | InvalidArgumentException $exception) {
×
101
            throw new CorreiosClientException($exception->getMessage(), $exception->getCode(), $exception);
×
102
        }
103
    }
104

105
    /**
106
     * Decode the Response
107
     *
108
     * @param ResponseInterface $response
109
     * @return array|null
110
     */
111
    public function handleResponse(ResponseInterface $response): ?array
112
    {
113
        return json_decode($response->getBody()->getContents(), true);
×
114
    }
115

116
    /**
117
     * Get the last response from API
118
     */
119
    public function getLastResponse(): ?ResponseInterface
120
    {
121
        return $this->lastResponse;
×
122
    }
123

124
    /**
125
     * Get the token
126
     *
127
     * @throws InvalidArgumentException
128
     * @throws GuzzleException
129
     */
130
    public function getToken(): Token
131
    {
132
        if ($this->cacheDriver->has($this->tokenCacheKey)) {
×
133
            return $this->cacheDriver->get($this->tokenCacheKey);
×
134
        }
135

136
        if ($this->authorization->getPostcard()) {
×
137
            $tokenUrl = '/token/v1/autentica/cartaopostagem';
×
138
            $payload = ['numero' => $this->authorization->getPostcard()];
×
139
        } elseif ($this->authorization->getContract()) {
×
140
            $tokenUrl = '/token/v1/autentica/contrato';
×
141
            $payload = ['numero' => $this->authorization->getContract()];
×
142
        } else {
143
            $tokenUrl = '/token/v1/autentica';
×
144
            $payload = [];
×
145
        }
146

147
        if ($this->authorization->getDr()) {
×
148
            $payload['dr'] = $this->authorization->getDr();
×
149
        }
150

151
        $response = $this->guzzle->request(
×
152
            'POST',
×
153
            $tokenUrl,
×
154
            [
×
155
                'headers' => [
×
156
                    'Authorization' => 'Basic '.base64_encode(
×
157
                        $this->authorization->getUsername().':'.$this->authorization->getPassword()
×
158
                    ),
×
159
                ],
×
160
                'json' => $payload
×
161
            ]
×
162
        );
×
163

164
        $token = Token::create($this->handleResponse($response));
×
165

166
        $this->cacheDriver->set(
×
167
            $this->tokenCacheKey,
×
168
            $token,
×
169
            $token->getExpiraEm()->clone()->subMinutes(10)->timestamp
×
170
        );
×
171

172
        return $token;
×
173
    }
174
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc