How to import gmail contacts in PHP using OAuth 2.0

 

As per day by day growing the website, Invite friend request functionality is a good feature which you can use in your website. Before use this you need to import your gmail/yahoo contacts.In this tutorial we will see how to import gmail contacts using PHP.

Before you import gmail contacts you need to configure some settings in gmail developer console. Below are the step by step description with images.

First go to Google Developer Console and login with your account details. After login, on the top right corner click on create project. below is the images.

After click on create project it will open a popup like below. By default project name is prefilled with “My Project”. You can change it yourself and then click on create.

Next click on Contacts API link which is marked in red color in the below image.

Then it will oopen a page something like below. Now click on Enable to activate the contacts API.

Now on the left menu click on Credentials menu which will open a page slike below. Now click on OAuth consent screen and by default email address is prefilled with your email address which you have logged in and then in the Product name shown to users box enter the name and then submit. Remember this name will display to the user at the time of login to gmail account.

Next click on Creditionals Tab and it will open a popup with 4 option which will look like below. Click on OAuth client ID.

Now it will open a new page which looks like below with 6 radio button and Web application radio button is pre selected. You can choose as per requirement and here we are using for website so we will select the Web application selected. Next enter the name of the client ID, In the Authorized Javascript origins enter your domain full URL and finally Authorised redirect URIs enter your full callback URL and then click on create button.

Finally it will generate your client ID and secret ID which we will use in our PHP script.

<?php
$client_id = 'XXXXX'; //Put your client Id
$client_secret = 'XXXXX'; //Put your gmail secret
$redirect_uri = 'http://www.yoursite.com/callback.php'; //Put your callback URL
$max_results = 500; //set the Maximum result you want to fetch

$auth_code='';
if(isset($_GET["code"])){
$auth_code = $_GET["code"];


function getContent($url)
{
 $curl = curl_init();
 
 //The URL to fetch.
 curl_setopt($curl,CURLOPT_URL,$url);	
 
 //TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
 curl_setopt($curl,CURLOPT_RETURNTRANSFER,TRUE);	
 
 //The number of seconds to wait while trying to connect.You can use 0 to wait indefinitely.
 curl_setopt($curl,CURLOPT_CONNECTTIMEOUT,5);	
 
 //Set the contents of "User-Agent: " which will used in a HTTP request.
 $userAgent = $_SERVER["HTTP_USER_AGENT"];
 curl_setopt($curl, CURLOPT_USERAGENT, $userAgent);	
 
 //Set this TRUE To follow any "Location: " header that the server sends as part of the HTTP header.
 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);	
 
 //To automatically set the Referer: field in requests where it follows a Location: redirect.
 curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE);	
 
 //The maximum number of seconds to allow cURL functions to execute.
 curl_setopt($curl, CURLOPT_TIMEOUT, 10);	
 
 //Set this false to stop cURL from verifying the peer's certificate.
 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
 $contents = curl_exec($curl);
 curl_close($curl);
 return $contents;
}

$fields=array(
    'code'=>  urlencode($auth_code),
    'client_id'=>  urlencode($client_id),
    'client_secret'=>  urlencode($client_secret),
    'redirect_uri'=>  urlencode($redirect_uri),
    'grant_type'=>  urlencode('authorization_code')
);
$post = '';
foreach($fields as $key=>$value) { $post .= $key.'='.$value.'&'; }
$post = rtrim($post,'&');

$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,'https://accounts.google.com/o/oauth2/token');
curl_setopt($curl,CURLOPT_POST,5);
curl_setopt($curl,CURLOPT_POSTFIELDS,$post);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,0);
$result = curl_exec($curl);
curl_close($curl);

$response =  json_decode($result);
$accesstoken = $response->access_token;
 
$url = 'https://www.google.com/m8/feeds/contacts/default/full?&alt=json&max-results='.$max_results.'&oauth_token='.$accesstoken;
$xmlresponse =  getContent($url);
 
if((strlen(stristr($xmlresponse,'Authorization required'))>0) && (strlen(stristr($xmlresponse,'Error '))>0))
{
	echo "There is some error.Try reloading the page.";
	exit();
}

/*Custom Coding*/
if(count($xmlresponse)>0){
	$decoded_data=json_decode($xmlresponse);
	echo '<table cellpadding="0" cellspacing="0">';	
	echo '<tr><th style="padding: 3px;border-top: 1px solid #000;border-left: 1px solid #000;border-bottom: 1px solid #000;font-family: arial;font-size: 13px;">User Name</th>
		 <th style="padding: 3px;border-top: 1px solid #000;border-left: 1px solid #000;border-bottom: 1px solid #000;font-family: arial;font-size: 13px;">Email Address</th>
		 <th style="padding: 3px;border-top: 1px solid #000;border-right: 1px solid #000;border-left: 1px solid #000;border-bottom: 1px solid #000;font-family: arial;font-size: 13px;">Contact No</th>
		 </tr>';
	foreach($decoded_data->feed->entry as $k=>$v){
		$email_address=isset($v->{'gd$email'}[0]->address)?$v->{'gd$email'}[0]->address:'';
		$UserName=isset($v->title->{'$t'})?ucwords(strtolower($v->title->{'$t'})):'';
		$ContactNo=isset($v->{'gd$phoneNumber'}[0]->{'$t'})?$v->{'gd$phoneNumber'}[0]->{'$t'}:'';
		echo '<tr>
			  <td style="padding: 3px;border-left: 1px solid #000;border-bottom: 1px solid #000;font-family: arial;font-size: 13px;">'.$UserName.'</td>
			  <td style="padding: 3px;border-left: 1px solid #000;border-bottom: 1px solid #000;font-family: arial;font-size: 13px;">'.$email_address.'</td>
			  <td style="padding: 3px;border-left: 1px solid #000;border-right: 1px solid #000;border-bottom: 1px solid #000;font-family: arial;font-size: 13px;">'.$ContactNo.'</td>
			  </tr>';			
	}
	echo '</table>';
}

}else{
?>
<a href="https://accounts.google.com/o/oauth2/auth?client_id=<?php echo $client_id;?>&redirect_uri=<?php echo $redirect_uri;?>&scope=https://www.google.com/m8/feeds/&response_type=code">Import Gmail Contact</a>
<?php
}
?>

Leave a comment

SUBSCRIBE TO NEWSLETTER

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Categories