Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- //Exemplo POST
- meuArrayPHP = [
- 'nome' = 'Maicon',
- 'dataNascimento' = '2001.01.01',
- 'valorLimite' = 100.55,
- 'qualquerPropriedadeApi' = 'Valor'
- ]
- $options = [
- /*De acordo com a biblioteca Guzzle: Ao acionar fazer um POST request, se eu quiser enviar um JSON posso enviar da maneira abaixo:
- "An easy way to upload JSON data and set the appropriate header is using the json request option:" */
- 'json' => $meuArrayPHP
- ];
- $method = 'POST';
- $uri = 'clientes';
- $resposta = request($method,$uri,$options);
- echo var_export($resposta,true);
- //Exemplo DELETE (deletando o cliente com ID 1
- $idCliente = 1;
- $resposta = request('DELETE','clientes/'.$idCliente);
- echo var_export($resposta,true);
- //Exemplo GET (consultando cliente com ID = 2)
- $idCliente = 2;
- $resposta = request('GET','clientes/'.$idCliente);
- echo var_export($resposta,true);
- /**
- * Reimplementa a função "request()" da biblioteca Guzzle Http Client.
- * Efetua alguns tratamentos de erros, e retorna o JSON já convertido para Array PHP e/ou String
- * (caso o retorno tenha sucesso mas não seja um JSON)
- * Documentação de Request (usando a Biblioteca Guzzle Http Client):
- * http://docs.guzzlephp.org/en/stable/quickstart.html#making-a-request
- * @param string $method Método da requisição que está sendo solicitada.
- * Opções: GET, POST, DELETE, PUT, etc.
- * @param string $uri URI/Requisição que está sendo solicitada
- * Exemplo: "pedidos", "pedidos/1", "clientes", "clientes?query=...."
- * @param array $options Opções, tal como no formato exibido pela biblioteca Guzzle Http Cliente e pela API a ser consultada.
- * é um parâmetro opcional (para GET e DELETE por exemplo, não é utilizado)
- * @return mix Resposta Retorna um JSON convertido em Array (caso a resposta seja um JSON)
- * ou o conteúdo de "body" em formato string (se body não for um JSON)
- */
- function request(string $method, string $uri,array $options = [])
- {
- //Instancia a classe Http Client do Guzzle. http://docs.guzzlephp.org/en/stable/
- $client = new Client([
- 'headers' => [
- 'Content-Type' => 'application/json',
- 'Accept' => 'application/json',
- //Autorização do tipo "Basic"
- 'Authorization' => 'Basic HUKLAadlflslckssklsdajfndsjkfnsdjklcnsdajkla'
- ],
- 'base_uri' => $this->base_url,
- 'timeout' => 5, //5 segundos
- /*Necessário desabilitar o verify se não daria erro de verificação de SSL
- http://docs.guzzlephp.org/en/stable/request-options.html#verify*/
- 'verify' => false
- ]);
- try
- {
- if ($this->is_debug) {
- echo '<b> '.date('d-m-Y H:i:s').' '.$method.' '.$this->base_url . $uri.'</b><br/>';
- }
- $response = $client->request($method,$uri, $options );
- $this->qtde_requisicoes++;
- $statuscode = $response->getStatusCode();
- //200 = Retorno OK
- if ($statuscode==200)
- {
- $strBody = (string) $response->getBody();
- //Converte o JSON para Array PHP
- $_ret = json_decode($strBody,true);
- /* Se não for um JSON (deu erro na conversão), então retorno o coteúdo de "body" em formato string.
- OBS: Note que isso não significa que é um erro. Por exemplo, ao fazer um request DELETE,
- se o item foi deletado com sucesso, a resposta será simplesmente 'true' */
- if (json_last_error()!=0) //0 = Não tem erro (arquivo JSON convertido para Array corretamente)
- $_ret = $strBody;
- if ($this->is_debug) {
- echo date('d-m-Y H:i:s').' StatusCode: '.$statuscode. ' ReasonPhrase: '.$response->getReasonPhrase(). '<br />'; // OK
- echo 'Count Array: '.count($_ret).'<br />';
- }
- //Retorna em o JSON convertido para array
- return $_ret;
- } else
- {
- throw new Exception('Erro no retorno do request '.$method.' "'.$uri.'" : '.$statuscode.' - '.$response->getReasonPhrase() );
- }
- } catch (ClientException $e) {
- //Exceptions for 400 level errors if the http_errors request option is set to true.
- echo Psr7\str($e->getRequest())
- //Servidor retornou alguma resposta ?
- if ($e->hasResponse()) {
- echo Psr7\str($e->getResponse()) ; //Exibie todo o conteúdo da resposta (incluindo: Header, Body, etc.)
- //Se houve resposta, então exibe a resposta devolvida pela API
- $statuscode = $e->getResponse()->getStatusCode();
- $strBody = $e->getResponse()->getBody();
- $_ret = json_decode($body,true);
- if (json_last_error()!=0) // Se código = 0, então não tem erro (arquivo JSON convertido para Array corretamente)
- $_ret = $strBody;
- /*Exemplo de resposta (depende da API)
- {
- "descricao": "ERRO",
- "erros": [
- {
- "codigo": "integracao.naoAutenticada",
- "mensagem": "Acesso não autorizado"
- }
- ],
- "status": 406
- }
- */
- return $_ret;
- //Ou gera Exception:
- throw new Exception('<b>Erro no request: '.$method.' "'.$uri.'" : <br/>'.PHP_EOL.
- var_export($_ret,true) . '</b> <br/>'.PHP_EOL);
- } else {
- throw new Exception('<b>Erro no request: '.$method.' "'.$uri.'": <br/>'.PHP_EOL.
- $e->getMessage() . '</b><pre/>' . PHP_EOL );
- }
- } catch (RequestException $e) {
- //Exceptions for errors that occur during a transfer.
- if ($this->is_debug)
- echo Psr7\str($e->getRequest()).'<br/>' ;
- echo "<pre>".var_export($options,true)."</pre><br/>";
- if ($e->hasResponse()) {
- //throw new Exception(' Erro no request: '.$method.' "'.$uri.'": '.Psr7\str($e->getResponse() ) );
- //throw new Exception(' Erro no request: '.$method.' "'.$uri.'": '.$e->getResponse() );
- throw new Exception(' Erro no request: '.$method.' "'.$uri.'": '.$e->getMessage() );
- } else {
- throw new Exception(' Erro no request: '.$method.' "'.$uri.'": '.$e->getMessage() );
- }
- } catch (Exception $e) {
- /* **** Erro genérico ***** */
- $_code = $response->getStatusCode();
- //http response code. List of all possible responde code: https://www.restapitutorial.com/httpstatuscodes.html
- //echo $response->getStatusCode();
- //http message phrase associated with the response code
- //echo $response->getReasonPhrase();
- //Tratamento específico para a resposta http "204 - No Content"
- if ( $_code==204 )
- throw new Exception ('204 - No Content (request processado, mas retornou vazio): '.$method.' "'.$uri.'"');
- else
- throw new Exception('Erro Geral no request '.$method.' "'.$uri.'": '.$e->getMessage() );
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement