William Buttlicker
William Buttlicker

Reputation: 6000

Facebook session not being created

I am using this code to post to the user's wall :

require 'fb/src/facebook.php';
$facebook = new Facebook(array(
   'appId' => 'xxx',
   'secret' => 'xxx',
));
$params = array(
    'canvas' => 1,
    'scope' => 'publish_stream,email,user_about_me,user_birthday,user_website',
    'redirect_uri' => 'urlhere',
);

$fb_session = $facebook->getUser();

// Session based API call.
if ($fb_session) 
{
    try 
    {
         $args = array(
                  'message' =>  $_GET['by'],
                  'link' => 'linkhere/',
                  'caption' => $_GET['test']
                 );
         $post_id = $facebook->api("/me/feed", "post", $args);
     } 
     catch (Exception $e) 
     {

         $fb_login_url = $facebook->getLoginUrl($params);
         echo $e->getMessage();
     }
} 
else 
{
     $fb_login_url = $facebook->getLoginUrl($params);
} 

The code is working till the point uuer clicks on login part to post. After that the url contains a code = xxxzz and a state =yyy but the $fb_session is 0.

This works sometimes without any changes. Please help!

Upvotes: 2

Views: 184

Answers (2)

Shpat
Shpat

Reputation: 502

You should include the access token when you try to post to some User Facebook wall.

First get access token:

$fbToken = NULL;
$fbToken = $facebook->getAccessToken();

right after $fb_session = $facebook->getUser();

and then include it in the $args array:

 'access_token' => $fbToken 

if session is NOT created or access token is not valid, you should redirect the user back to re-authorize your Facebook App.

So in ELSE, you should add

   header("Location: $fb_login_url ");

after $fb_login_url = $facebook->getLoginUrl($params);

  • assuming that everything else is correct, but the access_token is not valid, you should also include header("Location: $fb_login_url "); before echo $e->getMessage();

Upvotes: 1

user2366009
user2366009

Reputation:

in both cases you are using getloginurl

shouldn't it be

if ($fb_session) {
try {
$args = array(
'message' =>  $_GET['by'],
'link' => 'linkhere/',
'caption' => $_GET['test']
);
$post_id = $facebook->api("/me/feed", "post", $args);
} catch (Exception $e) {
$fb_logout_url = $facebook->getLogoutUrl;
.
.
.

Upvotes: 0

Related Questions