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();
Related
I´m trying to create an event and that part works, but it will not for some reason send out the invitations / attendees in the calendar system with google API using PHP. It does create the event but that also it. So I hope someone can help me figuring out what I´m doing wrong.
myfile.php
// Event details
parameters = { title: $("#event-title").val(),
event_time: {
start_time: $("#event-type").val() == 'FIXED-TIME' ? $("#event-start-time").val().replace(' ', 'T') + ':00' : null,
end_time: $("#event-type").val() == 'FIXED-TIME' ? $("#event-end-time").val().replace(' ', 'T') + ':00' : null,
event_date: $("#event-type").val() == 'ALL-DAY' ? $("#event-date").val() : null
},
'attendees': [
{'email': 'test#dds-slagelse.dk'},
],
all_day: $("#event-type").val() == 'ALL-DAY' ? 1 : 0,
};
$("#create-event").attr('disabled', 'disabled');
$.ajax({
type: 'POST',
url: 'ajax.php',
data: { event_details: parameters },
dataType: 'json',
success: function(response) {
$("#create-event").removeAttr('disabled');
alert('Event created with ID : ' + response.event_id);
},
error: function(response) {
$("#create-event").removeAttr('disabled');
alert(response.responseJSON.message);
}
});
ajax.php file
session_start();
header('Content-type: application/json');
require_once('google-calendar-api.php');
error_log($_SESSION['access_token']);
try {
// Get event details
$event = $_POST['event_details'];
error_log(__LINE__);
$capi = new GoogleCalendarApi();
error_log(__LINE__);
// Get user calendar timezone
$user_timezone = $capi->GetUserCalendarTimezone($_SESSION['access_token']);
error_log(__LINE__);
// Create event on primary calendar
error_log($event['attendees0']);
$event_id = $capi->CreateCalendarEvent('primary', $event['title'], $event['all_day'], $event['event_time'], $event['attendees'], $user_timezone, $_SESSION['access_token']);
error_log(__LINE__);
echo json_encode([ 'event_id' => $event_id ]);
}
catch(Exception $e) {
error_log($e->getMessage());
header('Bad Request', true, 400);
echo json_encode(array( 'error' => 1, 'message' => $e->getMessage() ));
}
google-calendar.api.php
class GoogleCalendarApi
{
public function GetAccessToken($client_id, $redirect_uri, $client_secret, $code) {
$url = 'https://accounts.google.com/o/oauth2/token';
$curlPost = 'client_id=' . $client_id . '&redirect_uri=' . $redirect_uri . '&client_secret=' . $client_secret . '&code='. $code . '&grant_type=authorization_code';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
$data = json_decode(curl_exec($ch), true);
$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($http_code != 200)
throw new Exception('Error : Failed to receieve access token');
return $data;
}
public function GetUserCalendarTimezone($access_token) {
$url_settings = 'https://www.googleapis.com/calendar/v3/users/me/settings/timezone';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_settings);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$data = json_decode(curl_exec($ch), true); //echo '<pre>';print_r($data);echo '</pre>';
$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($http_code != 200)
throw new Exception($http_code);
return $data['value'];
}
public function GetCalendarsList($access_token) {
$url_parameters = array();
$url_parameters['fields'] = 'items(id,summary,timeZone)';
$url_parameters['minAccessRole'] = 'owner';
$url_calendars = 'https://www.googleapis.com/calendar/v3/users/me/calendarList?'. http_build_query($url_parameters);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_calendars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$data = json_decode(curl_exec($ch), true); //echo '<pre>';print_r($data);echo '</pre>';
$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($http_code != 200)
throw new Exception('Error : Failed to get calendars list');
return $data['items'];
}
//'primary', $event['title'], $event['all_day'], $event['event_time'], $event['attendees'], $user_timezone, $_SESSION['access_token']
public function CreateCalendarEvent($calendar_id, $summary, $all_day, $event_time, $event_attendees, $event_timezone, $access_token) {
$url_events = 'https://www.googleapis.com/calendar/v3/calendars/' . $calendar_id . '/events';
$curlPost = array('summary' => $summary);
if($all_day == 1) {
$curlPost['start'] = array('date' => $event_time['event_date']);
$curlPost['end'] = array('date' => $event_time['event_date']);
}
else {
$curlPost['start'] = array('dateTime' => $event_time['start_time'], 'timeZone' => $event_timezone);
$curlPost['end'] = array('dateTime' => $event_time['end_time'], 'timeZone' => $event_timezone);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_events);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token, 'Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($curlPost));
$data = json_decode(curl_exec($ch), true);
$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($http_code != 200)
throw new Exception($http_code);
return $data['id'];
}
}
I hope this make sense as I have tried so many attempts that I have lost track of it.
The Form Data that is send (after what i can figure out from google chrome is the following:
event_details[title]: Privat
event_details[event_time][start_time]: 2018-08-11T13:00:00
event_details[event_time][end_time]: 2018-08-11T15:30:00
event_details[event_time][event_date]:
event_details[attendees][0][email]: test#dds-slagelse.dk
event_details[all_day]: 0
ADyson, thanks for your help / hint. It was the missing curl that was the solution.
$curlPost['attendees'] = $event_attendees;
I hope it wont be to much of a bother, but it seems that it does not send out the invites for the events as hoped, even thought it does add the "guests" to the event.
The starting point for this solution is found here: http://usefulangle.com/post/29/google-calendar-api-create-event-php and if someone can please helt me to get * "sendNotifications"=>true * inserted or set correctly I would be very thankful. (would like to see how that parameter / function is set).
Best Regards
Jess
This help to me:
$curlPost['attendees'] = [['email'=>$event_data['attendees']]];
$curlPost['sendUpdates'] = array("sendUpdates"=>"all");
$curlPost['reminders'] = array('useDefault' => true, 'overrides' => array('method' => 'email','minutes' => 20));
This is the code:
$title = 'Du hast neue Nachricht';
$message = 'Besuch meine Website';
$url = 'https://www.bla.com';
$subscriberId = 'xxx51a002dec08a1690fcbe6e';
$apiToken = 'xxxe0b282d9c886456de0e294ad';
$curlUrl = 'https://pushcrew.com/api/v1/send/individual/';
//set POST variables
$fields = array(
'title' => $title,
'message' => $message,
'url' => $url,
'subscriber_id' => $subscriberId
);
$httpHeadersArray = Array();
$httpHeadersArray[] = 'Authorization: key='.$apiToken;
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $curlUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($ch, CURLOPT_HTTPSHEADER, $httpHeadersArray);
//execute post
$result = curl_exec($ch);
$resultArray = json_decode($result, true);
if($resultArray['status'] == 'success') {
echo $resultArray['request_id']; //ID of Notification Request
}
else if($resultArray['status'] == 'failure')
{
echo 'fail';
}
else
{
echo 'dono';
}
echo '<pre>';
var_dump($result);
echo '</pre>';
And I get:
dono
string(36) "{"message":"You are not authorized"}"
And nothing in the console and no other errors. The apitoken is 100% correct. What could be the trouble here? Do I have to wait till pushcrew decide to allow my website or something?
Ignore this: I must add some more text to ask this question..
There is typo here:
curl_setopt($ch, CURLOPT_HTTPSHEADER, $httpHeadersArray);
Correct is with
CURLOPT_HTTPHEADER
(without the S)
I've got a POST form on WordPress that I'm using to pass data to MailChimp via its API.
In and of itself (i.e. not using jQuery), it works as expected. However, when instead of using the form's action to navigate to a new page I try to pass the data via an AJAX post action, it only finds the first row of the multi line text box.
FORM
<?php
// Template Name: MailChimp Form
get_header();
?>
<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>
<?php get_footer(); ?>
PAGE THAT PROCESSES THE $_POST DATA
<?php
// Template: AJAX - cURL actions.
###############################################################################
# #
# Available options: #
# #
# Add New Subscriber - Create a new subscriber and add them to a list. #
# Subscribe - Add an existing email to the specified list. #
# Unsubscribe - Completely unsubscribe an email from all mailers. #
# Update - Change subscriber information. #
# #
###############################################################################
$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;
?>
FUNCTIONS
// 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.
}
This, as is, works as expected. The second page imports the data from the first into MailChimp.
However, if I try to do the same via AJAX by using the following jQuery, it still imports into MailChimp, but only the first line of the multi line text box is included; all other lines are ignored.
$(document).on("submit","#mailchimp_actions",
function(event) {
event.preventDefault();
var bfm_action = $('#action').val();
var bfm_import = encodeURIComponent($('#import_data').val());
console.log(bfm_action);
console.log(bfm_import);
$.post("/ajax-curl-actions/",
{
import_data: bfm_import,
action: bfm_action,
},
function () {
alert("Successful import.");
}
);
}
);
What am I missing? How do I get it to recognise all the lines in the textbox?
It seems the problem is caused by double-escaping your variables: Once by you and then again by jQuery when you send the key-value pairs as an object.
If you send key-value pairs to any of jQuery's ajax methods, jQuery takes care of the escaping for you so you can remove encodeURIComponent:
$(document).on("submit","#mailchimp_actions",
function(event) {
event.preventDefault();
var bfm_action = $('#action').val();
var bfm_import = $('#import_data').val();
^^^^^^^^^^^^^^^^^^^^^^^ here
console.log(bfm_action);
console.log(bfm_import);
...
Please try by changing this lines of code
function bfm_data_format($data) {
$import_data = nl2br(urldecode($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;
}
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'],
);
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>