Calling google api url shortener via curl returns HTTP 403 status in php

497 Views Asked by At

I have a problem calling Google urlshortener. I use curl function to make a call:

$url = base_url()."home/register?source=@".$userid;
$longUrl = $url;
$apiKey = 'xxxxxxxxapikeyxxxxxxx';
$postData = array('longUrl' => $longUrl, 'key' => $apiKey);
$jsonData = json_encode($postData);
$curlObj = curl_init();
curl_setopt($curlObj, CURLOPT_URL, 
'https://www.googleapis.com/urlshortener/v1/url?key='.$apiKey);
curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curlObj, CURLOPT_HEADER, 0);
curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content- 
type:application/json'));
curl_setopt($curlObj, CURLOPT_POST, 1);
curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData);
$response = curl_exec($curlObj);
$json = json_decode($response);
curl_close($curlObj);
print_r($json);

So I'm getting the following response:

stdClass Object ( [error] => stdClass Object ( [errors] => Array ( [0] => 
stdClass Object ( [domain] => global [reason] => forbidden [message] => 
Forbidden ) ) [code] => 403 [message] => Forbidden ) )

Please help me.

1

There are 1 best solutions below

2
On

You can no longer use the Google URL Shortener API using an api key.

Starting March 30, 2018, we will be turning down support for goo.gl URL shortener. Please see this blog post for detailed timelines and alternatives.

You should be aware that the Google URL Shortener API has been discontinued Transitioning Google URL Shortener to Firebase Dynamic Links

They have already begun tuning down a number of the features within the API. I suspect the issue you are having is due to that.

You should switch to FireBase Dynamic links