My website won't show any contacts? - php

When I click on the <a> which stands in main.php to import the contacts and I click through the accepts of google so I allow them to see my contacts. And then when I return to own page... it doesn't show any contacts at all. I think it's because I don't return any contacts, but I don't know how.
app.yaml:
application: csimporttest
version: 1
runtime: php55
api_version: 1
handlers:
- url: /.*
script: main.php
main.php:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h2>Hi!</h2>
<?php include('response-callback.php');?>
Import
</body>
</html>
response-callback.php;
<?php
session_start();
require_once 'google-api-php-client-master/src/Google/autoload.php';
$google_client_id = 'SECRET';
$google_client_secret = 'SECRET';
$google_redirect_uri = 'https://csimporttest.appspot.com/response-callback.php';
//setup new google client
$client = new Google_Client();
$client -> setApplicationName('csimporttest');
$client -> setClientid($google_client_id);
$client -> setClientSecret($google_client_secret);
$client -> setRedirectUri($google_redirect_uri);
$client -> setAccessType('online');
$client -> setScopes('https://www.googleapis.com/auth/contacts.readonly');
$googleImportUrl = $client -> createAuthUrl();
function curl($url, $post = "") {
$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.
if ($post != "") {
curl_setopt($curl, CURLOPT_POST, 5);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
}
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, FALSE);
//To stop cURL from verifying the peer's certificate.
$contents = curl_exec($curl);
curl_close($curl);
return $contents;
}
//google response with contact. We set a session and redirect back
if (isset($_GET['code'])) {
$auth_code = $_GET["code"];
$_SESSION['google_code'] = $auth_code;
header('Location: ' . $google_redirect_uri);
}
if(isset($_SESSION['google_code'])) {
$auth_code = $_SESSION['google_code'];
$max_results = 200;
$fields=array(
'code'=> urlencode($auth_code),
'client_id'=> urlencode($google_client_id),
'client_secret'=> urlencode($google_client_secret),
'redirect_uri'=> urlencode($google_redirect_uri),
'grant_type'=> urlencode('authorization_code')
);
$post = '';
foreach($fields as $key=>$value)
{
$post .= $key.'='.$value.'&';
}
$post = rtrim($post,'&');
$result = curl('https://www.googleapis.com/oauth2/v4/token',$post);
$response = json_decode($result);
$accesstoken = $response->access_token;
$url = 'https://www.google.com/m8/feeds/contacts/default/full?max-results='.$max_results.'&alt=json&v=3.0&oauth_token='.$accesstoken;
$xmlresponse = curl($url);
$contacts = json_decode($xmlresponse,true);
$return = array();
if (!empty($contacts['feed']['entry'])) {
foreach($contacts['feed']['entry'] as $contact) {
//retrieve Name and email address
$return[] = array (
'name'=> $contact['title']['$t'],
'email' => $contact['gd$email'][0]['address'],
);
}
}
$google_contacts = $return;
unset($_SESSION['google_code']);
}
if (!empty($contacts['feed']['entry'])) {
foreach($contacts['feed']['entry'] as $contact) {
//retrieve Name and email address
$return[] = array (
'name'=> $contact['title']['$t'],
'email' => $contact['gd$email'][0]['address'],
);
//retrieve user photo
if (isset($contact['link'][0]['href'])) {
$url = $contact['link'][0]['href'];
$url = $url . '&access_token=' . urlencode($accesstoken);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_TIMEOUT, 15);
curl_setopt($curl, CURLOPT_VERBOSE, true);
$image = curl_exec($curl);
curl_close($curl);
}
$return['image'] = $image;
echo '';
}
}
?>

The last thing the code does is set '$google_contacts = $return', so it's up to your app to do something useful with the $google_contacts array, such as display it. The blog where this code originated doesn't mention that the code sample displays anything, only that it is an example of how to retrieve contacts.

You can use an var_dump() to see if the array google_contacts is actually filled. Put this in the main.php:
<?php
var_dump($google_contacts);
?>
If you get an output in the var_dump you can use an html table and an easy foreach, look below:
<table border='1' class="table table-striped table-condensed">
<thead>
<tr>
<th>Naam </th>
<th>Email </th>
</tr>
</thead>
<tbody>
<?php
foreach ($google_contacts as $contacts){
echo'<tr>';
echo'<td>'. $contacts['name']."</td>";
echo'<td>'. $contacts['email'].'</td>';
echo'</tr>';
}
?>
</tbody>
</table>

