Am using https://github.com/googleapis/google-api-php-client/releases
Source File :https://github.com/googleapis/google-api-php-client/archive/v2.4.0.zip
to get User details like Username, email, profile picture, user ID, access token, refresh token so on and i was able to get all details with user authenticate permission and saved it to my database.
Google_config.php
require_once 'Google/autoload.php';
//require_once 'client.json';
session_start();
$client = new Google_Client();
$client->setApplicationName("Login with Google Account");
$client->setClientId('xxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com');
$client->setClientSecret('xxxxxxxxxxxxxxxxxxxxx');
$client->setRedirectUri('http://localhost:8000/ads/login/redirect.php');
//$client->setAuthConfig("client.json");
$client->addScope([
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile"
]);
$client->setAccessType('offline');
$client->setApprovalPrompt ("force");
Redirect.php
if (isset($_SESSION['accessToken'])) {
$client->setAccessToken($_SESSION['accessToken']);
} else if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$access_token = $client->getAccessToken();
$_SESSION['accessToken'] = $access_token;
} else {
header('location : index.php');
}
$oauth = new Google_Service_Oauth2($client);
if ($client->getAccessToken()) {
// Get user profile data from google
$gpUserProfile = $oauth->userinfo->get();
// Initialize User class
$user = new User();
// Getting user profile info
$gpUserData = array();
$gpUserData['oauth_uid'] = !empty($gpUserProfile['id']) ? $gpUserProfile['id'] : '';
$gpUserData['first_name'] = !empty($gpUserProfile['given_name']) ? $gpUserProfile['given_name'] : '';
$gpUserData['last_name'] = !empty($gpUserProfile['family_name']) ? $gpUserProfile['family_name'] : '';
$gpUserData['email'] = !empty($gpUserProfile['email']) ? $gpUserProfile['email'] : '';
$gpUserData['gender'] = !empty($gpUserProfile['gender']) ? $gpUserProfile['gender'] : '';
$gpUserData['locale'] = !empty($gpUserProfile['locale']) ? $gpUserProfile['locale'] : '';
$gpUserData['picture'] = !empty($gpUserProfile['picture']) ? $gpUserProfile['picture'] : '';
$gpUserData['link'] = !empty($gpUserProfile['link']) ? $gpUserProfile['link'] : '';
// Insert or update user data to the database
$gpUserData['oauth_provider'] = 'google';
$userData = $user->checkUser($gpUserData);
// Storing user data in the session
$_SESSION['userData'] = $userData;
// Render user profile data
if (!empty($userData)) {
$output = '<h2>Google Account Details</h2>';
$output .= '<div class="ac-data">';
$output .= '<img src="' . $userData['picture'] . '">';
$output .= '<p><b>Google ID:</b> ' . $userData['picture'] . '</p>';
$output .= '<p><b>Google ID:</b> ' . $userData['oauth_uid'] . '</p>';
$output .= '<p><b>Name:</b> ' . $userData['first_name'] . ' ' . $userData['last_name'] . '</p>';
$output .= '<p><b>Email:</b> ' . $userData['email'] . '</p>';
$output .= '<p><b>Gender:</b> ' . $userData['gender'] . '</p>';
$output .= '<p><b>Locale:</b> ' . $userData['locale'] . '</p>';
$output .= '<p><b>access token:</b> ' . $client->getAccessToken() . '</p>';
$output .= '<p>Click to visit Google+</p>';
$output .= '<p>Logout from Google</p>';
$output .= '</div>';
} else {
$output = '<h3 style="color:red">Some problem occurred, please try again.</h3>';
}
} else {
// Get login url
$authUrl = $client->createAuthUrl();
// Render google login button
$output = '<img src="images/google-sign-in-btn.png" alt=""/>';
}
?>
<div class="container">
<!-- Display login button / Google profile information -->
<?php echo $output; ?>
</div>
Now my problem is HOW DOES GOOGLE LOGIN WORKS Because when i use above method it get user authentication and then give back user info.
Where here in https://stackoverflow.com/ when i try to log-in i was able to login with google account with some redirect.
How do i do a login, tried many online solution and google document too.
Any solution would be helpfull.
finally a simple solution here:
if (isset($_GET['code'])) {
try {
$gapi = new GoogleLoginApi();
// Get the access token
$data = $gapi->GetAccessToken(CLIENT_ID, CLIENT_REDIRECT_URL, CLIENT_SECRET, $_GET['code']);
// Get user information
$user_info = $gapi->GetUserProfileInfo($data['access_token']);
} catch (Exception $e) {
echo $e->getMessage();
exit();
}
}
class GoogleLoginApi {
public function GetAccessToken($client_id, $redirect_uri, $client_secret, $code) {
$url = 'https://www.googleapis.com/oauth2/v4/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 GetUserProfileInfo($access_token) {
$url = 'https://www.googleapis.com/oauth2/v2/userinfo?fields=name,email,gender,id,picture,verified_email';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $access_token));
$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 get user information');
}
return $data;
}
}
Related
I want to link and view the analytics account linked with Google Adwords.
Procedure used:
Authenticating google account with scopes "Ananlytics and Adwords" with following url
https://www.googleapis.com/auth/adwords
https://www.googleapis.com/auth/analytics
After getting the authentication response creating Google analytics service object.
Google ads link API throwing error "Insufficient Premissions" screenshot attached
Script :
<?php
//function to authenticate google account and create analytics service object
function googleAuth(){
if (!empty($code)) {
$postFields = 'client_id=' . Configure::read('GOOGLE_OAUTH_CLIENT_ID') . '&client_secret=' . Configure::read('GOOGLE_OAUTH_CLIENT_SECRET') . '&code=' . $code . '&grant_type=authorization_code&redirect_uri=' . Configure::read('GOOGLE_OAUTH_REDIRECT_URI');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://accounts.google.com/o/oauth2/token');
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$Rec_Data = curl_exec($ch);
if (curl_exec($ch) === false) {
return $Rec_Data;
}
$Rec_Data = json_decode($Rec_Data, true);
if (isset($Rec_Data['refresh_token'])) {
try {
$credentials = array('client_id' => Configure::read('GOOGLE_OAUTH_CLIENT_ID'), 'client_secret' => Configure::read('GOOGLE_OAUTH_CLIENT_SECRET'), 'redirect_uris' => array(Configure::read('GOOGLE_OAUTH_REDIRECT_URI')));
$client = new \Google_Client($credentials);
$client->addScope(\Google_Service_Analytics::ANALYTICS_READONLY);
$client->setAccessToken($Rec_Data['access_token']);
// Create an authorized analytics service object.
$analytics = new \Google_Service_Analytics($client);
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
die();
}
}
} else {
if (!empty($id)) {
header("Location:https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=" . Configure::read('GOOGLE_OAUTH_CLIENT_ID') . "&redirect_uri=" . Configure::read('GOOGLE_OAUTH_REDIRECT_URI') . "&access_type=offline&approval_prompt=force&state=" . $id . "&scope=https://www.googleapis.com/auth/adwords https://www.googleapis.com/auth/analytics");
exit;
}
}
}
//function to fetch linked account list
function adwordsLinkAnalytics($analyticsAuth) {
$this->autoRender = false;
try {
$adWordsLinks = $analyticsAuth->management_webPropertyAdWordsLinks
->listManagementwebPropertyAdWordsLinks('123456', 'UA-123456-1');
} catch (apiServiceException $e) {
print 'There was an Analytics API service error '
. $e->getCode() . ':+' . $e->getMessage();
exit;
} catch (apiException $e) {
print 'There was a general API error '
. $e->getCode() . ':-' . $e->getMessage();
exit;
}
pr($adWordsLinks);
exit;
}
Required result: List of the analytics account linked with adwords account.
You are missing scope to management entities in Google Analytics, please look at this https://developers.google.com/identity/protocols/oauth2/scopes#analytics
Please update your scope with "https://www.googleapis.com/auth/analytics.edit"
My suggested Updates:
function googleAuth(){
if (!empty($code)) {
--------------
---- Your existing script ----
--------------
} else {
if (!empty($id)) {
header("Location:https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=" . Configure::read('GOOGLE_OAUTH_CLIENT_ID') . "&redirect_uri=" . Configure::read('GOOGLE_OAUTH_REDIRECT_URI') . "&access_type=offline&approval_prompt=force&state=" . $id . "&scope=https://www.googleapis.com/auth/adwords%20https://www.googleapis.com/auth/analytics%20https://www.googleapis.com/auth/analytics.edit");
exit;
}
}
}
Reference Url: https://developers.google.com/identity/protocols/oauth2/scopes#analytics
I am trying to use disqus login here: http://beta.perfectquiver.com/include/disqus/index.php
Also i set redirect URL : http://beta.perfectquiver.com/include/disqus/index.php in disqus configuration.
But it showing me error
Invalid parameter: redirect_uri (values for POST and GET arguments differ)" ["error"]=> string(13) "invalid_grant" }
After google it, someone said it is issue with mismatch of redirect URL, it should be identical.
But here its already identical.
Still same error.
Here id the code which i am using.
$PUBLIC_KEY = "PUBLIC_KEY";
$SECRET_KEY = "SECRET_KEY";
$redirect = urlencode("http://beta.perfectquiver.com/include/disqus/index.php");
$endpoint = 'https://disqus.com/api/oauth/2.0/authorize?';
$client_id = $PUBLIC_KEY;
$scope = 'read,write';
$response_type = 'code';
$auth_url = $endpoint.'&client_id='.$client_id.'&scope='.$scope.'&response_type='.$response_type.'&redirect_uri='.$redirect;
echo "<h3>Trigger authentication -> <a href='".$auth_url."'>OAuth</a></h3>";
$CODE = $_GET['code'];
if($CODE){
extract($_POST);
$authorize = "authorization_code";
$url = 'https://disqus.com/api/oauth/2.0/access_token/';
$fields = array(
'grant_type'=>urlencode($authorize),
'client_id'=>urlencode($PUBLIC_KEY),
'client_secret'=>urlencode($SECRET_KEY),
'redirect_uri'=>urlencode($redirect),
'code'=>urlencode($CODE)
);
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, "&");
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$data = curl_exec($ch);
curl_close($ch);
$auth_results = json_decode($data);
echo "<p><h3>The authentication information returned:</h3>";
var_dump($auth_results);
echo "</p>";
$access_token = $auth_results->access_token;
echo "<p><h3>The access token you'll use in API calls:</h3>";
echo $access_token;
echo "</p>";
echo $auth_results->access_token;
function getData($url, $SECRET_KEY, $access_token){
//Setting OAuth parameters
$oauth_params = (object) array(
'access_token' => $access_token,
'api_secret' => $SECRET_KEY
);
$param_string = '';
//Build the endpiont from the fields selected and put add it to the string.
//foreach($params as $key=>$value) { $param_string .= $key.'='.$value.'&'; }
foreach($oauth_params as $key=>$value) { $param_string .= $key.'='.$value.'&'; }
$param_string = rtrim($param_string, "&");
// setup curl to make a call to the endpoint
$url .= $param_string;
//echo $url;
$session = curl_init($url);
// indicates that we want the response back rather than just returning a "TRUE" string
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($session,CURLOPT_FOLLOWLOCATION,true);
// execute GET and get the session backs
$results = curl_exec($session);
// close connection
curl_close($session);
// show the response in the browser
return json_decode($results);
}
//Setting the correct endpoint
$cases_endpoint = 'https://disqus.com/api/3.0/users/details.json?';
//Calling the function to getData
$user_details = getData($cases_endpoint, $SECRET_KEY, $access_token);
echo "<p><h3>Getting user details:</h3>";
var_dump($user_details);
echo "</p>";
//Setting the correct endpoint
$forums_endpoint = 'https://disqus.com/api/3.0/users/listForums.json?';
//Calling the function to getData
$forum_details = getData($forums_endpoint, $SECRET_KEY, $access_token);
echo "<p><h3>Getting forum details:</h3>";
var_dump($forum_details);
echo "</p>";
}
This is the function in home_model.php (codeigniter application)
public function edit_google_contact_oauth($oldname,$oldphone,$oldtype, $newname, $newphone, $newtype)
{
$checkname = $oldname. '(' . $oldtype. ')';
$putname = $newname. '(' . $newtype . ')';
session_start();//start session
chdir(APPPATH.'libraries');
require_once('Google/autoload.php');
require('Google/Config.php');
require('Google/Google_Client.php');
chdir(FCPATH);
$client_id = '371163949109-o19u9mlm4d6d9gi59v9inj9jjje6c46s.apps.googleusercontent.com';
$client_secret = 'k9cE1eVSMN29pQzUO4ugWoUZ';
$redirect_uri = 'http://neighborhood.apptechclient.com/restaurant/index.php/home/customer';
$client = new Google_Client();
$client -> setApplicationName('contact');
$client -> setClientid($client_id);
$client -> setClientSecret($client_secret);
$client -> setScopes('https://www.google.com/m8/feeds');
$client -> setRedirectUri($redirect_uri);
$client -> setAccessType('online');
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location: ' . $redirect_uri);
}
if(!isset($_SESSION['token']))
{
$url = $client->createAuthUrl();
}else{
$client->setAccessToken($_SESSION['token']);
$token = json_decode($_SESSION['token']);
$token->access_token;
$curl = curl_init("https://www.google.com/m8/feeds/contacts/default/full?alt=json&max-results=1000&access_token=" . $token->access_token);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
$contacts_json = curl_exec($curl);
curl_close($curl);
$contacts = json_decode($contacts_json, true);
$return = array();
foreach($contacts['feed']['entry'] as $contact){
$return[] = array(
'id'=>$contact['id']['$t'],
'name' => $contact['title']['$t'],
'phone' => isset($contact['gd$phoneNumber'][0]['$t']) ? $contact['gd$phoneNumber'][0]['$t'] :false,
);
}
$count = -1;
$contactId;
foreach($return as $value) {
$count++;
if ((strcmp($value['name'], $checkname) == 0) && (strcmp($value['phone'], $oldphone) == 0)) {
$contactid=$value['id'];
}
}
}
}
I would like to update the contact details of the contact having id as $contactId by replacing that contact's name with $putname and contact's phoneNumber with $newphone.
I am looking at https://developers.google.com/google-apps/contacts/v3/#updating_contacts but I am not able to figure out what php code do I need to add to the function to make the update happen in google contacts.
Everything else is working fine. I am able to access the google contacts and retrieve the contacts and so on. I am using the google api php client.
I feel confused looking at https://developers.google.com/google-apps/contacts/v3/#updating_contacts. Please tell me the steps I need to take and what php code I need to add to successfully update the contact in Google Contacts. Thank you.
I am using Smart Debit Payment Gateway to do the payment from a website...
I am facing a error on submit through CURL,
Couldn't init Money from [nil, 8000]
Can you please tell me why i am having this issue, all the credentials are fine..
I.N: I am testing this on my local xampp server not online and also on test account not live account.:
Code i am using is :
<?php
$request_host = 'https://secure.ddprocessing.co.uk';
$request_path = '/api/ddi/variable/create';
$user = "myusername";
$password = "mypassword";
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_POST => true,
CURLOPT_USERPWD => $user . ":" . $password,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_HTTPHEADER => array("Accept: application/XML"),
CURLOPT_USERAGENT => $_SERVER['HTTP_USER_AGENT'], // Let SmartDebit see ho we are
);
$session = curl_init($request_host . $request_path);
curl_setopt_array( $session, $options );
// tell cURL to accept an SSL certificate if presented
if(ereg("^(https)", $request_host)) {
curl_setopt($session, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false);
}
// The request parameters
$pslid = 'pslidcode';
$payer_ref = 'XYZ-12345';
$first_name = 'John';
$last_name = 'Smith';
$address_1 = "123 Fake St";
$town = "London";
$postcode = "07666";
$country = "United State";
$account_name = "John Smith";
$sort_code = "40-12-23";
$account_number = "12345678";
$regular_amount = 1000;
$frequency_type = "M";
// urlencode and concatenate the POST arguments
$postargs = 'variable_ddi[service_user][pslid]=' . $pslid;
$postargs .= '&variable_ddi[payer_reference]=' . urlencode($payer_ref);
$postargs .= '&variable_ddi[first_name]=' . urlencode($first_name);
$postargs .= '&variable_ddi[last_name]=' . urlencode($last_name);
$postargs .= '&variable_ddi[address_1]=' . urlencode($address_1);
$postargs .= '&variable_ddi[town]=' . urlencode($town);
$postargs .= '&variable_ddi[postcode]=' . urlencode($postcode);
$postargs .= '&variable_ddi[country]=' . urlencode($country);
$postargs .= '&variable_ddi[account_name]=' . urlencode($account_name);
$postargs .= '&variable_ddi[sort_code]=' . urlencode($sort_code);
$postargs .= '&variable_ddi[account_number]=' . urlencode($account_number);
$postargs .= '&variable_ddi[regular_amount]=' . urlencode($regular_amount);
$postargs .= '&variable_ddi[frequency_type]=' . urlencode($frequency_type);
// Tell curl that this is the body of the POST
$smrtoutput = curl_setopt($session, CURLOPT_POSTFIELDS, $postargs);
// $output contains the output string
$output = curl_exec($session);
print_r($output);die;
$header = curl_getinfo($session);
// close curl resource to free up system resources
curl_close($session);
if(curl_errno($session)) {
echo 'Curl error: ' . curl_error($session);
}
else {
switch ($header["http_code"]) {
case 200:
echo "Variable DDI created";
break;
default:
echo "HTTP Error: " . $header["http_code"];
}
}
?>
Did Facebook just randomly change their API over the last couple of days? I had my site working perfectly with the Facebook API and now all of a sudden it doesn't work at all. No, I haven't changed anything, it literally just decided yesterday to not redirect anymore...it seems to just try to connect a few times and then it displays this page:
"The page isn't redirecting properly
Firefox has detected that the server is redirecting the request for this address in a way that will never complete.
* This problem can sometimes be caused by disabling or refusing to accept
cookies."
Anyway, here is some code to wrap your heads around :P (yes, I do actually have my real app id's and such in place)
This is the fbLogin_member.php file which is where you're directed after clicking on the Login link:
$app_id = "my id #";
$app_secret = "my secret id";
$my_url = "http://www.sitedomain.com/confirmlogin_fb_member.php";
if (empty($code)) {
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id=". $app_id ."&redirect_uri=". urlencode($my_url) ."&scope=email";
echo "<script> top.location.href='". $dialog_url ."'</script>";
}
$code = $_REQUEST['code'];
Here is the confirmlogin_fb_member.php file:
//if user denies access to your website, take him to your manual login page
// if ($_GET['error']) {
// header("Location: memberlogin.php");
// exit;
// }
require_once('config/dbconfig.php');
$app_id = "my id #";
$app_secret = "my secret id";
$my_url = "http://www.sitedomain.com/confirmlogin_fb_member.php";
$code = $_GET['code'];
$token_url = "https://graph.facebook.com/oauth/access_token?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&client_secret="
. $app_secret . "&code=" . $code;
// request access token
//use curl and not file_get_contents()
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $token_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$access_token = curl_exec($ch);
curl_close($ch);
$graph_url = "https://graph.facebook.com/me?" . $access_token;
// request user data using the access token
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $graph_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$temp_user = curl_exec($ch);
curl_close($ch);
//decode the json array to get user data
$user = json_decode($temp_user);
//store user data
$u = $user->name;
$e = $user->email;
$fb_id = $user->id;
$username = $user->username;
$picture = 'https://graph.facebook.com/'. $fb_id .'/picture';
//check if user has already signed up before
$insert = true;
$result = mysql_query("SELECT * FROM members") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
//if username already exists, do not insert
if (($row['name'] == $u) && ($row['userType'] == "facebook_user")) {
$insert = false;
}
}
// Random Password Generator
$chars = "abcdefghijkmnopqrstuvwxyz023456789";
srand((double)microtime()*1000000);
$i = 0;
$pass = '' ;
while ($i <= 7) {
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
// end generator
// if new user, insert user details in your mysql table
if ($insert) {
mysql_query("INSERT INTO members(name, fb_username, password, email, profile_pic, userType) VALUES('$u', '$username', '$pass' , '$e', '$picture', 'facebook_user')") or die(mysql_error());
}
//login user
if (!session_start()) session_start();
$_SESSION['in'] = true;
$_SESSION['userName'] = $u;
$_SESSION['userType'] = "facebook_user";
$_SESSION['userEmail'] = $e;
//take user to his/her homepage
header("Location: layout.php");
Lastly, here is the top of layout.php where the Facebook API session is called:
session_start();
require_once('config/dbconfig.php');
require_once('facebook/facebook.php');
if (isset($_REQUEST['logout'])) {
unset($_SESSION['in']);
unset($_SESSION['userName']);
unset($_SESSION['userType']);
unset($_SESSION['userEmail']);
session_destroy();
header("Location: layout.php");
}
$session = $_SESSION['in'];
if (!$session) {
$login = 'Login with Facebook';
$tooltipMsg = '<p>You must <strong>Log in</strong> to vote.</p>';
} else {
$sessionUser = $_SESSION['userName'];
$result = mysql_query("SELECT * FROM `members` WHERE name = '$sessionUser'") or die('Query failed: ' . mysql_error() . "<br />\n$sql");
if ($result) {
$sessionRow = mysql_fetch_array($result);
$sessionUserid = $sessionRow['memberid'];
}
if ($sessionRow['userType'] == "facebook_user") {
$facebook = new Facebook(array(
'appId' => 'my app id #',
'secret' => 'my secret id',
'cookie' => true
));
// $session = $facebook->getSession();
$user = $facebook->getUser();
$me = null;
// Session based API call.
if ($user) {
try {
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
// error_log($e);
}
}
}
It just boggles my mind that it has worked fine for a couple weeks, and now when I come back home from being gone a day and a half it doesn't work. Any help would be appreciated, even if there is some other things wrong you see with my coding (this is my first attempt with the facebook api) :)
It sounds like you might have an infinite redirect problem?
You are checking to see if $code is set before assigning it, try flipping the order of these two statements:
$code = $_REQUEST['code'];
if (empty($code)) {
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id=". $app_id ."&redirect_uri=". urlencode($my_url) ."&scope=email";
echo " top.location.href='". $dialog_url ."'";
}
You might need to change $_REQUEST to $_GET in protected function getCode() in base_facebook.php
protected function getCode() {
if (isset($_GET['code'])) {
if ($this->state !== null &&
isset($_GET['state']) &&
$this->state === $_GET['state']) {
// CSRF state has done its job, so clear it
$this->state = null;
$this->clearPersistentData('state');
return $_GET['code'];
} else {
self::errorLog('CSRF state token does not match one provided.');
return false;
}
}
return false;
}