curl isnt returning any hotmail contacts - php

I am trying to get my contacts from Hotmail. I made a script which used to work, but now it doesn't anymore. It does return a accesstoken, but no xml or json response. I am sure that I have the correct client-id and secret. I am using Google App Engine and even in the log of the Google App Engine Launcher no error appears, the console in my browser itself is also empty.
This is where I registered the application to get both the client id and secret: https://account.live.com/developers/applications/index
Hotmail development page:
oauth-hotmail.php:
<?php
//function for parsing the curl request
function curl_file_get_contents($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$client_id = '000000004018D847';
$client_secret = 'CfhxxxxxxxxxxxxxxxNPE';
$redirect_uri = 'http://localhost:11080/oauth-hotmail.php';
$auth_code = $_GET["code"];
$urls_ = 'https://login.live.com/oauth20_authorize.srf?client_id='.$client_id.'&scope=wl.signin+wl.basic+wl.emails+wl.contacts_emails+wl.contacts_birthday+wl.contacts_postal_addresses+wl.contacts_phone_numbers
&response_type=code&redirect_uri='.$redirect_uri;
echo 'Contact From MSN';
$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://login.live.com/oauth20_token.srf');
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);
$result = curl_exec($curl);
curl_close($curl);
echo $contents ;
$response = json_decode($result);
$accesstoken = $response->access_token;
//$accesstoken = $_SESSION['accesstoken'] ;//= $_GET['access_token'];
$url = 'https://apis.live.net/v5.0/me/contacts?access_token='.$accesstoken.'&limit='.$max_results;
$xmlresponse = curl_file_get_contents($url);
$contacts = json_decode($xmlresponse, true);
echo 'xmlresponse = '.$xmlresponse;
$return = array();
foreach($contacts['data'] as $contact)
{
$exploded = explode(".", $contact['id']);
$birthday = $contact['birth_day'].'-'.$contact['birth_month'];
if(!is_null($contact['phones']['personal'])){
$phoneNumber = $contact['phones']['personal'];
}elseif(!is_null($contact['phones']['mobile'])){
$phoneNumber = $contact['phones']['mobile'];
}elseif(!is_null($contact['phones']['business'])){
$phoneNumber = $contact['phones']['business'];
}else{
$phoneNumber = null;
}
$return[] = array (
'firstname'=> $contact['first_name'],
'lastname'=> $contact['last_name'],
'email' => $contact['emails']['preferred'],
'phoneNumber' => $phoneNumber,
'city' => $contact['addresses']['personal']['city'],
'street' => $contact['addresses']['personal']['street'],
'country' => $contact['addresses']['personal']['region'],
'birthday' => $birthday,
'id' => $exploded[1],
);
}
$hotmail_contacts = $return;
$hotmail_json = json_encode($return);
echo '<br><br><pre>';
echo $xmlresponse;
echo '</pre><br><br>';
?>
<table border='1' class="table table-striped table-condensed">
<thead>
<tr>
<th>Voornaam </th>
<th>Achternaam </th>
<th>Email </th>
<th>Telefoon </th>
<th>Stad </th>
<th>Adres </th>
<th>Land </th>
<th>Verjaardag </th>
<th>ID </th>
</tr>
</thead>
<tbody>
<?php
foreach ($hotmail_contacts as $contacts){
echo'<tr>';
echo'<td>'. $contacts['firstname']."</td>";
echo'<td>'. $contacts['lastname']."</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'<td>'. $contacts['birthday'].'</td>';
echo'<td>'. $contacts['id'].'</td>';
echo'</tr>';
}
?>
</tbody>
</table>
app.yaml:
application: famous-archway-127123
version: 1
runtime: php55
api_version: 1
handlers:
- url: /.*
script: oauth-hotmail.php
php.ini:
extension=php_curl.dll

Related

curl_exec to Mailchimp doesn't work when using AJAX

