로그인

  • 목록
  • 아래로
  • 위로
  • 쓰기
  • 검색

정보&강의 Google URL Shortener API PHP 최종 완결판 소스


인터넷에 떠도는 소스들은 버그나 문제가 많다.

아래의 소스는 최종 완결판이다.

 

$longUrl = "사이트 URL";
$apiKey = "구글 API Key";
$referer = "인증에 사용할 리퍼러";
 
//Array로 도메인을 넣는다.  
$postData = array('longUrl' => $longUrl);
//인코딩 시킨다.
$jsonData = json_encode($postData);
 
$Curl = "https://www.googleapis.com/urlshortener/v1/url?key=\".$apiKey;
$curlObj = curl_init();
  
curl_setopt($curlObj, CURLOPT_URL, $Curl);
curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curlObj, CURLOPT_HEADER, 0);
curl_setopt($curlObj, CURLOPT_REFERER, $referer);
curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
curl_setopt($curlObj, CURLOPT_POST, 1);
curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData);
  
$response = curl_exec($curlObj);
  
//change the response json string to object
$json = json_decode($response);
  
curl_close($curlObj);
 
if(isset($json->error)){
    $result = $json->error->message;
}else{
    $result = $json->id;
}
 
echo $result;

 

만일 $result 값이 에러가 아래와 같이 나온다면

 

"domain": "usageLimits", "reason": "dailyLimitExceededUnreg", "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.",

"code": 403,

API and credentials are authorized and within daily quota, intact, below 0.07/sec/day.

 

https://console.developers.google.com/apis/credentials > Credentials > API Manager > Accept requests from these HTTP referrers (web sites) 항목에 자신의 도메인을 적으면 된다. (ex, naver.com)


이런 글도 찾아보세요!

공유

facebooktwitterpinterestbandkakao story
퍼머링크

댓글 0

권한이 없습니다. 로그인

신고

"님의 댓글"

이 댓글을 신고 하시겠습니까?

삭제

"님의 댓글"

이 댓글을 삭제하시겠습니까?