本文主要是介绍Facebook获取AccessToken和获取个人主页信息,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、开始的准备工作
- (1)创建你自己的应用
- (2)填写创建应用的信息
- (3)创建成功
[应用创建完成会生成对应的AppId和AppSecret还有对应的版本号]
- (4)添加产品
[这里我们需要登录,因为我们要通过登录获取他的AccessToken]
[把下面三个按钮打开,设置登录成功AccessToken的回传地址 注意:必须在服务器或者云服务器上进行操作,指定的地址必须可以访问不能是局域网的ip,不能在本地localhost下进行]
指定到控制器的某个方法就可以了路径必须正确,失败时候检查服务器是否开启路由重写模式,没有开启要加index.php
(5)下载Facebook对应的php SDK
facebook/php-graph-sdk下载:https://github.com/facebook/php-graph-sdk
把Facebook这个目录的文件放到自己项目对应的目录下
我是用TP做的,所有我把他放在Queens\ThinkPHP\Library\Vendor\Facebook
二、代码实现
- (1)login
<?php
namespace Admin\Controller;use Facebook\Facebook;
use Think\Controller;class FaceController extends CommonController
{private $app_id='';private $app_secret='';private $fb='';public function _initialize(){parent::_initialize();vendor('Facebook.autoload');$this->_getAppId();}private function _getAppId(){$map=array('type'=>'facebook_appid');$m=M('info')->field('info')->where($map)->find();$arr=json_decode($m['info'],true);$this->app_id=$arr['app_id'];$this->app_secret=$arr['app_secret'];$this->_getFb($this->app_id,$this->app_secret);}/**我这里是通过数据库保存的App Id,和App Secret,最好是这样,不要在控制那里写死,因为这些东西可以在Facebook那里更改,最好弹性一点反正都可以,只有组装成像下面$fb的格式就可以!*/private function _getFb($app_id,$app_secret){$fb = new Facebook(['app_id' => $app_id,'app_secret' => $app_secret,'default_graph_version' => 'v2.8',//[注意:最好要对应自己php的sdk版本号]]);$this->fb=$fb;}/**把登陆按钮的信息返回页面,因为Facebook的AccessToken他是有时间限定的,不是永久,而且必须要通过登陆才能获取所有这里吧登陆的信息做成一个更新AccessToken的按钮,让管理员去更新,可以自己判断AccessToken,写个定时更新都可以,我这里是为了简单实现!*/public function index(){$fb=$this->fb;$helper = $fb->getRedirectLoginHelper();$url='这里是你自己等会后的回传地址nsdining/index.php/Admin/Face/showFace';$loginUrl = $helper->getLoginUrl($url);$this->assign('data',htmlspecialchars($loginUrl));$this->display();}/**登陆后Facebook服务器会让你跳到你自己定义的这个方法,还有带回Facebook给你的AccessToken,
*/public function showFace(){$fb=$this->fb;$helper = $fb->getRedirectLoginHelper();try {$accessToken = $helper->getAccessToken();} catch(Facebook\Exceptions\FacebookResponseException $e) {// When Graph returns an errorecho 'Graph returned an error: ' . $e->getMessage();exit;} catch(Facebook\Exceptions\FacebookSDKException $e) {// When validation fails or other local issuesecho '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;}// Logged in
// echo '<h3>Access Token</h3>';
// var_dump($accessToken->getValue());// OAuth 2.0 client handler$oAuth2Client = $fb->getOAuth2Client();// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($accessToken->getValue());// The OAuth 2.0 client handler helps us manage access tokens
$oAuth2Client = $fb->getOAuth2Client();// Get the access token metadata from /debug_token$tokenMetadata = $oAuth2Client->debugToken($accessToken);// echo '<h3>Metadata</h3>';$token_time_out_json=json_encode($accessToken->getExpiresAt());$token_time_out_json_time=explode('.',json_decode($token_time_out_json,true)['date']);// pr($tokenMetadata->getExpiresAt()->date);// Validation (these will throw FacebookSDKException's when they fail)$tokenMetadata->validateAppId($this->app_id); // Replace {app-id} with your app id
// If you know the user ID this access token belongs to, you can validate it here
//$tokenMetadata->validateUserId('123');$tokenMetadata->validateExpiration();if (! $accessToken->isLongLived()) {// Exchanges a short-lived access token for a long-lived onetry {$accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);} catch (Facebook\Exceptions\FacebookSDKException $e) {echo "<p>Error getting long-lived access token: " . $helper->getMessage() . "</p>\n\n";exit;}
// echo '<h3>Long-lived</h3>';}$_SESSION['fb_access_token'] = (string) $accessToken;//获取到了AccessToken,接下来的处理,你可以存在session或者数据库都可,只要能随时拿就ok,//我这里是写在文件那里$accessTokenArr=array('Facebook_token'=>$accessToken->getValue(), //AccessToken值'time_out'=>$token_time_out_json_time[0] //AccessToken过期的时间);file_put_contents('./Public/key/facebookToken.txt',json_encode($accessTokenArr));if( $this->_updateFacebookAccessToken($accessTokenArr)){echo "<script>alert('update successfully');window.location.href='".U('Face/index')."'</script>";}else{echo "<script>alert('Failed to update');window.location.href='".U('Face/index')."'</script>";}
// User is logged in with a long-lived access token.
// You can redirect them to a members-only page.
//header('Location: https://example.com/members.php');//可以跳到你指定的页面}
}
三、去Facebook那里拿数据
- (1)Facebook官网那里有个可以测试的工具
[這裡是我要拿的數據!]
$url = "https://graph.facebook.com/主页id或者me?fields=posts{permalink_url,full_picture,message}&access_token=AccessToken值";//也可以分页获取,这里我就不测试了,具体看开发文档
facebook文档连接
- (2)拿回来的数据放到自己对应的前端就可以了显示了[要开VPN,不然就显示不了]
- -
[点击后可以跳对对应Facebook的动态]
这篇关于Facebook获取AccessToken和获取个人主页信息的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!