[php] PHP에서 API 호출을 위한 토큰 기반 인증 처리
웹 애플리케이션을 개발하다보면 외부 API를 호출해야 하는 경우가 많습니다. 이때 API에 접근하기 위해서는 토큰 기반 인증을 통해 권한을 부여받아야 합니다. PHP에서 API를 호출하고자 할 때 가장 먼저 할 일은 토큰을 받아오는 것입니다.
1. API 인증을 위한 토큰 받아오기
PHP에서는 cURL을 사용하여 API에 요청을 보내고 응답을 받아올 수 있습니다. API의 인증을 위해 동일한 프로세스를 사용하여 토큰을 요청하고 받아오게 됩니다. 아래는 예시 코드입니다.
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.example.com/auth/token');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=client_credentials');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded', 'Authorization: Basic '.base64_encode('client_id:client_secret')));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$token = json_decode($response)->access_token;
?>
위 코드는 cURL을 사용하여 API의 /auth/token
엔드포인트에 client_credentials
방식으로 토큰을 요청하는 예시입니다.
2. 받아온 토큰을 사용하여 API 호출하기
받아온 토큰을 사용하여 실제로 API를 호출하는 과정은 아래와 같이 이루어집니다.
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.example.com/data');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '.$token));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response);
?>
받아온 토큰을 Authorization
헤더에 담아 API에 요청을 보내고 응답을 받아오고 있습니다.
결론
PHP에서 API를 호출하기 위해서는 먼저 토큰을 받아오고, 받아온 토큰을 이용하여 API에 요청을 보내는 과정이 필요합니다. 위 코드를 참고하여 효율적으로 API를 호출하여 사용할 수 있습니다.