Related

How can I put values from an array into an HTML Table?

I am trying to use the Google Contacts API to show all my contacts. I followed an tutorial, but sadly this tutorial doesnt show how to show the data on my website. I am also using Google App Engine and PHPStorm if it matters...
Main.php
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js"></script>
</head>
<body>
<table class="table table-striped table-condensed">
<thead>
<tr>
<th>Naam </th>
<th>Email </th>
</tr>
</thead>
<tbody>
<?php
include('response-callback.php');
foreach ($google_contacts as $contacts){
echo'<tr>';
echo'<td>'. $contacts['title']."</td>";
echo'<td>'. $contacts['gd$email'].'</td>';
echo'</tr>';
}
?>
</tbody>
</body>
</html>
Response-callback.php
require_once '../../../mike/Documents/google-api-php-client-1-master/src/Google/autoload.php';
$google_client_id = 'xxxxxxxxx-xxxxxxxxxxxx.apps.googleusercontent.com';
$google_client_secret = 'xxxxxxx';
$google_redirect_uri = 'https://xxxxxxx-xxxx.appspot.com/main.php';
//setup new google client
$client = new Google_Client();
$client -> setApplicationName('ImportContacts');
$client -> setClientid($google_client_id);
$client -> setClientSecret($google_client_secret);
$client -> setRedirectUri($google_redirect_uri);
$client -> setAccessType('online');
$client -> setScopes('https://www.google.com/m8/feeds');
$googleImportUrl = $client -> createAuthUrl();
function curl($url, $post = "") {
$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.
if ($post != "") {
curl_setopt($curl, CURLOPT_POST, 5);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
}
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, FALSE);
//To stop cURL from verifying the peer's certificate.
$contents = curl_exec($curl);
curl_close($curl);
return $contents;
}
//google response with contact. We set a session and redirect back
if (isset($_GET['code'])) {
$auth_code = $_GET["code"];
$_SESSION['google_code'] = $auth_code;
header('Location: ' . $google_redirect_uri);
}
if(isset($_SESSION['google_code'])) {
$auth_code = $_SESSION['google_code'];
$max_results = 200;
$fields=array(
'code'=> urlencode($auth_code),
'client_id'=> urlencode($google_client_id),
'client_secret'=> urlencode($google_client_secret),
'redirect_uri'=> urlencode($google_redirect_uri),
'grant_type'=> urlencode('authorization_code')
);
$post = '';
foreach($fields as $key=>$value)
{
$post .= $key.'='.$value.'&';
}
$post = rtrim($post,'&');
$result = curl('https://accounts.google.com/o/oauth2/token',$post);
$response = json_decode($result);
$accesstoken = $response->access_token;
$url = 'https://www.google.com/m8/feeds/contacts/default/full?max-results='.$max_results.'&alt=json&v=3.0&oauth_token='.$accesstoken;
$xmlresponse = curl($url);
$contacts = json_decode($xmlresponse,true);
$return = array();
if (!empty($contacts['feed']['entry'])) {
foreach($contacts['feed']['entry'] as $contact) {
//retrieve Name and email address
$return[] = array (
'name'=> $contact['title']['$t'],
'email' => $contact['gd$email'][0]['address'],
);
}
}
$google_contacts = $return;
unset($_SESSION['google_code']);
}
You are using the wrong array keys when you iterate through the $google_contacts array.
Change this
foreach ($google_contacts as $contacts){
echo'<tr>';
echo'<td>'. $contacts['title']."</td>";
echo'<td>'. $contacts['gd$email'].'</td>';
echo'</tr>';
}
To this
foreach ($google_contacts as $contacts){
echo'<tr>';
echo'<td>'. $contacts['name']."</td>";
echo'<td>'. $contacts['email'].'</td>';
echo'</tr>';
}

Can't seem to retrieve other things than name and email from Contacts API

I'm pretty sure that the gd$phoneNumber, gd$city, gd$street and gd$country are not valid. I just can not find out what to call these variables.
All the variables just return NULL. See below for my vardump.
["name"]=> string(0) ""
["email"]=> string(18) "xxxx#xxxxxxx.com"
["phoneNumber"]=> NULL
["city"]=> NULL
["street"]=> NULL
["country"]=> NULL
Also I am only able to retrieve information from the Contacts API when in localhost.
When I am on the xxxxxx.appspot.com website it won't retrieve information but it will show the table headers.
QUESTION
How can I retrieve more things than just the name and email address with the Contacts API?
Main.php
Import google contacts
<table class="table table-striped table-condensed">
<thead>
<tr>
<th>Naam </th>
<th>Email </th>
<th>Telefoon </th>
<th>Stad </th>
<th>Adres </th>
<th>Land </th>
</tr>
</thead>
<tbody>
<?php
foreach( $google_contacts as $contacts ){
echo'<tr>';
echo'<td>'. $contacts['name']."</td>";
echo'<td>'. $contacts['email'].'</td>';
echo'<td>'. $contacts['phoneNumber']."</td>";
echo'<td>'. $contacts['city'].'</td>';
echo'<td>'. $contacts['street']."</td>";
echo'<td>'. $contacts['country'].'</td>';
echo'</tr>';
}?>
</tbody>
</table>
Response-callback.php
$test = 'HEY';
require_once 'google-api-php-client-1-master/src/Google/autoload.php';
$google_client_id = 'xxxxxx-xxxxxx.apps.googleusercontent.com';
$google_client_secret = 'xxxxxxx';
$google_redirect_uri = 'http://localhost:9080';
//$google_redirect_uri = 'https://importcontacts-1216.appspot.com';
//setup new google client
$client = new Google_Client();
$client -> setApplicationName('ImportContacts');
$client -> setClientid($google_client_id);
$client -> setClientSecret($google_client_secret);
$client -> setRedirectUri($google_redirect_uri);
$client -> setAccessType('online');
$client -> setScopes('https://www.google.com/m8/feeds');
$googleImportUrl = $client -> createAuthUrl();
function curl( $url, $post = "" ){
$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.
if( $post != "" ){
curl_setopt($curl, CURLOPT_POST, 5);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
}
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, FALSE);
//To stop cURL from verifying the peer's certificate.
$contents = curl_exec($curl);
curl_close($curl);
return $contents;
}
//google response with contact. We set a session and redirect back
if( isset( $_GET['code'] ) ){
$auth_code = $_GET["code"];
$_SESSION['google_code'] = $auth_code;
header('Location: ' . $google_redirect_uri);
}
if( isset( $_SESSION['google_code'] ) ){
$auth_code = $_SESSION['google_code'];
$max_results = 200;
$fields = array(
'code'=> urlencode($auth_code),
'client_id'=> urlencode($google_client_id),
'client_secret'=> urlencode($google_client_secret),
'redirect_uri'=> urlencode($google_redirect_uri),
'grant_type'=> urlencode('authorization_code')
);
$post = '';
foreach( $fields as $key=>$value ){
$post .= $key.'='.$value.'&';
}
$post = rtrim($post,'&');
$result = curl('https://accounts.google.com/o/oauth2/token',$post);
$response = json_decode($result);
$accesstoken = $response->access_token;
$url = 'https://www.google.com/m8/feeds/contacts/default/full?max-results='.$max_results.'&alt=json&v=3.0&oauth_token='.$accesstoken;
$xmlresponse = curl($url);
$contacts = json_decode($xmlresponse,true);
$return = array();
if( !empty( $contacts['feed']['entry'] ) ){
foreach( $contacts['feed']['entry'] as $contact ){
//retrieve Name and email address
$return[] = array(
'name'=> $contact['title']['$t'],
'email' => $contact['gd$email'][0]['address'],
'phoneNumber' => $contact['gd$phoneNumber'][0]['address'],
'city' => $contact['gd$city'][0]['address'],
'street' => $contact['gd$street'][0]['address'],
'country' => $contact['gd$country'][0]['address'],
);
}
}
$google_contacts = $return;
unset( $_SESSION['google_code'] );
}
if( !empty( $contacts['feed']['entry'] ) ){
foreach( $contacts['feed']['entry'] as $contact ){
//retrieve Name and email address
$return[] = array(
'name'=> $contact['title']['$t'],
'email' => $contact['gd$email'][0]['address'],
'phoneNumber' => $contact['gd$phoneNumber'][0]['address'],
'city' => $contact['gd$city'][0]['address'],
'street' => $contact['gd$street'][0]['address'],
'country' => $contact['gd$country'][0]['address'],
'' => $contact['gd$']
);
//retrieve user photo
if( isset( $contact['link'][0]['href'] ) ){
$url = $contact['link'][0]['href'];
$url = $url . '&access_token=' . urlencode($accesstoken);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_TIMEOUT, 15);
curl_setopt($curl, CURLOPT_VERBOSE, true);
$image = curl_exec($curl);
curl_close($curl);
}
$return['image'] = $image;
echo '';
}
}
Change your return array to:
$return[] = array (
'firstname'=> $contact['gd$name']['gd$givenName']['$t'],
'lastname'=> $contact['gd$name']['gd$familyName']['$t'],
'email' => $contact['gd$email'][0]['address'],
'phoneNumber' => $contact['gd$phoneNumber'][0]['$t'],
'city' => $contact['gd$structuredPostalAddress'][0]['gd$city']['$t'],
'street' => $contact['gd$structuredPostalAddress'][0]['gd$street']['$t'],
'country' => $contact['gd$structuredPostalAddress'][0]['gd$country']['$t'],
);

Can't seem to install the google-api-php-client correctly

There is something going wrong with the google api php client. Even though I followed the installation on github precisely it still wont work. Im not using the Composer way but i downloaded the release. I have tried to use different paths in the response-callback.php require_once like
'google-api-php-client/src/google/autoload.php'
'google-api-php-client/vendor_autoload.php'
But nothing worked...
Error:
Fatal error: require_once(): Failed opening required 'google-api-php-client/vendor/autoload.php' (include_path='.:/Users/mike/Documents/test:/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/php/sdk') in /Users/mike/Documents/test/response-callback.php on line 3
Warning: require_once(google-api-php-client/vendor/autoload.php): failed to open stream: No such file or directory in /Users/mike/Documents/test/response-callback.php on line 3
app.yaml:
application: csimporttest
version: 1
runtime: php55
api_version: 1
handlers:
- url: /.*
script: main.php
main.php
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h2>Hi! Stackoverflow!</h2>
<?php include'response-callback.php';
echo "response-callback file: ", $test;
?>
Import google contacts
</body>
</html>
response-callback.php
<?php
require_once 'google-api-php-client/vendor/autoload.php';
$test = 'WORKS!';
$google_client_id = 'SECRET';
$google_client_secret = 'SECRET';
$google_redirect_uri = 'https://csimporttest.appspot.com';
//setup new google client
$client = new Google_Client();
$client -> setApplicationName('csimporttest');
$client -> setClientid($google_client_id);
$client -> setClientSecret($google_client_secret);
$client -> setRedirectUri($google_redirect_uri);
$client -> setAccessType('online');
$client -> setScopes('https://www.googleapis.com/auth/contacts.readonly');
$googleImportUrl = $client -> createAuthUrl();
function curl($url, $post = "") {
$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.
if ($post != "") {
curl_setopt($curl, CURLOPT_POST, 5);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
}
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, FALSE);
//To stop cURL from verifying the peer's certificate.
$contents = curl_exec($curl);
curl_close($curl);
return $contents;
}
if(isset($_SESSION['google_code'])) {
$auth_code = $_SESSION['google_code'];
$max_results = 200;
$fields=array(
'code'=> urlencode($auth_code),
'client_id'=> urlencode($google_client_id),
'client_secret'=> urlencode($google_client_secret),
'redirect_uri'=> urlencode($google_redirect_uri),
'grant_type'=> urlencode('authorization_code')
);
$post = '';
foreach($fields as $key=>$value)
{
$post .= $key.'='.$value.'&';
}
$post = rtrim($post,'&');
$result = curl('https://www.googleapis.com/oauth2/v4/token',$post);
$response = json_decode($result);
$accesstoken = $response->access_token;
$url = 'https://www.google.com/m8/feeds/contacts/default/full?max-results='.$max_results.'&alt=json&v=3.0&oauth_token='.$accesstoken;
$xmlresponse = curl($url);
$contacts = json_decode($xmlresponse,true);
$return = array();
if (!empty($contacts['feed']['entry'])) {
foreach($contacts['feed']['entry'] as $contact) {
//retrieve Name and email address
$return[] = array (
'name'=> $contact['title']['$t'],
'email' => $contact['gd$email'][0]['address'],
);
}
}
$google_contacts = $return;
unset($_SESSION['google_code']);
}
?>
Just put the whole Google php client library in your project folder, then change
require_once 'google-api-php-client/vendor/autoload.php';
to:
require_once 'google-api-php-client-1-master/src/Google/autoload.php';

My php wont do anything? Using Contacts API of google

I'm trying to make an website in which you can import contacts from gmail and add them as friends within the website. For now I'm only trying to show the contacts of the one whom clicks on the <a>. I've followed an tutorial and everything should work, but it doesn't. It does show the <H2> at the top, but not the <a> which is actually important. My google secret and client id are correct, but I'd rather not just show them. The path to the google php API is correct as well, but I think something is going wrong there since it doesn't recognize any php.
app.yaml:
application: csimporttest
version: 1
runtime: php55
api_version: 1
threadsafe: yes
handlers:
- url: .*
script: response-callback.php
Response-callback.php:
<!DOCTYPE html>
<html><body>
<h2>ttest</h2>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js"></script>
<?php
session_start();
//include google api library
require_once 'google-api-php-client/src/Google/autoload.php';// or wherever autoload.php is located
$google_client_id = 'Google Client Id';
$google_client_secret = 'Google Secret';
$google_redirect_uri = 'https://csimporttest.appspot.com';
//setup new google client
$client = new Google_Client();
$client -> setApplicationName('csimporttest');
$client -> setClientid($google_client_id);
$client -> setClientSecret($google_client_secret);
$client -> setRedirectUri($google_redirect_uri);
$client -> setAccessType('online');
$client -> setScopes('https://www.google.com/m8/feeds');
$googleImportUrl = $client -> createAuthUrl();
function curl($url, $post = "") {
$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.
if ($post != "") {
curl_setopt($curl, CURLOPT_POST, 5);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
}
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, FALSE);
//To stop cURL from verifying the peer's certificate.
$contents = curl_exec($curl);
curl_close($curl);
return $contents;
}
if(isset($_SESSION['google_code'])) {
$auth_code = $_SESSION['google_code'];
$max_results = 200;
$fields=array(
'code'=> urlencode($auth_code),
'client_id'=> urlencode($google_client_id),
'client_secret'=> urlencode($google_client_secret),
'redirect_uri'=> urlencode($google_redirect_uri),
'grant_type'=> urlencode('authorization_code')
);
$post = '';
foreach($fields as $key=>$value)
{
$post .= $key.'='.$value.'&';
}
$post = rtrim($post,'&');
$result = curl('https://accounts.google.com/o/oauth2/token',$post);
$response = json_decode($result);
$accesstoken = $response->access_token;
$url = 'https://www.google.com/m8/feeds/contacts/default/full?max-results='.$max_results.'&alt=json&v=3.0&oauth_token='.$accesstoken;
$xmlresponse = curl($url);
$contacts = json_decode($xmlresponse,true);
$return = array();
if (!empty($contacts['feed']['entry'])) {
foreach($contacts['feed']['entry'] as $contact) {
//retrieve Name and email address
$return[] = array (
'name'=> $contact['title']['$t'],
'email' => $contact['gd$email'][0]['address'],
);
}
}
echo ';print_r($google_contacts);echo ';
unset($_SESSION['google_code']);
}
?>
Import google contacts
<?php
if (!empty($contacts['feed']['entry'])) {
foreach($contacts['feed']['entry'] as $contact) {
//retrieve Name and email address
$return[] = array (
'name'=> $contact['title']['$t'],
'email' => $contact['gd$email'][0]['address'],
);
//retrieve user photo
if (isset($contact['link'][0]['href'])) {
$url = $contact['link'][0]['href'];
$url = $url . '&access_token=' . urlencode($accesstoken);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_TIMEOUT, 15);
curl_setopt($curl, CURLOPT_VERBOSE, true);
$image = curl_exec($curl);
curl_close($curl);
}
$return['image'] = $image;
echo '';
}
}
?>
</html></body>
You can use an var_dump() to see if the array google_contacts is actually filled. Put this in the main.php:
<?php
var_dump($google_contacts);
?>
If you get an output in the var_dump you can use an html table and an easy foreach, look below:
<table border='1' class="table table-striped table-condensed">
<thead>
<tr>
<th>Naam </th>
<th>Email </th>
</tr>
</thead>
<tbody>
<?php
foreach ($google_contacts as $contacts){
echo'<tr>';
echo'<td>'. $contacts['name']."</td>";
echo'<td>'. $contacts['email'].'</td>';
echo'</tr>';
}
?>
</tbody>
</table>
First of all, you're correct - never show your client ID and secret.
There are a number of things that are unclear about what you're posting, including how, exactly, you're getting the google_code session variable set, but I would suggest debugging along the following lines:
Look at the full value from $result. It may be returning an error code which might indicate why it isn't loading the contacts.
Double-check the token URL endpoint. https://developers.google.com/identity/protocols/OAuth2WebServer says it should be https://www.googleapis.com/oauth2/v4/token, but I've seen the URL listed differently in the past, so I never know which one is actually valid.
Make sure you have authorized the Contact API in the Google Developers Console and make sure, as you go through the authorization window, that it asks for permission to access your contacts.

