Last active
May 20, 2021 16:26
-
-
Save lipebz/69992767358f80563c4369b43b7fc209 to your computer and use it in GitHub Desktop.
Exemplo de consumo de api com php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Configutações (deixar num arquivo separado e protegido..) | |
define('API_BASE_URL', 'http://10.75.200.152:1266/'); | |
define('API_USER', ''); | |
define('API_PASS', ''); | |
function getInfo($cpf) { | |
// Detalhes do ENDPOINT | |
$url = API_BASE_URL . 'servidor/' . $cpf; | |
$method = 'GET'; | |
$token = getToken()->response->access_token; | |
$headers = [ | |
"Content-Type:application/json", | |
"Authorization: Bearer $token", | |
]; | |
// Consulta na api | |
$ch = curl_init($url); | |
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers); | |
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); | |
$response = curl_exec($ch); | |
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE); | |
curl_close($ch); | |
return (Object) [ | |
'response' => json_decode($response), | |
'code' => $code | |
]; | |
} | |
function getToken() { | |
// Detalhes do ENDPOINT | |
$url = API_BASE_URL . 'token'; | |
$method = 'POST'; | |
$body = json_encode([ | |
'usuario' => API_USER, | |
'senha' => API_PASS, | |
]); | |
$headers = [ | |
"Content-Type:application/json", | |
]; | |
// Consulta na api | |
$ch = curl_init($url); | |
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers); | |
curl_setopt( $ch, CURLOPT_POSTFIELDS, $body); | |
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true); | |
$response = curl_exec($ch); | |
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE); | |
curl_close($ch); | |
return (Object) [ | |
'response' => json_decode($response), | |
'code' => $code | |
]; | |
} | |
// Teste de consulta simples | |
$cpf = 34360378858; | |
$pessoa = getInfo($cpf); // Retorna dois indices (response e code). os dados estão dentro de $pessoa->response | |
var_dump($pessoa); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment