[英]Facebook PHP SDK access token issue when retrieve User Profile via the Graph API
I have trying to retrieve user profile in my website. 我试图在我的网站中检索用户个人资料。 But after I get the access token, I can't use it. 但在我获得访问令牌后,我无法使用它。 The result it show is 它显示的结果是
Graph returned an error: Invalid OAuth access token
I can get the access token by below code 我可以通过下面的代码获取访问令牌
Login.php 的login.php
session_start();
require_once __DIR__ . '/facebook-php-sdk-v4-5.0-dev/src/Facebook/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => 'I have insert correct app id',
'app_secret' => 'and app secret',
'default_graph_version' => 'v2.0',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email'];
$loginUrl = $helper->getLoginUrl('http://myweb.com/login-callback.php', $permissions);
echo '<a href="' . htmlspecialchars($loginUrl) . '">Log in with Facebook!</a>';
?>
And below is login-callback.php 以下是login-callback.php
<?php
session_start();
require_once __DIR__ . '/facebook-php-sdk-v4-5.0-dev/src/Facebook/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => 'I have insert correct app id',
'app_secret' => 'and app secret',
'default_graph_version' => 'v2.0',
]);
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (! isset($accessToken)) {
if ($helper->getError()) {
header('HTTP/1.0 401 Unauthorized');
echo "Error: " . $helper->getError() . "\n";
echo "Error Code: " . $helper->getErrorCode() . "\n";
echo "Error Reason: " . $helper->getErrorReason() . "\n";
echo "Error Description: " . $helper->getErrorDescription() . "\n";
} else {
header('HTTP/1.0 400 Bad Request');
echo 'Bad request';
}
exit;
}
$_SESSION['fb_access_token'] = (string) $accessToken;
try {
$response = $fb->get('/me?fields=id,name', "'".$_SESSION['fb_access_token']."'");
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$user = $response->getGraphUser();
echo 'Name: ' . $user['name'];
?>
Am I doing something wrong? 难道我做错了什么? Please help. 请帮忙。 Thanks. 谢谢。
I only have: 我只有:
$response = $fb->get('/me?fields=id,name', $token);
$user = $response->getGraphUser();
It works perfectly 它完美地运作
我想你应该改变你的代码: "'".$_SESSION['fb_access_token']."'"
来$accessToken
并再试一次
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.