Google Contacts Import to Mysql in PHP via OAuth

i was creating a small app using jquery mobile with server side language as php,so i want to import all my google contacts (Names,Numbers & Email) into a mysql database using the OAuth. Currently im using the following script which can grab only email addresses but is there a way for the same to import names & numbers as well?
<html>
<head>
<meta name="robots" content="noindex" />
<title>Email address list - Import Gmail or Google contacts</title>
<style type="text/css">
a:link {color:Chocolate;text-decoration: none;}
a:hover {color:CornflowerBlue;}
.logo{width:100%;height:110px;border:2px solid black;background-color:#666666;}
</style>
</head>
<body>
<div class="logo" >
<a href="http://25labs.com/" >
<img style="padding-top: 10px;" src="http://25labs.com/wp-content/themes/TheStyle/images/logo.png"></img>
</a>
</div>
<br/>
<div><b>Visit Tutorial: </b><a style="font-size:17px;" href="http://25labs.com/import-gmail-or-google-contacts-using-google-contacts-data-api-3-0-and-oauth-2-0-in-php/" >Import Gmail or Google contacts using Google Contacts Data API 3.0 and OAuth 2.0 in PHP</a></div>
<br/>
<div style="padding-left: 50px;">
<?php
$client_id = '';
$client_secret = '';
$redirect_uri = '';
$max_results = 1000;
$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);
$accesstoken = $response->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 "<h3>Email Addresses:</h3>";
$xml = new SimpleXMLElement($xmlresponse);
$xml->registerXPathNamespace('gd', 'http://schemas.google.com/g/2005');
$result = $xml->xpath('//gd:email');
foreach ($result as $title) {
echo $title->attributes()->address . "<br>";
}
?>
</div>
</body></html>
This code uses ZF2 client but you can get the idea:
$client = new \Zend\Http\Client('https://www.google.com/m8/feeds/contacts/default/full?max-results=100000&alt=json', array(
'adapter' => 'Zend\Http\Client\Adapter\Curl'
));
$client->setHeaders(array(
array('Authorization' => 'Bearer ' . $ACCESS_TOKEN)
));
$client->send();
if ($client->getResponse()->getStatusCode() != 200) {
return false;
} else {
$output = json_decode($client->getResponse()->getBody());
if ($output) {
$entries = $output->feed->entry;
foreach ($entries as $e) {
print_r($e); // here you can see all the available information
}
}
}

Categories