由於需要寫自動將網址轉成 google 短網址, 所以需要用到 Google Short URL api, 正巧使用的是 Laravel, 所以就順勢搜尋有沒有現成的 package 可以使用, 沒想到居然真的有, 那就不要浪費!直接給他用下去!
Laravel Package for Google Short URL API -> https://github.com/mbarwick83/shorty
使用步驟:
1. 於專案目錄執行 composer require mbarwick83/shorty
2. 修改 config/app.php 在 providers 末端增加 Mbarwick83\Shorty\ShortyServiceProvider::class 後存檔
3
. 修改 config/app.php 在 alias 末端增加 'Shorty' => Mbarwick83\Shorty\Facades\Shorty::class 後存檔
4
. 回到專案根目錄, 執行 php artisan vendor:publish --provider="Mbarwick83\Shorty\ShortyServiceProvider" 進行組態
5
. 顯示
Publishing complete. 便代表安裝完成.
6. 接著, 你必須到 https://developers.google.com/url-shortener/v1/getting_started#APIKey 按下 [get a key] 取得必須的 api key 才能繼續使用
7. 在 [get a key] 的過程, 你必須選擇一個 project 或 建立新的 project.
8. 然後當顯示 You're ready to start developing with URL Shortener API! 代表 API key 已經建立完成, 可以拿該 api key 往下使用.
9. 接著開始寫 code ..
use Mbarwick83\Shorty\Facades\Shorty;
$url = "http://google.com"; --> 你要轉緩的網址 $google_short_url = Shorty::shorten($url);
如此一來 google_short_url 這個PHP變數, 就是你轉址後的網址.
---- 以下是其他的範例 ----
To shorten a URL:
$url = "http://google.com";
Shorty::shorten($url);
// returns, http://goo.gl/XXXXX
To expand a shortened URL:
$url = "http://goo.gl/XXXXX";
Shorty::expand($url);
// returns, http://google.com
To get stats on shortened URL:
$url = "http://goo.gl/XXXXX";
Shorty::stats($url);
If successful, stats response will return:
{
"kind": "urlshortener#url",
"id": "http://goo.gl/fbsS",
"longUrl": "http://www.google.com/",
"status": "OK",
"created": "2009-12-13T07:22:55.000+00:00",
"analytics": {
"allTime": {
"shortUrlClicks": "3227",
"longUrlClicks": "9358",
"referrers": [ { "count": "2160", "id": "Unknown/empty" } /* , ... */ ],
"countries": [ { "count": "1022", "id": "US" } /* , ... */ ],
"browsers": [ { "count": "1025", "id": "Firefox" } /* , ... */ ],
"platforms": [ { "count": "2278", "id": "Windows" } /* , ... */ ]
},
"month": { /* ... */ },
"week": { /* ... */ },
"day": { /* ... */ },
"twoHours": { /* ... */ }
}
}