leandroferreirama /
api-itau
| 1 | <?php |
||
| 2 | |||
| 3 | namespace Itau\API; |
||
| 4 | |||
| 5 | use Exception; |
||
| 6 | use Itau\API\Exception\ItauException; |
||
| 7 | |||
| 8 | /** |
||
| 9 | * Class ItauCertificate |
||
| 10 | * |
||
| 11 | * @package Itau\API |
||
| 12 | */ |
||
| 13 | class ItauCertificate |
||
| 14 | { |
||
| 15 | private string $endpoint = 'https://sts.itau.com.br/seguranca/v1/certificado/solicitacao'; |
||
| 16 | |||
| 17 | public function criarCertificado(string $token, string $certificadoCSR) |
||
| 18 | { |
||
| 19 | return $this->executeRequest($token, $certificadoCSR); |
||
| 20 | } |
||
| 21 | |||
| 22 | public function renovarCertificado(Itau $credentials, string $certificadoCSR) |
||
| 23 | { |
||
| 24 | if (!$credentials->getAuthorizationToken()) { |
||
| 25 | new Request($credentials); |
||
| 26 | } |
||
| 27 | $token = $credentials->getAuthorizationToken(); |
||
| 28 | return $this->executeRequest($token, $certificadoCSR); |
||
| 29 | } |
||
| 30 | |||
| 31 | private function executeRequest(string $token, string $certificadoCSR) |
||
| 32 | { |
||
| 33 | $headers = [ |
||
| 34 | 'Content-Type: text/plain', |
||
| 35 | 'Authorization: Bearer ' . $token |
||
| 36 | ]; |
||
| 37 | |||
| 38 | $curl = curl_init(); |
||
| 39 | |||
| 40 | curl_setopt_array($curl, [ |
||
| 41 | CURLOPT_URL => $this->endpoint, |
||
| 42 | CURLOPT_HTTPHEADER => $headers, |
||
| 43 | CURLOPT_RETURNTRANSFER => true, |
||
| 44 | CURLOPT_CUSTOMREQUEST => 'POST', |
||
| 45 | CURLOPT_POSTFIELDS => $certificadoCSR, |
||
| 46 | ]); |
||
| 47 | |||
| 48 | try { |
||
| 49 | $response = curl_exec($curl); |
||
| 50 | } catch (Exception $e) { |
||
| 51 | curl_close($curl); |
||
| 52 | throw new ItauException($e->getMessage(), 100); |
||
| 53 | } |
||
| 54 | |||
| 55 | if ($response === false) { |
||
| 56 | $error = curl_error($curl); |
||
| 57 | curl_close($curl); |
||
| 58 | throw new ItauException('CURL Error: ' . $error, 100); |
||
| 59 | } |
||
| 60 | |||
| 61 | $statusCode = (int) curl_getinfo($curl, CURLINFO_HTTP_CODE); |
||
| 62 | curl_close($curl); |
||
| 63 | |||
| 64 | // Verifica status HTTP |
||
| 65 | if ($statusCode >= 400) { |
||
| 66 | $obj = json_decode($response); |
||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 67 | $acao = $obj->acao ?? ''; |
||
| 68 | $mensagem = $obj->mensagem ?? 'Erro desconhecido'; |
||
| 69 | $acaoText = $acao ? "- {$acao}" : ''; |
||
| 70 | throw new ItauException("HTTP Error: $statusCode - $mensagem {$acaoText}", $statusCode); |
||
| 71 | } |
||
| 72 | |||
| 73 | // Lógica para 204 |
||
| 74 | if ($statusCode === 204) { |
||
| 75 | return [ |
||
| 76 | 'status_code' => 204 |
||
| 77 | ]; |
||
| 78 | } |
||
| 79 | |||
| 80 | // Verifica resposta vazia |
||
| 81 | if (empty($response)) { |
||
| 82 | throw new ItauException('Empty response received from server.', $statusCode); |
||
| 83 | } |
||
| 84 | |||
| 85 | return $response; |
||
| 86 | } |
||
| 87 | } |
||
| 88 |