BitlyClient.php
<?php
class BitlyClient
{
private $token;
private $baseUrl = "https://api-ssl.bitly.com/v4";
private $response;
public function __construct($token)
{
$this->token = $token;
}
private function request($method, $endpoint, $data = null)
{
$ch = curl_init($this->baseUrl . $endpoint);
$headers = [
"Authorization: Bearer {$this->token}",
"Content-Type: application/json"
];
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
if ($data !== null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
$res = curl_exec($ch);
if (curl_errno($ch)) {
throw new Exception(curl_error($ch));
}
curl_close($ch);
$this->response = json_decode($res, true);
return $this;
}
/**
* 短縮URL作成
*/
public function shorten($longUrl, $groupGuid, $domain = "bit.ly")
{
return $this->request("POST", "/shorten", [
"long_url" => $longUrl,
"domain" => $domain,
"group_guid" => $groupGuid
]);
}
/**
* 情報取得
*/
public function getBitlink($bitlink)
{
return $this->request("GET", "/bitlinks/" . $bitlink);
}
/**
* 削除
*/
public function deleteBitlink($bitlink)
{
return $this->request("DELETE", "/bitlinks/" . $bitlink);
}
/**
* レスポンス取得
*/
public function getResponse()
{
return $this->response;
}
}
BitlyClient (PHP)
Bitly API v4 を簡単に扱うためのシンプルな PHP クライアントクラスです。
短縮URLの 作成・取得・削除 をサポートしています。
公式API: Bitly API v4
Features
- 短縮URL作成
- 短縮URL情報取得
- 短縮URL削除
- メソッドチェーン対応
- cURLベースの軽量クライアント
Requirements
- PHP 7.4 以上
- cURL extension
Installation
クラスファイルをプロジェクトに配置してください。
BitlyClient.php
読み込み
require_once 'BitlyClient.php';
Usage
1. 初期化
$token = "YOUR_BITLY_TOKEN";
$bitly = new BitlyClient($token);
Bitlyのアクセストークンは
Bitly の管理画面から取得できます。
Create Short Link
短縮URLを作成します。
$bitly->shorten(
"https://example.com",
"GROUP_GUID"
);
$response = $bitly->getResponse();
print_r($response);
レスポンス例
{
"link": "https://bit.ly/xxxxx",
"long_url": "https://example.com"
}
Get Bitlink Info
短縮URLの情報を取得します。
$bitly->getBitlink("bit.ly/xxxxx");
$response = $bitly->getResponse();
print_r($response);
Delete Bitlink
短縮URLを削除します。
$bitly->deleteBitlink("bit.ly/xxxxx");
$response = $bitly->getResponse();
print_r($response);
Method Chaining
API呼び出しはメソッドチェーンで利用できます。
$response = $bitly
->shorten("https://example.com","GROUP_GUID")
->getResponse();
Available Methods
| Method | Description |
|---|---|
| shorten() | 短縮URLを作成 |
| getBitlink() | 短縮URLの情報取得 |
| deleteBitlink() | 短縮URL削除 |
| getResponse() | APIレスポンス取得 |
Example Project Structure
project/
├ BitlyClient.php
└ index.php