Hello! This post will show you how to import google contacts just after entering the gmail id using google oauth2. It will display all google contacts of that particular Email ID  and will give you  option to download those contact in excel sheet.

OAuth is a strong  protocol for accessing the third party data on behalf of owner .

This whole google OAuth cycle is basically focused on accessing the third party data, after passing through a strong authorization we get some access permission with client id and password and that data is used for getting the code and access token and that key is further used for accessing the complete details by accessing the google API.


Watch the live demo or download code from the link given below


MailGet – Email Service Provider has got many smarter and effective features & facilities which can help in email list management.

Before going to complex coding part  just have  a look over these basic terminology listed below.

 Google OAuth:

OAuth stands for “open standard for authorization” and provide a strong authorization scheme on behalf of owner, OAuth was started with oauth1.0

but it has been deprecated  and replaced with oauth2.0, make sure you are using oauth2.0

OAuth Code: We only get this code while we are successfully authorized, after getting this code we can request for the access token.

Access Token: This token is key to get the content from the website server, while we request for the access token with authorized code then we get the access token. With this token, we can access most of the API and can collect the data according to our requirements.

Refresh Token: Often! we are confused with refresh the token. Refresh token is not a separate token even though it is same access token, but its value got refreshed after leaving  one complete flow or logout from your session.

So Simply get the access token and make its session and maintain it till you get logout and at the time of re-login you will get a new access token or you can call it refresh token .

Steps for getting the google contacts :  here we are explaining step-by-step process for accessing the google contacts.

Step :1

In this step you have to make one google  oauth registration  in google developer console for accessing the google api, for doing that please visit ‘https://console.developers.google.com/project’ and follow these steps.

  1. Go to the Google Developers Console.
  2. Select a project, or create a new one by clicking Create Project. 
  3. In the Project name field, type in a name for your project.
  4. In the Project ID field, optionally type in a project ID for your project or use the one that the console has created for you. This ID must be unique world-wide.
  5. Click the Create button and wait for the project to be created.
  6. Click on the new project name in the list to start editing the project.
  7. In the sidebar under “APIs & auth”, select Consent screen.
  8. Choose an Email Address and specify a Product Name.
  9. In the sidebar under “APIs & auth”, select Credentials.
  10. Click Create a new Client ID — a dialog box appears.
  11. Register the origins from which your app is allowed to access the Google APIs, as follows. An origin is a unique combination of protocol, hostname, and port.
  12. In the Application type section of the dialog, select Web application.
  13. In the Authorized JavaScript origins field, enter the origin for your app. You can enter multiple origins to allow for your app to run on different protocols, domains, or subdomains.
  14. Wildcards are not allowed. In the example below, the second URL could be a production URL.
    http://localhost:8080
    https://myproductionurl.example.com
  15. In the Authorized redirect URI field, delete the default value. Redirect URIs are not used with JavaScript APIs.
  16. Click the Create Client ID button.
  17. In the resulting Client ID for web application section, copy the Client ID that your app will need to use to access the APIs.

just after completion you will get a client id and client secret id.

Step :2

we have already gotten the client id and secret and now we will use these credential for login window or our login page ‘index.php’  while we execute this page we get window asking for ‘sign in with google ‘ when  we click on button we are sent to gmail login window and after entering the gmail credential it directly redirected to our google api. here user is asked for giving and deny the access if he click on access button he is redirected to the callback page here we can see our google contacts and can import them in excel sheet.

index.php

<html>
<head>
<link href="css/style.css" rel="stylesheet" type="text/css"/>
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
<title>Export Google Contacts Using PHP</title>

</head>
<body>

<div id="main" class="col-sm-6 col-md-4 col-lg-2">
<div id="envelope" class="col-sm-6 col-md-4 col-lg-2">

<header id="sign_in" class="col-sm-6 col-md-4 col-lg-2">
<center>
<h2>Export Gmail Contacts With Google Oauth PHP</h2>
</center>
</header>
<hr>
<div id="content" class="col-sm-6 col-md-4 col-lg-2">
<center>
<h3 id ="sign">Sign In with Google for retrieving Contacts</h3>
<div class="col-sm-6 col-md-4 col-lg-2">
<a href="https://accounts.google.com/o/oauth2/auth?client_id=470483912778-4sa6ef2lhjfabp2no8nb5f0ht3sel123.apps.googleusercontent.com&redirect_uri=http://127.0.0.1/export-gmail-contacts-in-php/callback.php&scope=https://www.google.com/m8/feeds/&response_type=code"><img src="images/sign1.png" alt="" id="signimg"/></a>
</div>
</center>
</div>
</div>
</div>

</body>
</html>

Step :3

Here you will display all the google content , we are using access token for accessing the google contacts.

callback.php

<?php
session_start();
?>
<?php
$accesstoken = '';
$client_id = '470483912778-4sa6ef2lhjfabp2no8nb5f0ht3sel123.apps.googleusercontent.com';
$client_secret = 'lu7N1ukpl2nezboZI2orYRj2';
$redirect_uri = 'http://127.0.0.1/export-gmail-contacts-in-php/callback.php';
$simple_api_key = 'AIzaSyB_IOM7pfIAc3OEFZZBC5LpoACPPgwJ_hg';
$max_results = 500;
$auth_code = $_GET["code"];

function curl_file_get_contents($url) {
$curl = curl_init();
$userAgent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)';

curl_setopt($curl, CURLOPT_URL, $url); //The URL to fetch. This can also be set when initializing a session with curl_init().
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); //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_CONNECTTIMEOUT, 5); //The number of seconds to wait while trying to connect.

curl_setopt($curl, CURLOPT_USERAGENT, $userAgent); //The contents of the "User-Agent: " header to be used in a HTTP request.
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE); //To follow any "Location: " header that the server sends as part of the HTTP header.
curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE); //To automatically set the Referer: field in requests where it follows a Location: redirect.
curl_setopt($curl, CURLOPT_TIMEOUT, 10); //The maximum number of seconds to allow cURL functions to execute.
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); //To stop cURL from verifying the peer's certificate.
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);

$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);
if (isset($response->access_token)) {
$accesstoken = $response->access_token;
$_SESSION['access_token'] = $response->access_token;
}
if (isset($_GET['code'])) {
$accesstoken = $_SESSION['access_token'];
}

if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
$url = 'https://www.google.com/m8/feeds/contacts/default/full?max-results=' . $max_results . '&oauth_token=' . $accesstoken;
$xmlresponse = curl_file_get_contents($url);

if ((strlen(stristr($xmlresponse, 'Authorization required')) > 0) && (strlen(stristr($xmlresponse, 'Error ')) > 0)) {
echo "<h2>OOPS !! Something went wrong. Please try reloading the page.</h2>";
exit();
}

//echo " <a href ='http://127.0.0.1/gmail_contact/callback.php?downloadcsv=1&code=4/eK2ugUwI_qiV1kE3fDa_92geg7s1DusDsN9BHzGrrTE# '><img src='images/excelimg.jpg' alt=''id ='downcsv'/></a>";
// echo "<h3>Email Addresses:</h3>";
$xml = new SimpleXMLElement($xmlresponse);
$xml->registerXPathNamespace('gd', 'http://schemas.google.com/g/2005/Atom');

$result = $xml->xpath('//gd:email');

foreach ($result as $title) {
$arr[] = $title->attributes()->address;
echo $title->attributes()->displayName;
}
//print_r($arr);
foreach ($arr as $key) {
//echo $key."<br>";
}

$response_array = json_decode(json_encode($arr), true);

// echo "<pre>";
// print_r($response_array);
//echo "</pre>";

$email_list = '';
foreach ($response_array as $value2) {

$email_list = ($value2[0] . ",") . $email_list;
}
//echo $abc;
// $final_array[] = $abc;
// $farr =$final_array;
//echo "<pre>";
//print_r($final_array);
// echo "</pre>";
//<input type="text" value="<?php echo ($abc);?" name="email">
?>
<html>
<head>
<link href="css/style.css" rel="stylesheet" type="text/css"/>
<link href="css/table.css" rel="stylesheet" type="text/css"/>
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Export Google Contacts Using PHP</title>

</head>
<body>

<div id="main" >

<div class="col-sm-6 col-md-4 col-lg-2">
<div id="envelope" class="col-sm-6 col-md-4 col-lg-2">

<header id="sign_in">
<h2> <form action='csvdownload.php' method='post'>
<input type='text' value= '<?php echo $email_list; ?>' name='email' style='display: none'>

<input type='image' width='100' value='submit' src='images/excelimg1.gif' alt='submit Button' id ='btnimg'>
</form>Export Gmail Contacts<a href='https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=http://127.0.0.1/export-gmail-contacts-in-php/index.php' ><img src='images/logoutimg1.png' alt=''id ='logoutimg'/></a></h2>
</header>
<hr>
<div id="content" class="col-sm-6 col-md-4 col-lg-2">
<div class="col-sm-6 col-md-4 col-lg-2">

<div class="col-sm-6 col-md-4 col-lg-2">

<table cellspacing='0'>
<thead>
<td id="name">S.No</td>
<td>Email Addresses</td>
</thead>
<?php
$count = 0;
foreach ($result as $title) {
?>
<tr>
<td><?php echo $count;
$count++ ?></td>
<link href="style.css" rel="stylesheet" type="text/css"/>
<td><?php echo $title->attributes()->address; ?></td>
</tr>
<?php
}
?></table>

</div>

</div>
</div>
</div>
</div>
</div>

</body></html>

csvdownload.php

This script will show you how to download the google contacts in excel sheet , we are getting the data in form of string and here we are using scripts for printing them for spread sheet format.

<?php

$data = $_POST['email'];

$arry[] = explode(',', $data);

foreach ($arry as $row) {
$arlength = count($row);
for ($i = 0; $i < $arlength; $i++) {
$farry[] = explode(',', $row[$i]);
}
}

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

$file = fopen('php://output', 'w');
fputcsv($file, array('Description'));
foreach ($farry as $row) {
fputcsv($file, $row);
}
exit();

Conclusion :

After reading the above post, I am sure you will give a try to the script provided and implement it in your own projects as well. Feel free to visit our website again in the future to get in touch with new coding tricks. You can let us know about your feedback in the space provided below

Get more related information here –