I'm working on a script for post a message on a visitors wall. The visitor can enter there own message in a form en then send it to facebook.
index.php:
<form name="form" method="post" action="wall.php">
<textarea name="t_update" cols="50" rows="5" id="t_update" >message</textarea><br>
<input type="submit" name="Submit" value="Post To Your facebook Account!">
</form>
This sends "t_update" to "wall.php". The wall.php script is working fine I tested it with static text. but when I try to insert the "t_update" text into the var $APP_MSG it's empty when send to facebook. This is the complete wall.php script.
wall.php:
<?php
/** FB APP DATA **/
$FB_APPID = "Facebook app id";
$FB_SECRET = "Facebook secret code";
/** MSG DATA **/
$APP_MSG = ($_POST['t_update']); // post message
$APP_MSG_LINK_TITLE = "Title";
$APP_MSG_LINK = "www.domain.com";
global $ch;
$code = $_REQUEST["code"];
$error = $_REQUEST["error"];
$returnurl = "http://".$_SERVER["HTTP_HOST"].$_SERVER["SCRIPT_NAME"];
function facebook_curl_request($url,$params=array(),$post = false){
global $ch;
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt ($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11');
curl_setopt ($ch, CURLOPT_HEADER, false);
if($post == true){
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
}
$response = curl_exec ($ch);
$temp = json_decode($response,1);
if(isset($temp["error"]) && is_array($temp["error"])){
echo $temp["error"]["type"]."<br>";
echo $temp["error"]["message"]."<br>";
echo "--------------------------------------------";
curl_close ($ch);
exit;
}
return $response;
}
if(empty($code)) {
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id="
. $FB_APPID . "&redirect_uri=" . urlencode($returnurl) . "&scope=publish_stream,email";
header("Location: $dialog_url");
}
if(!empty($error)){
echo $_REQUEST["error"]."<br>".$_REQUEST["error_reason"]."<br>".$_REQUEST["error_description"];
}else{
if(!empty($code)){
/** CREATE TOKEN **/
$ch = curl_init();
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $FB_APPID . "&redirect_uri=" . $returnurl
. "&client_secret=" . $FB_SECRET . "&code=" . $code;
$token = facebook_curl_request($token_url);
$tarr = explode("&",$token);
list($token_name,$token) = explode("=",$tarr[0]);
/**GET USER INFO**/
$graph_url = "https://graph.facebook.com/me?".$token_name."=".$token;
$user = json_decode(facebook_curl_request($graph_url),1);
$userid = $user["id"];
/* POST TO WALL **/
$graph_url = "https://graph.facebook.com/".$userid."/feed";
$params = array(
$token_name => $token,
"message" => $APP_MSG,
'name' => $APP_MSG_LINK_TITLE,
'link' => $APP_MSG_LINK
);
$response = facebook_curl_request( $graph_url, $params, true);
list($userid,$postid) = explode("_",$response);
echo "<html><head></head><body>Bedankt voor het posten op facebook!</body></html>";
curl_close ($ch);
}
}
?>
I've tried everything can anybody point me in the right direction???
I did test the code and can confirm that it's not working. The reason its not is because when you first hit wall.php, you get redirected to Facebook to authenticate, it then redirects back to your application script "wall.php" with a GET - so you lose your POST variables on the redirect. That's why it ends up empty. Your other variables are still there because it's hard coded and will get called regardless when you run the script. Hope that makes sense.
I've just started working on an application and have found using the Facebook PHP SDK alot easier to work with. Code is much cleaner as well. The Dev area has a sample PHP file you can work with that shows you how to authenticate as well.
Example below:
<?php
require_once 'facebook-php-sdk/src/facebook.php';
$APP_MSG = ($_POST['t_update']);
$facebook = new Facebook(array(
'appId' => 'APPID',
'secret' => 'SECRET'
));
$wallArgs = array('message' => $APP_MSG);
try {
$facebook->api('me/feed', 'post', $wallArgs);
}
catch(Exception $e) {
print "<pre>";
print_r($e);
print "</pre>";
}
?>
You can also do this in HTML and JavaScript without requesting the users permission. First, initialize the Facebook API in your HTML page. Put this at the BOTTOM of the page, before the closing body tag.
<div id="fb-root"></div>
<script src="https://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId : '[your_app_id_goes_here];',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
</script>
Don't forget to replace [your_app_id_goes_here] with your Facebook App ID. Next, create a JS function that will post on the users wall. Put this in the head of the page.
<script>
// A function to post on the users wall
function wallPost() {
FB.ui(
{
method: 'feed',
name: 'Go find something!',
link: 'http://www.google.com',
picture: 'http://www.google.com/images/logos/ps_logo2.png',
caption: 'Google',
description: 'This was posted from a test app I created.',
message: ''
},
function(response) {
if (response && response.post_id) {
document.getElementById('message').innerHTML = 'Thanks for sharing!';
} else {
document.getElementById('message').innerHTML = 'Hey, you didn\'t share!';
}
}
);
}
</script>
Finally, use the function you just created in a link of some sort.
<p id="message">
Share Me!
</p>
This example is from my book Social App Development by Joel Dare. Get it at social.joeldare.com.
Related
I'm working in Facebook bot that replies to some comments (so far so good), yet at some point I need to renew the user authentification token (access_token), yet I still can't get it right. This is my webhook so far...yet I can't get the access token. I used 3 methods yet still nothing. How can I get the renew access token or how to get it with logic that I'm using? No FB SDK implemented so I rather would like to know a solution based on this code.
<?php
if(isset($_GET['hub_mode']) && isset($_GET['hub_challenge']) && isset($_GET['hub_verify_token'])){
if($_GET['hub_verify_token'] == '1234567890')echo $_GET['hub_challenge'];
}else{
$feedData = file_get_contents('php://input');
$data = json_decode($feedData);
$code = NULL;
//$code = $_REQUEST["code"]; //I Tried $_REQUEST yet I can't get the code value.
if (isset($_GET['code'])) { //I tried $_GET yet still no luck.
$code = $_GET['code'];
$app_id = 4444444444444444;
$my_url = 'https://example.com/robots/jotabot-comment-replier/fbwebhook.php';
$app_secret = 'ee....8';
$token_url="https://graph.facebook.com/oauth/access_token?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret
. "&code=" . $code . "&display=popup";
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
//KEEP GOING FROM HERE WITH TOKEN.
http_response_code(200);
return;
}
if($data->object == "page"){
$userMsg = $data->entry[0]->changes[0]->value->message;
$commentID = $data->entry[0]->changes[0]->value->comment_id;
$accessToken = "EAAKGo...AZDZD";
$url = 'https://graph.facebook.com/v15.0/me/messages?access_token='.$accessToken;
$reply = "Thanks for your comment";
$btn1 = array("type"=>"postback","title"=>"OPTION 1","payload"=>"BUDGET_10_PAYLOAD");
$btn2 = array("type"=>"postback","title"=>"OPTION 2","payload"=>"BUDGET_20_PAYLOAD");
$data = array("recipient"=>array("comment_id"=>$commentID),"message"=>array("attachment"=>array("type"=>"template","payload"=>array("template_type"=>"button","text"=>$reply,"buttons"=>[$btn1,$btn2]))));
$postdata = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response);
$errorCode = $data->error->code;
// If we had an error code that means that there is an authentification error.
if ($errorCode) {
$my_url = 'https://example.com/robots/jotabot-comment-replier/fbwebhook.php';
$token_url="https://graph.facebook.com/oauth/authorize?client_id=88884888&redirect_uri=".urlencode($my_url);
//If I put this URL with this parameters manually in my browser I successfully got the redirection with the code that I need:
//https://example.com/robots/jotabot-comment-replier/fbwebhook.php?code=AQS...Puw#_=_
//I tried 3 methods, JS (1st is how documentation suggests), file_get_contents and cURL.
//echo("<script> top.location.href='" . $token_url . "'</script>"); //I tried the way the documentation suggests, yet still no luck.
//$response = file_get_contents($token_url);
//$params = null;
//parse_str($response, $params);
//$access_token = $params['access_token']; //There's no $access_token
$url = $token_url;
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch); //I tried to catch the code after the redirection yet I can't.
curl_close($ch);
}
}
}
http_response_code(200);
You can't renew your User's access_token without going through Facebook Login flow.
That's why for your application it's better to use Page access_token which has no expiration date. You can read here how to obtain one
I'm working on Globe Labs API to send an SMS. But before I can send an SMS, the mobile number I want to send message to needs to be subscribed so I can get the access_token which will be used in sending SMS.
There are 2 options to subscribe - via SMS or via Web Form. I was able to use first option without any problem. But I can't make the second option work.
According to the documentation, after the subscriber keyed-in the received confirmation pin on the page and clicked the Confirm button to authorize the subscriber, the page will then be redirected to the redirect_uri of my application, and a Code parameter will be passed(via GET) to it.
Here's the part where I fail to make it work:
To get the access token, you need to do a POST request via https://developer.globelabs.com.ph/oauth/access_token with your ‘app_id’, ‘app_secret’ and ‘code’ as the parameters. The parameters ‘access_token’ and ‘subscriber_number’ will then be returned to your Redirect URI as a response.
Here's my code:
$app_id = '<my_app_id>';
$app_secret = '<my_app_secret>';
$content = array(
'app_id' => $app_id,
'app_secret' => $app_secret,
'code' => $this->input->get('code')
);
$url = 'http://developer.globelabs.com.ph/oauth/access_token';
$this->post_to_url($url, $content);
function post_to_url($url, $data) {
$fields = '';
foreach($data as $key => $value) {
$fields .= $key . '=' . $value . '&';
}
rtrim($fields, '&');
$post = curl_init();
curl_setopt($post, CURLOPT_URL, $url);
curl_setopt($post, CURLOPT_POST, count($data));
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($post);
curl_close($post);
if(!$result){
die('Error: "' . curl_error($post) . '" - Code: ' . curl_errno($post));
} else {
$this->Sms_Api_model->save_subscriber_data();
}
}
This is my redirect URL: http://api.forexcargo.us/sms_api/globelabs_api?code=[code]
And the result I get:
Error: "" - Code:
EDIT:
I tried to use a form and send my data via method POST and it worked. So it really might be my curl setup.
What am I doing wrong?
Any help is highly appreciated. Thank you!
Apologies for being a newbie regarding curl. Apparently, I had to add the following code to see the errors on my code because the URL I'm using has its error checking disabled:
error_reporting(-1);
ini_set('display_errors', 1);
set_time_limit(0);
And my new code:
function do_post_request($post_data)
{
error_reporting(-1);
ini_set('display_errors', 1);
set_time_limit(0);
$url = 'https://developer.globelabs.com.ph/oauth/access_token';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
// execute!
$response = curl_exec($ch);
// close the connection, release resources used
curl_close($ch);
// do anything you want with your response
if($this->json_validator($response) == 1){
$decode_data = json_decode($response, true);
$post_data_arr = array('access_token' => $decode_data['access_token'], 'subscriber_number' => $decode_data['subscriber_number']);
$this->Sms_Api_model->save_subscriber_data($post_data_arr);
//var_dump(http_response_code(200));
}
}
$content = [
'app_id' => $app_id,
'app_secret' => $app_secret,
'code' => $this->input->get('code')
];
$post_request = $this->do_post_request($content);
Now it's working and I was able to save the data I received in my database. Thank you everyone for your help!
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.
I try to login on steam using the following code.
steamcommunity.com/login/getrsakey first request is successful.
Request a steamcommunity.com/login/dologin/ all the time gives an error incorrect login.
Perhaps dealing with encryption password or need to add ssl.
I use to encrypt library on http://phpseclib.sourceforge.net/
function geturl($url, $ref, $cookie, $postdata, $header, &$info, &$output)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36');
if ($ref)
{
curl_setopt($ch, CURLOPT_REFERER, $ref);
}
if ($cookie)
{
curl_setopt($ch, CURLOPT_COOKIE, $cookie);
}
if ($postdata)
{
curl_setopt($ch, CURLOPT_POST, true);
$postStr = "";
foreach ($postdata as $key => $value)
{
if ($postStr)
$postStr .= "&";
$postStr .= $key . "=" . $value;
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $postStr);
}
curl_setopt($ch, CURLOPT_HEADER, $header);
$info = curl_getinfo($ch);
$output = curl_exec($ch);
curl_close($ch);
}
geturl("https://steamcommunity.com/login/getrsakey", null, null, array('username' => $login), 0, $info, $output);
$data = json_decode($output, true);
if ($data['success'] === true)
{
$publickey_exp = $data['publickey_exp'];
$publickey_mod = $data['publickey_mod'];
$RSA = new Crypt_RSA();
$RSA->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$n = new Math_BigInteger($publickey_mod, 16);
$e = new Math_BigInteger($publickey_exp, 16);
$key = array("modulus"=>$n, "publicExponent"=>$e);
$RSA->loadKey($key, CRYPT_RSA_PUBLIC_FORMAT_RAW);
$encryptedPassword = base64_encode($RSA->encrypt($password, false));
$captchaGid = -1;
$captchaText;
$emailAuth;
$emailSteamId;
$params = array(
'username' => $login,
'password' => $encryptedPassword,
'rsatimestamp' => $data['timestamp'],
'captcha_gid' => $captchaGid,
'captcha_text' => $captchaText,
'emailauth' => $emailAuth,
'emailsteamid' => $emailSteamId
);
geturl("https://steamcommunity.com/login/dologin/", null, null, $params, 0, $info, $output);
$data = json_decode($output, true);
var_dump($data);
if ($data['captcha_needed'])
{
$captchaGid = $data['captcha_gid'];
echo '<img src="https://steamcommunity.com/public/captcha.php?gid=' . $captchaGid . '">';
}
}
I think it would be better to use third-part libraries to auth.
Check this one: https://github.com/SmItH197/SteamAuthentication
It creates login button like "Sign in via Facebook".
EDIT: Steam has alsow his own API https://steamcommunity.com/dev
I can't be sure, but it looks like you are attempting to log a user into your site using Steam as the login method. Is this what you are attempting to do? If so, I recommend using the LightOpenID library.
<?php
require 'includes/lightopenid/openid.php';
$_STEAMAPI = "YOURSTEAMAPIKEY";
try
{
$openid = new LightOpenID('http://URL.TO.REDIRECT.TO.AFTER.LOGIN/');
if(!$openid->mode)
{
if(isset($_GET['login']))
{
$openid->identity = 'http://steamcommunity.com/openid/?l=english'; // This is forcing english because it has a weird habit of selecting a random language otherwise
header('Location: ' . $openid->authUrl());
}
?>
<form action="?login" method="post">
<input type="image" src="http://cdn.steamcommunity.com/public/images/signinthroughsteam/sits_small.png">
</form>
<?php
}
elseif($openid->mode == 'cancel')
{
echo 'User has canceled authentication!';
}
else
{
if($openid->validate())
{
$id = $openid->identity;
// identity is something like: http://steamcommunity.com/openid/id/76561197960435530
// we only care about the unique account ID at the end of the URL.
$ptn = "/^http:\/\/steamcommunity\.com\/openid\/id\/(7[0-9]{15,25}+)$/";
preg_match($ptn, $id, $matches);
echo "User is logged in (steamID: $matches[1])\n";
// $matches[1] is the profile ID you will want to use for additional API calls
}
else
{
echo "User is not logged in.\n";
}
}
}
catch(ErrorException $e)
{
echo $e->getMessage();
}
?>
At the end of this login, you will have the user's profile ID (ie. 76561197960435530) which you can use against many of the API's that Steam provides to gather further information on the player.
Use "urlencode()" function
$encryptedPassword = urlencode(base64_encode($RSA->encrypt($password, false)));
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
}
}
}