I am doing login and fetching albums from facebook:
1) Here, first of all the function $facebook->getUser() returning 0
2) If I commented the rest of code i.e. if/else conditions then it going into the catch block and showing exception like :
Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user.
3) I found lots of posts on stackoverflow and google regarding to this and tried almost all but still its not working. Thats why I am sharing the code here.
4) Also I created the new app facebook and tried for it but still problem persist.
Following is my code :
public function facebookapiAction() {
require 'auth/src/facebook.php';
$facebook = new Facebook(array(
'appId' => '3xxxxxxxxxxxxxxxxxxxx7',
'secret' => '6xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx5',
'cookie' => true,
));
return $facebook;
}
public function facebookalbumAction() {
$session = new Zend_Session_Namespace('user');
$facebook = $this->facebookapiAction();
$access_token = $facebook->getAccessToken();
$facebook->setAccessToken($access_token);
$user = $facebook->getUser();
$albumid = $this->_getParam('albumid');
if ($user <> '0' && $user <> '') {
if ($albumid != "") {
$photos = $this->albumlistAction($albumid, $facebook);
} else {
try {
$albumArrInfo = array();
$user_profile = $facebook->api('/me/albums');
} catch (FacebookApiException $e) {
error_log($e);
exit;
}
}
$session->fb_logout = $facebook->getLogoutUrl(array('next' => "http://{$_SERVER['HTTP_HOST']}/register/logout/id/Logout"));
$session->isfb = 1;
} else {
if (isset($_REQUEST['getfurl']) && !(isset($_REQUEST['state']))) {
$loginUrl = $facebook->getLoginUrl(array('display' => 'popup','scope' => 'manage_pages,user_events,email,read_stream,user_photos,offline_access'));
echo $loginUrl;
exit;
}
}
}
public function albumlistAction($albumid, $facebook) {
$photos = $facebook->api("/{$albumid}/photos");
$albumArr = array();
$albumArrInfo = array();
foreach ($photos['data'] as $photo) {
$albumArr['id'] = $photo['id'];
$albumArr['name'] = $photo['name'];
}
return $albumArr;
}
Whats wrong with this code.
Need help.
Sounds like a similar problem I was facing. Bug report is here: http://developers.facebook.com/bugs/238039849657148
Try updating to the latest version of the PHP-SDK (3.2.2).
Try this:
$user = $facebook->getUser();
...
$user_profile = $facebook->api('/'.$user.'/albums');
Related
I have a little problem with my integration with Facebook PHP SDK on my website. On desktop everything works fine. When try to register account using fb-login button on mobile devices despite the successful redirection from the facebook website to my website, it receives an empty response.
I don't know where is the main problem, session, redirects policy, cookie problem?
The problem does not exist when accounts are merged and connected - so login function works on mobile, just creating account and connecting new ids.
I note that everything works fine on the desktop version
my config
Facebook PHP SDK: 5.6.2
Graph API: v14.0
$config = array_merge([
'app_id' => getenv(static::APP_ID_ENV_NAME),
'app_secret' => getenv(static::APP_SECRET_ENV_NAME),
'default_graph_version' => static::DEFAULT_GRAPH_VERSION,
'enable_beta_mode' => false,
'http_client_handler' => null,
'persistent_data_handler' => 'memory',
'pseudo_random_string_generator' => null,
'url_detection_handler' => null,
], $config);
You can see the code implementations below
public function _facebook_account($action = null){
$isLogged = $this->getCustomer()->isAuthenticated();
$fb = FacebookAPIHelper::getInstance()->getAPI($this->getContext());
$redirectUrl = null;
if (!empty($_POST['secret_code']))
{
$code = $_POST['secret_code'];
}
if (!$isLogged) {
if ($action == FacebookAPI::ACTION_LOGIN || $action == FacebookAPI::ACTION_REGISTER){
$redirectUrl = '/customer/login_with_facebook/' . $action;
}
}
else{
if ($action == FacebookAPI::ACTION_MERGE) {
$redirectUrl = '/customer/merge_with_facebook';
}
else {
$this->redirectTo('customer,profile');
}
}
if (!is_null($redirectUrl)) {
$url = $fb->getLoginUrl($this->getRouter()->getHost(null, true) . $redirectUrl, isset($code) ? $code : null);
header("Location: $url");
}
else {
$this->redirectTo('');
}
}
2
try {
$facebookProfileData = FacebookLoginHelper::getFacebookProfileData($this->getContext());
if ($facebookProfileData) {
$customer = FacebookLoginHelper::findOrCreateCustomerByFacebookProfileData($facebookProfileData);
} else {
$this->addMessageForNextRequest('`facebook_login.error_fetch_user_data`');
$this->redirectTo('customer,login');
}
if (is_null($customer)) {
$customer = CustomerBase::getCustomerFromFacebookProfileData($facebookProfileData);
if (Module::moduleInstalled('referer')) {
if ($this->hasCookie(RefererSettings::COOKIE_NAME)) {
$referer = $this->getCookie(RefererSettings::COOKIE_NAME);
$customer->referer = $referer;
}
}
$this->view->customer = $customer;
$this->renderAction('confirm_customer_data.tpl');
}
3
public function _login_with_facebook($action)
{
$customer = null;
$oldCustomer = $this->getCustomer();
$isLogged = $oldCustomer->isAuthenticated();
$facebookLoginNotInstalled = Module::moduleInstalled('facebook_login') == false;
if ($isLogged) {
$this->redirectTo('customer,profile');
return;
}
if ($facebookLoginNotInstalled) {
$this->redirectTo('customer,login');
return;
}
try {
$facebookProfileData = FacebookLoginHelper::getFacebookProfileData($this->getContext());
if ($facebookProfileData) {
$customer = FacebookLoginHelper::findOrCreateCustomerByFacebookProfileData($facebookProfileData);
} else {
$this->addMessageForNextRequest('`facebook_login.error_fetch_user_data`');
$this->redirectTo('customer,login');
}
if (is_null($customer)) {
$customer = CustomerBase::getCustomerFromFacebookProfileData($facebookProfileData);
if (Module::moduleInstalled('referer')) {
if ($this->hasCookie(RefererSettings::COOKIE_NAME)) {
$referer = $this->getCookie(RefererSettings::COOKIE_NAME);
$customer->referer = $referer;
}
}
$this->view->customer = $customer;
$this->renderAction('confirm_customer_data.tpl');
i am using FB SDK v.3.2.3 , and i'm trying to retrieve the events that my friends are going to. So far, my code can retrieve the list of friends who are using my app. The documentation on FB tells the event can be pulled out by using "me/events", but since i want my friend's event to be pulled, i used "me/friends/event" or "me/friends?fields=event", but it still does not work. Someone has an idea about it? Below is my code --
<pre>
require_once('facebook.php');
$config = array(
'appId' => 'xxx',
'secret' => 'xxx'
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
if($user_id) {
try {
$user_profile = $facebook->api('/me','GET');
echo "<pre>";
print_r($user_profile);
echo "</pre>";
$dost = $facebook->api('/me/friends','GET');
foreach ($dost as $friend) {
echo "<pre>";
print_r($friend);
echo "</pre>";
}
echo '<br><a href=' . $facebook->destroySession() . '>Logout</a>';
} catch(FacebookApiException $e) { }
} else {
$params = array(
'scope' => 'public_profile, user_friends, email',
'redirect_url' => 'http://xxxxx.com',
'auto_logout_link' => 'true',
'show_faces' => 'true'
);
$login_url = $facebook->getLoginUrl($params);
echo 'Please login.';
}
Try it:
//...
$dost = $facebook->api('/me/friends','GET');
foreach ($dost["data"] as $value) {
$friend_id = $value['id'];
$events = $facebook->api('/'.$friend_id.'/events');
print_r($events);
}
//...
Facebook changed the privacy policy for friends - your friends also need to give permission to your app
I am trying to access and update a file in my Google Drive with PHP. Everything goes fine until I try to call $file_to_update->setTitle("NEW TITLE").
I can download the file's metadata, but I can't update anything.
require_once 'google-api-php-client/Google_Client.php';
require_once 'google-api-php-client/contrib/Google_DriveService.php';
$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('');
$client->setClientSecret('');
$client->setRedirectUri('');
$client->setScopes(array(''));
$service = new Google_DriveService($client);
$authUrl = $client->createAuthUrl();
//Request authorization
print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";
$authCode = trim(fgets(STDIN));
// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);
retrieveAllFiles($service);
function retrieveAllFiles($service) {
$result = array();
$pageToken = NULL;
do {
try {
$parameters = array();
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$files = $service->files->listFiles($parameters);
$fileIDs = array();
$file = ($files[items]);
foreach($file as $f){
array_push($fileIDs, $f["id"]);
print $f["id"]."\n";
}
$str = $fileIDs[1];
$file_to_update = $service->files->get($str);
$file_to_update->setTitle("NEW TITLE");
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
return $result;
}
Your call to $service->files->get($str) is not returning object.
if you check at function:
public function get($fileId, $optParams = array()) {
$params = array('fileId' => $fileId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Google_DriveFile($data);
} else {
return $data;
}
}
It checks if you want to work with objects, or not:
$this->useObjects()
You need to configure 'use_objects' to 'true' in your api config.php file, it is set to 'false' by default.
'use_objects' => false,
I know this is a duplicate, however, I've tried pretty much everything suggested in the other questions.
I'm currently getting a redirect loop because getUser is always returning 0, even after approving the app.
Code:
public function auth() {
$user = $this->facebook->getUser();
if ($user) {
$user = $this->facebook->api('/me');
if (!$this->Users->getByID($user["id"])) {
$this->data->needsRegister = true;
} else {
$toSetInSessions = new stdClass();
$toSetInSessions->authed = 1;
$dbUser = $this->Users->getByID($user["id"]);
foreach ($dbUser as $key => $value) {
$toSetInSessions->user->$key = $value;
}
$this->session->set_userdata($toSetInSessions);
redirect("/");
}
} else {
$params = array('scope' => 'email,read_friendlists');
if ($_SERVER['HTTP_USER_AGENT'] != "facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)") {
redirect($this->facebook->getLoginUrl($params));
}
}
$this->load->view('header', $this->data);
$this->load->view('auth', $this->data);
$this->load->view('footer', $this->data);
}
Here is the screenshot of my settings page for this App.
https://dl.dropbox.com/u/6647629/facebookapp.png
Sometimes it does work, but most of the time it doesn't.
Found the solution here: http://www.galalaly.me/index.php/2012/04/using-facebook-php-sdk-3-with-codeigniter-2-1/
Had to add:
parse_str($_SERVER['QUERY_STRING'], $_REQUEST);
I created a Facebook page, added a new Tab with an application.
Now I want todo these steps:
See if User liked the page // Is Working
Ask for permissions to post a status // Isn't working
Finish.
This is the code which I use:
$permissions = array (
'email',
'user_status',
'publish_stream',
'status_update'
);
public function __construct($app_id, $secret, $perm)
{
$this->facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $secret,
'cookie' => true
));
$this->perm = $perm;
}
public function checkPermissions()
{
$allPerm = true;
$permissions = $this->facebook->api("/me/permissions");
foreach($this->perm as $value)
{
if(!array_key_exists($value, $permissions['data'][0]) ) {
$allPerm = false;
}
}
return $allPerm;
}
public function RequestPermissions()
{
header( "Location: " . $this->facebook->getLoginUrl($this->GenerateScope()) );
}
public function GenerateScope()
{
$scope = null;
$last_key = array_keys($this->perm);
$last_key = end($last_key);
foreach ($this->perm as $key => $value) {
if ($key == $last_key) {
$scope .= $value;
} else {
$scope .= $value . ',';
}
}
return array("scope" => $scope);
}
So, I check for the Permissions, if not all are set, I want to ask for them.
$this->facebook->getLoginUrl($this->GenerateScope()).
But when i display the link, or redirect to it, nothings (really nothing) happens?
Your tab application is operating within an iframe element on facebook.com. To redirect users to a different URL, you'll have to change the top most frame's location.
This is possible using JavaScript, so all you have to do is get your PHP code to echo out this JavaScript code -
$url = $facebook->getLoginUrl(...your_params...);
echo "<script language=javascript>";
echo "top.location.href ='".$url."';";
echo "</script>";
exit();
That will execute the redirect for your users.