미디어 온 연구실

[전자부품 API] 전자부품 Digi-Key API를 위한 OAUTH2.0 토큰 PHP 모듈 본문

연구실 노트

[전자부품 API] 전자부품 Digi-Key API를 위한 OAUTH2.0 토큰 PHP 모듈

미디어ON 2024. 5. 29. 12:00

전자부품 검색용 Digi-Key API 연계를 위해 개발 전 Rest API 사용 테스트를 위해 PHP로 모듈을 아래와 같이 만들어 봤다.

 

모듈 제작 전 digikey.com에 가입 후 https://developer.digikey.com/ 으로 이동 Production App 과  Sandbox App 에 정보를 등록하여, 각 각 Client ID와 Client Secret를 만듭니다.

 

<?php

$code_type = $_GET["code"];
$client_id = "등록된 client_id";
$client_secret = "등록된 client_secret";
$redirect_uri = "등록한 Callback URL";

$grant_type = "authorization_code";
$url = 'https://api.digikey.com/v1/oauth2/token';

$headers[] = 'Content-Type: application/x-www-form-urlencoded';
$headers[] = 'Accept: application/json';
$headers[] = 'Cache-Control: no-cache';

$host_info = explode("/", $url);
$port = $host_info[0] == 'https:' ? 443 : 80;

$ch = curl_init();
curl_setopt($ch, CURLOPT_PORT, $port);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'code='.$code_type.'&client_id='.$client_id.'&client_secret='.$client_secret.'&redirect_uri='.$redirect_uri.'&grant_type='.$grant_type);

$response = curl_exec($ch);
curl_close($ch);

if (!$response) {
 echo 'no response';
 exit;
}

echo "받은 토큰 정보 : <br>";
var_dump ($response);
?>

 

등록한 Callback URL 소스를 작성 후 

https://api.digikey.com/v1/oauth2/authorize?response_type=code&client_id=등록된 client_id&redirect_uri=https%3A%2F%2F등록한 Callback URL

 

를 웹브라우저 주소창에 입력하여 Digi-Key API 연계를 위해 토큰을 확인할 수 있다.

 

전자 부품 및 산업용 웹/앱 솔루션 개발은 미디어인  http://www.mediain.co.kr

Comments