獲取 FaceBook 訪問令牌以讀取和寫入 Facebook 社交圖

本文件詳細介紹了獲取 facebook 訪問令牌和使用令牌獲取 FB 源的步驟。

示例:可以使用例項

https://newtonjoshua.com

Graph API 簡介: Graph API 是將資料輸入和輸出 Facebook 平臺的主要方式。它是一種基於 HTTP 的低階 API,可用於查詢資料,釋出新故事,管理廣告,上傳照片以及應用可能需要執行的各種其他任務。

FaceBook 應用程式:

https://developers.facebook.com

建立一個 Facebook 應用程式。你會得到一個 App_IdApp_Secret

圖 API Explorer:

https://developers.facebook.com/tools/explorer/ {{App_Id}} /?method=GET&path=me%2Ffeed&version=v2.8

你會得到一個短暫的 access_token。所以這將是我們的節目。

注意:建立訪問令牌時,請選擇所需的所有 fb 欄位。這將授予訪問令牌獲取這些欄位的許可權。

訪問令牌擴充套件:

https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id= {{App_Id}} &client_secret = {{App_Secret}} &fb_exchange_token = {{short-lived-access_token}}

你會得到一個有效期為 2 個月的 access_token

訪問令牌偵錯程式:

https://developers.facebook.com/tools/debug/accesstoken?q= {{access_token}} &version = v2.8

你可以檢視 access_token 的詳細資訊。

適用於 JavaScript 的 Facebook SDK: 在 HTML 中包含以下 JavaScript,以便將 SDK 非同步載入到你的頁面中

<script>
        (function (d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) {
                return;
            }
            js = d.createElement(s);
            js.id = id;
            js.src = "//connect.facebook.net/en_US/sdk.js";
            fjs.parentNode.insertBefore(js, fjs);
        }(document, 'script', 'facebook-jssdk'));
    </script>

圖譜 API: 讓我們進行 API 呼叫以獲取我們的 FB ID,個人資料照片,封面圖片和供稿。

<script>
window.fbAsyncInit = function () {
    FB.init({
        appId: '{{App_Id }}',
        xfbml: true,
        version: 'v2.7'
    });
    FB.api(
        '/me',
        'GET', {
            fields: 'id,picture{url},cover,feed',
            access_token: {{access_token}}
        },
        function (response) {
        if (response.error) {
                console.error(response.error.message);
            }
            if (response.picture.data.url) {
                profilePic = response.picture.data.url;
            }
            if (response.cover.source) {
                coverPic = response.cover.source;
            }
            if (response.feed.data) {
        feeds = response.feed.data;
                feeds.forEach(function (feed) {
            // view each feed content
                });
            }
            if (response.feed.paging.next) {
                nextFeedPage = response.feed.paging.next;
        // a request to nextFeedPage will give the next set of feeds
            }
            
        }
    );
};

</script>

使用 Graph API Explorer 來設計應在欄位中輸入的 querry(例如:‘id,picture {url},cover,feed’)

現在,你可以使用 access_token 從 Facebook Graph API 獲取你的 Facebook 資料。參考 https://developers.facebook.com/docs/graph-api/overview/

注意:你的 access_token 將在 2 個月後到期。之後建立一個新的 access_token。