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 error
            echo 'Graph returned an error: ' . $e->getMessage();
            exit;
        } catch(Facebook\Exceptions\FacebookSDKException $e) {
            // When validation fails or other local issues
            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;
        }

// 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 one
            try {
                $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的动态]

这里写图片描述

猜你喜欢

转载自blog.csdn.net/post_mans/article/details/72780065