I have the follow code to login with Facebook:
// Include Facebook SDK
$this->facebook = new Facebook(array(
'appId' => 'APP ID',
'secret' => 'APP SECRET',
'cookie' => true
));
$uid = $this->facebook->getUser();
if($uid) {
try {
echo 'Done!';
} catch (FacebookApiException $e) {
echo $e;
error_log($e);
}
} else {
$loginUrl = $this->facebook->getLoginUrl(array(
'redirect_uri' => 'http://ogabrielsantos.com.br/dev/index.php?route=account/connect/facebook',
'scope' => 'user_birthday'
));
echo('<script>top.location.href = "' . $loginUrl . '";</script>');
}
UPDATE 1
I can authorize the App, but, after authorization, I can't get the logged user, EVER redirecting to
http://ogabrielsantos.com.br/dev/index.php?route=account%2Fconnect%2Ffacebook&state=RANDOM STATE&code=RANDOM CODE#_=_
I have tried:
Put the APP in a server;
Verify APP settings. All is correct;
Verify if url is the same at settings and code. All is ok;
My url is properly written: http://ogabrielsantos.com.br/dev/index.php?route=account/connect/facebook;
Reset APP SECRET.
Nothing worked.
You can check what happens going to:
http://ogabrielsantos.com.br/dev/index.php?route=account/connect/facebook
Facebook ask you to authorize the app to get your website, which is a safe information.
UPDATE 2
The follow code:
$this->facebook = new Facebook(array(
'appId' => $this->connect->config->get('facebook_api_key'),
'secret' => $this->connect->config->get('facebook_app_secret'),
'cookie' => true
));
$uid = $this->facebook->getUser();
echo'<pre>';
print_r($this->facebook);
echo'</pre>';
exit;
returns:
Facebook Object
(
[sharedSessionID:protected] =>
[appId:protected] => APP ID
[appSecret:protected] => APP SECRET
[user:protected] => 0
[signedRequest:protected] =>
[state:protected] =>
[accessToken:protected] => APP ID|APP SECRET
[fileUploadSupport:protected] =>
[trustForwarded:protected] =>
)
I think the accessToken is wrong, returning my APP ID and SECRET with a pipeline separator.
UPDATE 3:
Now, I verify the code, but, always get Fatal error: Uncaught OAuthException: Error validating verification code
if(isset($_GET['code'])) {
$api = $this->facebook->api('/oauth/access_token', array(
'client_id' => APP ID,
'redirect_uri' => 'http://ogabrielsantos.com.br/dev/index.php?route=account/connect/facebook',
'client_secret' => APP SECRET,
'code' => $_GET['code']
));
echo'<pre>';
var_dump($api);
print_r($this->facebook->getUser());
echo'</pre>';
exit;
}
I have read some questions, which is similar but can't help-me.
Are you working on localhost? if yes it probably is the reason why.
If not, check your app settings in developers.facebook.com/apps/APP_ID
1. You have to compare the urls written in your code with the ones you have in your app settings.
2. Another reason could be the that the urls in you app settings are not properly written, I remember having to add index.php at the end of my urls in Page Tab settings. Worked for me
3. Another option is to get a new APP_SECRET and update your code
These options are from my personal experience, you issue could also be something else but you lose nothing trying
The Facebook Sharing and Facebook Sign In functions are completely separate and each require their own app.
Are you using facebook sharing in the page you want the login working on?
Ref: http://www.ning.com/help/?p=8523
Related
I'm using https://github.com/pocesar/facebook-kohana for facebook login. I have problem with facebook logout. It doesn't destroy facebook session. I've tried so many things and I've read many questions. I tried this in my logout method, but no result:
$this->redirect('https://www.facebook.com/logout.php?
next=mysite.dev
&access_token=USER_ACCESS_TOKEN');
My logout method is:
public function action_logout(){
$facebook = new Facebook(array(
'appId' => 'appId',
'secret' => 'mySecret',
));
$user = $facebook->getUser();
$facebook->destroySession();
Session::instance()->delete('user');
$this->redirect('/');
}
How to destroy session, so that user can log in my site with another facebook account? Thanks!
My method login is:
public function action_fbLogin(){
$facebook = new Facebook(array(
'appId' => 'appId',
'secret' => 'Secret',
));
$user = $facebook->getUser();
if ($user) {
$user_profile = $facebook->api('/me', array('fields' => 'id,email,name,first_name,last_name,picture'));
$user_id = Model_UserFunctions::checkIfUserExist($user_profile['email']);
if($user_id > 0)
{
Session::instance()->set('user', array(
'fb_id' => $user_profile['id'],
'user_id' => $user_id,
'pic' => $user_profile['picture'],
'email' => $user_profile['email'],
'first_name' => $user_profile['first_name'],
'last_name' => $user_profile['last_name'],
));
//var_dump($_SESSION);
$this->redirect('profile');
exit;
}
$values = array(
'email' => $user_profile['email'],
'username' => $user_profile['email'],
'password' => '12345678'
);
$user = ORM::factory ( 'User' );
$user->values($values);
try
{
if($user->save()){
$user_new_id = $user->as_array();
$user_new_id = $user_new_id['id'];
Session::instance()->set('user', array(
'fb_id' => $user_profile['id'],
'user_id' => $user_new_id,
'pic' => $user_profile['picture'],
'email' => $user_profile['email'],
'first_name' => $user_profile['first_name'],
'last_name' => $user_profile['last_name'],
));
$this->redirect('profile');
}
}
catch (ORM_Validation_Exception $e)
{
$result = $e->errors('models');
echo '<pre>';
print_r($result);
exit;
}
}
else
{
$this->redirect($facebook->getLoginUrl(array('id,email,name,first_name,last_name,picture')));
}
exit;
}
Edited: My goal to use Facebook logout is because in my site I only use Facebook login, there isn't another way to log in my site, that's idea of it. And I should have logout method in my site, so when user wants to logout, he could do it.
This logouts me from facebook but facebook login page is shown. How to redirect next to my site. I've set it as next but it doesn't redirect to it:
<a href="https://www.facebook.com/logout.php?
next=http://mysite.dev
&access_token=Null">Logout</a>
You can get facebook logout url using facebook-php-sdk API.
When user will click on that url he will be offline from his facebook account.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
For more info you can check this url.
https://github.com/facebookarchive/facebook-php-sdk
Then you don't have a problem with facebook
Is only the session that needs to be destroyed...
On this page of PHP manual there is an example showing you might need aditional steps to destroy a session beyond unset($_SESSION)
http://php.net/manual/en/function.session-destroy.php
Forcing the users to log off from Facebook does not seem a good move for me.
Millions of FB users have intentionally asked to stay logged in and if they visit your site and logoff from there they might think it wasn't very friendly of you to log them off the FB accounts. many don't even remember their pwd... so you would be creating a problem for them and they might never comeback to your site... Just saying
I'm trying to add an event to a page in the name of the page. I'm the admin of the page and I found a lot of stuff to the topic, but, no matter what I do, it ends in the PHP Exception:
Uncaught Exception: You must be an admin of the specified page to perform the requested action.
I can add events with my app in my own profile. So, I think the problem is the Access Token. I tried several ways, but to me the best way seems to be:
Open the Graph API Explorer
Select my Application
Request a new access code with permissions manage_pages, publish_actions, publish_stream, create_event
Request /me/accounts
Get the access_token from the page I want to post to and use it in my script
My test script, that works in my own profile:
require 'src/facebook.php';
$facebook = new Facebook(array(
'appId' => $APPLICATION_ID,
'secret' => $APPLICATION_SECRET,
'cookie' => false,
'fileUpload' => true
));
$event_id = 0;
$event_name = "New Event API Test Event";
$event_start = '2013-12-04';
$event_privacy = "OPEN";
$ret_obj = $facebook->api('/'.$page_id.'/events?access_token='.$access_token, 'POST',
array(
'name' => $event_name,
'start_time' => $event_start,
'privacy_type' => $event_privacy,
'location_id' => $location_id
));
if(isset($ret_obj['id'])) {
echo 'Event with added. ID: ' . $ret_obj['id'];
} else {
echo 'Couldn\'t create event';
}
What I did wrong?
You need a page access token.
Page Access Token – These access tokens are similar to user access
tokens, except that they provide permission to APIs that read, write
or modify the data belonging to a Facebook Page. To obtain a page
access token you need to start by obtaining a user access token and
asking for the manage_pages permission. Once you have the user access
token you then get the page access token via the Graph API.
Doc: https://developers.facebook.com/docs/facebook-login/access-tokens/
Then use GET /me/accounts to get the access token associated to your page.
I found the solution in How to programmatically add an event to a page using Graph API?. I had to add the access_token direct into the event array and everything works as expected:
$ret_obj = $facebook->api('/'.$page_id.'/events', 'POST',
array(
'access_token' => $access_token,
'name' => $event_name,
'start_time' => $event_start,
'privacy_type' => $event_privacy,
'location_id' => $location_id
));
Thanks for the help!
I'm trying to create a script that post status updates on facebook pages without logging-in the user. I've got access_token for my application and for the pages as the user granted the application once; but I always get the error
Fatal error: Uncaught OAuthException: (#200) The user hasn't authorized the application to perform this action
despite I've granted manage_pages and publish_stream permission.
Also if I use the access_token for the page I get the error
Fatal error: Uncaught OAuthException: Error validating access token: The session is invalid because the user logged out.
Here is the code I use.
$facebook = new Facebook(array(
'appId' => 'XXX',
'secret' => 'XXXXXXXXXXX'
));
$post = array(
'message' => 'Message to user'/*,
access_token = "XXXXXXXX"*/
);
$feed = '/[PAGE_ID]/feed';
$post_id = $facebook->api($feed, "post", $post);
Thanks.
Edit :
I finally managed to post status updates on a user's page while this user was disconnected, I had to generate the access_token through the server-side auth method.
Below is a small code smaple on how to do a FB post to a page:
yOU NEED:
Your_authToken_for_User
List item
saved_fb_Page_Token
$facebook = $facebook = new Facebook(array(
'appId' => $fbAppId,
'secret' => $fbAppSecret,
'cookie' => true,
));
$facebook->setAccessToken("Your_authToken_for_User");
//Now your FB instance is authenticated.
$pages= $facebook->api('/me/accounts'); //use the current authenticated FB instance to grab Pages. If you already know your page ID , skip this.
//Assuming you have a pageid in $page_id,(the $page_id can be grabbed from the $pages array).
$attachment = array(
'access_token' => $saved_fb_Page_Token,
'message' => "foo",
'name' => "Bar",
'link' => "http://foo.bar",
'description' => "barfoo",
'picture' => "an image url here",
);
$facebook->api('/' . $page_id . '/feed', 'POST', $attachment);//post to fb page
I know this error has been bitten to death over here, and I read every single one to have better understanding of my problem.
But my issue is a bit different, and I wonder if anyone can give me good suggestion where to look.
I'm using wordpress + wordpress social login. This plugin authenticates user and stores name/age/email/fbID/fbProfilePic in the DB.
I've a little feature on my website where users registered through facebook can click and post message to the their wall.
My code looks like this:
<?php
//IF user is registered via facebook, when he clicks INTERESTED message will appear on his/her wall to spread the news
$user = get_user_meta($current_user->ID,'Facebook',true);
if ($user && $_GET['commentstab'] == 1 && !$_POST['delmycom']) {
require ('Facebook/facebook.php');
//Access details
$facebook = new Facebook(array(
'appId' => 'XXX',
'secret' => 'XXX'
//'cookie' => true
));
//try {
$params = array(
'message' => "Hurray! This works :)",
'name' => "This is my title",
'caption' => "My Caption",
'description' => "Some Description...",
'link' => "http://stackoverflow.com",
'picture' => "http://i.imgur.com/VUBz8.png",
);
$post = $facebook->api("/$user/feed","POST",$params);
echo "Your post was successfully posted to UID: $user";
//} //try
//catch (FacebookApiException $e) {
// $result = $e->getResult();
//} //catch
} //master if
?>
I read in various topics that I need publish_stream permission from user to perform this action. But since I store user info separately in my own DB, how do I get this publish stream permission? Do I need to modify wordpress plugin to store some kind of access token? and utilize this token to post to wall?
you generate loginurl with publish_stream permission
if user is not logged in with permission, you have to make sure he does
redirect user to proper page
you can do it like this,
<?php
include_once("facebook.php");
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET,
'cookie' => true,
));
$user = $facebook->getUser();
if ($user) {
try {
// Get the user profile data you have permission to view
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$user = null;
}
} else {
$loginUrl = $facebook->getLoginUrl(array('scope' =>'publish_stream','redirect_uri'=>'example.com'));
die('<script> top.location.href="'.$loginUrl.'";</script>');
}
$params = array(
'message' => "Hurray! This works :)",
'name' => "This is my title",
'caption' => "My Caption",
'description' => "Some Description...",
'link' => "http://stackoverflow.com",
'picture' => "http://i.imgur.com/VUBz8.png",
);
$post = $facebook->api("/$user/feed","POST",$params);
?>
Facebooks documentation is inadecuate, confusing at best.
I have created an app, I have created a page for my business. I want to post updates on that page from my website as my App using the php-sdk.
I had this working perfectly with other pages/sites but nothing seems to be working any more.
I require offline_access, so I have followed the new endpoint as suggested in their docs.
Sequence of obtaining access_token with longer expiry:
https://www.facebook.com/dialog/oauth?client_id={my_app_id}&redirect_uri=http://my_url.redirect/fb/fb_token.php&scope=publish_stream,offline_access,user_status,read_stream,email,user_groups,manage_pages&response_type=token
returned [TOKEN_1]
https://graph.facebook.com/oauth/access_token?client_id={my_app_id}&client_secret={my_app_secret}&grant_type=fb_exchange_token&fb_exchange_token=[TOKEN_1]
returned [ACCESS_TOKEN]
https://graph.facebook.com/me/accounts?access_token=[ACCESS_TOKEN]
returns list of my pages and apps and their relevant ids and access codes. This is where I got my final [DEFINITIVE_ACCESS_TOKEN] && [PAGE_ID]
$facebook = new Facebook(array(
'appId' => {my_app_id},
'secret' => {my_app_secret},
'cookie' => false,
'oauth' => true
));
try {
$attachment = array(
'access_token' => [DEFINITIVE_ACCESS_TOKEN],
'message' => {my_message},
'name' => {my_title},
'link' => {my_url},
'description' => {my_description},
'picture' => {my_image_url},
);
$publishStream = $facebook->api('/[PAGE_ID]/feed', 'POST', $attachment);
} catch (FacebookApiException $e) {
die($e);
}
This has returned an error message "OAuthException: (#200) Posts where the actor is a page cannot also include a target_id"
Where am I going wrong? Is there a tutorial of getting this to work perfectly anywhere or are we supposed to all be mind readers and guess how it is supposed to be done?
Thanks in advance for any help.
I have noticed you are using offline access
Offline access will no longer be available as of May 1, 2012.
See this
https://developers.facebook.com/roadmap/offline-access-removal/
Make sure you have handling for this.
~K