google url shortener
先去google dev console建立一個project,然後去啟用google url shortener這個API服務。
再來針對這個功能新增一組APIkey。
金鑰限制選擇=>HTTP 參照網址 (網站)
並將你會call這個api的網址key上去。
$key = 'AIzaSyDIpQt_Dg4-4ttIIsg-RNO5VkTxxbicvk8'; // 這是申請到的apiKey
$url = 'https://www.googleapis.com/urlshortener/v1/url?key='.$key; // 這是要call的google url shoretner,並且在後面加上你的apiKey
$data['longUrl'] = $metadata['og_url']; // 這是你要轉成短連結的原始連結
$var = $this->curlModule($data,$url); // 然後透過curl傳給google
// 以下這是針對這個google url shortener 所做的一些設定並送出然後等response
public function curlModule ($post, $route){
try {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_HEADER => 0,
CURLOPT_REFERER => 'http://'.$_SERVER['HTTP_HOST'], // 這個很重要,要把你在申請金鑰的時候所key進去的domain
CURLOPT_URL => $route,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($post),
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-type: application/json",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
throw new \Exception($err);
} else {
return \App\Library\Commontools::ConvertStringToArray($response);
}
} catch(\Exception $ex) {
\App\Models\ErrorLog::InsertData($ex);
return false;
}
}
Last updated
Was this helpful?