Google-Shortner API mit PHP

Im Laufe der Arbeiten an der Midrub-API entschied ich mich zur folgenden Lösung zwecks Kürzen der Links (Produktlinks, Affiliatelinks).

$api_key = 'deinapikey';
$request_data = array(
'longUrl' => 'deeplink'
);
$curl_obj = curl_init(sprintf('%s/url?key=%s', 'https://www.googleapis.com/urlshortener/v1', $api_key));
curl_setopt($curl_obj, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_obj, CURLOPT_POST, true);
curl_setopt($curl_obj, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
curl_setopt($curl_obj, CURLOPT_POSTFIELDS, json_encode($request_data));
curl_setopt($curl_obj, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_obj, CURLOPT_SSL_VERIFYHOST, false);
$response = curl_exec($curl_obj);
$json = json_decode($response);
curl_close($curl_obj);
$shortLink = get_object_vars($json);
echo "Shortened URL is: ".$shortLink['id'];
die();

Schreibe einen Kommentar