I've created a form in Wordpress that posts data to Mailchimp using the Mailchimp API. If I use just a regular form, with an action that goes to the appropriate page, it works fine; all the data imports as expected.
However, I want to do it via an AJAX POST command. I'm sending all the same information as when doing it using a traditional posted form, but it doesn't work. The AJAX success condition triggers to show that the page loaded successfully, so there must be something in that page that isn't working.
Here's my form:
<div class="card full">
<form id="mailchimp_actions" method="post" action="/ajax-curl-actions/">
<select name="action" id="action">
<option>Subscribe</option>
<option>Unsubscribe</option>
<option>Find</option>
</select>
<textarea name="import_data" id="import_data" placeholder="Email Address,First Name,Last Name"></textarea>
<input type="submit">
</form>
</div>
Here's the page it posts to:
<?php
// Template Name: AJAX - cURL actions.
$subscribers = bfm_data_format($_POST);
$final_report = array('successes'=>0,'failures'=>array());
foreach($subscribers as $subscriber) :
$post_data = array('email' => $subscriber[0], 'fname' => $subscriber[1], 'lname' => $subscriber[2]);
$action = $_POST['action'];
if(!bfm_subscriber_exists($subscriber[0]) && $action=='Subscribe') $action = 'Add New Subscriber';
$report = bfm_curl_actions(bfm_list_id(),bfm_api_key(),$post_data,$action);
if($report['success']) :
$final_report['successes']++;
else:
$final_report['failures'][] = $report['error'];
endif;
endforeach;
?>
<h1>Import Completed</h1>
<p><?=$final_report['successes']?> records were imported successfully.</p>
<h2>Failed imports</h2>
<table>
<tr>
<th>Email</th>
<th>Reason</th>
</tr>
<?php foreach($final_report['failures'] as $failure): ?>
<tr>
<td><?=$failure['email']?></td>
<td><?=$failure['message']?></td>
</tr>
<?php endforeach; ?>
</table>
Here are the various functions that make it work:
<?php
function bfm_fudge_timeout(){
$wpmetetxt = "
# WP Maximum Execution Time Exceeded
<IfModule mod_php5.c>
php_value max_execution_time 10000
</IfModule>";
$htaccess = ABSPATH .'/.htaccess';
$contents = #file_get_contents($htaccess);
if(!strpos($htaccess,$wpmetetxt))
file_put_contents($htaccess,$contents.$wpmetetxt);
}
add_action("after_switch_theme", "bfm_fudge_timeout");
// Format data
function bfm_data_format($data) {
$import_data = $data['import_data'];
$import_data_lines = explode("\n",$import_data);
$i=0;
foreach($import_data_lines as $import_data_line) :
$import_data_lines[$i] = explode(',',$import_data_line);
$i++;
endforeach;
return $import_data_lines;
}
// MailChimp data manipulation
function bfm_curl_actions($list_id,$api_key,$post_data,$action) {
$auth = base64_encode( 'user:'.$api_key );
$data = array(
'apikey' => $api_key,
'email_address' => $post_data['email'],
'merge_fields' => array(
'FNAME' => $post_data['fname'],
'LNAME' => $post_data['lname'],
)
);
if($action == 'Subscribe' || $action == 'Add New Subscriber') :
$data['status']='subscribed';
elseif($action == 'Unsubscribe'):
$data['status']='unsubscribed';
endif;
$member_id = md5($post_data['email']);
$json_data = json_encode($data);
$ch = curl_init();
$curlopt_url = "https://us7.api.mailchimp.com/3.0/lists/$list_id/members/";
if($action!='Add New Subscriber') $curlopt_url.=$member_id; // Member ID needs to be excluded if adding an entirely new person.
curl_setopt($ch, CURLOPT_URL, $curlopt_url);
if($action == 'Subscribe' || $action == 'Unsubscribe' || $action == 'Update') :
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH");
endif;
if($action == 'Find'):
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
endif;
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: Basic '.$auth));
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/3.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
$result = curl_exec($ch);
$status = "undefined";
$msg = "";
$myArray = json_decode($result, true);
foreach($myArray as $key => $value)
{
if( $key == "status" )
{
$status=$value;
}
else if ($key == "title")
{
$msg=$value;
}
}
$email = $post_data['email'];
if($action == 'Subscribe' || $action == 'Add New Subscriber'):
if($status == "subscribed") :
$report = array ('success'=>true,'error'=>'');
else:
$report = array ('success'=>false,'error'=>array('email'=>$email,'message'=>$msg));
endif;
endif;
return $report;
}
function bfm_subscriber_exists($email) {
$api_key = bfm_api_key();
$list_id = bfm_list_id();
$auth = base64_encode( 'user:'.$api_key );
$data = array(
'apikey' => $api_key,
'email_address' => $email,
);
$member_id = md5($email);
$json_data = json_encode($data);
$ch = curl_init();
$curlopt_url = "https://us7.api.mailchimp.com/3.0/lists/$list_id/members/$member_id";
curl_setopt($ch, CURLOPT_URL, $curlopt_url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: Basic '.$auth));
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/3.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
$result = json_decode(curl_exec($ch),true);
if ($result['status']=='404') return false;
return true;
die(' '); // Free up memory.
}
?>
All of the above works. Here's the jQuery I'm trying to use to do the same but via AJAX, and it fails.
// MailChimp Functions
$(document).on("submit","#mailchimp_actions",
function(event) {
event.preventDefault();
var import_data = $('#action').val();
var action = $('#import_data').val();
$.post("/ajax-curl-actions/",
{
import_data: import_data,
action: action
},
function () {
alert("All done!");
}
);
}
);
Solved it! I'd transposed the two variables in the AJAX request:
var import_data = $('#action').val();
var action = $('#import_data').val();
should have been:
var import_data = $('#import_data').val();
var action = $('#action').val();

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'],
);

My website won't show any contacts?

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>

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.

Categories