Skip to content

Instantly share code, notes, and snippets.

@lipebz
Last active May 20, 2021 16:26
Show Gist options
  • Save lipebz/69992767358f80563c4369b43b7fc209 to your computer and use it in GitHub Desktop.
Save lipebz/69992767358f80563c4369b43b7fc209 to your computer and use it in GitHub Desktop.
Exemplo de consumo de api com php
<?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