Skip to content

Instantly share code, notes, and snippets.

@irasally
Last active December 27, 2015 05:49
Show Gist options
  • Save irasally/7277684 to your computer and use it in GitHub Desktop.
Save irasally/7277684 to your computer and use it in GitHub Desktop.
[CakePHP]GET Shorten URL using BitlyAPI
<?php
// app/Lib/BitlyAPI.php
App::uses('HttpSocket', 'Network/Http');
class BitlyAPI {
const LOGIN_ID = "Your ID";
const API_KEY = "Your API Key";
/* 短縮URLを含むjsonを取得する
* = example response =
* {
* "data": {
* "global_hash": "900913",
* "hash": "ze6poY",
* "long_url": "http://google.com/",
* "new_hash": 0,
* "url": "http://bit.ly/ze6poY"
* },
* "status_code": 200,
* "status_txt": "OK"
* }
*/
public function shorten( $url ) {
$http = new HttpSocket();
$response = $http->get($this->shortenReqUrl($url));
if($response->code != 200) {
throw new Exception("http_status_error::" . $http_status);
}
return json_decode(mb_convert_encoding($response->body, 'UTF-8', 'auto'), true);
}
private function shortenReqUrl($url){
$reqUrl = "http://api.bit.ly/v3/shorten";
$reqUrl .= "?login=" .BitlyAPI::LOGIN_ID;
$reqUrl .= "&apiKey=" .BitlyAPI::API_KEY;
$reqUrl .= "&longUrl=" .urlencode($url);
return $reqUrl;
}
}
?>
<?php
// app/View/Helper/BitlyHelper.php
App::uses('BitlyAPI', 'Lib');
class BitlyHelper extends Helper {
function getShortenUrl($url){
try {
$api = new BitlyAPI();
$json = $api->shorten($url);
if($json['status_code'] != 200 || $json['status_txt'] != 'OK') {
throw new Exception( sprintf('status_code::%s, errorMessage::%s', $json['status_code'], $json['status_txt']));
}
} catch(Exception $e) {
// 元URLをそのまま表示させる
return $url;
}
return $json['data']['url'];
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment