So this is working fine... But when I refresh the page twice(or click on two pages who include this script fast) it gives this error OAuthException: An active access token must be used to query information about the current user. Any ideas?
<?php
$app_id = '***************';
$app_secret = '**************';
$app_namespace = '****************';
$app_url = 'http://apps.facebook.com/' . $app_namespace . '/';
$scope = 'email,publish_actions';
// Init the Facebook SDK
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
));
// Get the current user
$user = $facebook->getUser();
// If the user has not installed the app, redirect them to the Login Dialog
if (!$user) {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => $scope,
'redirect_uri' => $app_url,
));
print('<script> top.location.href=\'' . $loginUrl . '\'</script>');
}
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me', 'POST');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
//<img src="https://graph.facebook.com/?php echo $user; ?/picture">
//?php print_r($user_profile); ?
?>
I personally find it easier to manage the access_token
myself. Facebook's Graph API secures protected endpoints by requiring that an access_token
be passed in. The PHP SDK abstracts this away, but I have never been comfortable with Facebook handling the information because sometimes it just doesn't work . This isn't to say that the library is bad, but only that I haven't been using it correctly . Keep this caveat in mind.
It looks like you're working with a Facebook Canvas App. When the user successfully authenticates for the first time, Facebook will send an access_token
in $_GET
. At this point, you should save this to your database, since that access token is good for 3 months or so.
At the point, from then on, you can pass in the access_token
in the call parameters:
try {
$user_profile = $facebook->api('/me', 'POST', array(
"access_token" => '' // access token goes here
));
} catch (FacebookApiException $e) {
// error handling
}
Given that Facebook is returning the error that you need an access token in order to call the /me
resource, it looks like $facebook->getUser();
is returning something. You may want to double-check what it is.
While I'm here, you're using this logic:
if (!conditional) {
// do something
}
if (conditional) {
// do something else
}
Confusing. Use else
:
if (conditional) {
// do something
} else {
// do something else
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.