Unity 接入Facebook SDK——最白話,手把手教你做系列

最近需要用到facebook登錄,分享,邀請和獲取好友列表功能。於是就開始踩坑之旅。當然,功能也是站在巨人肩膀上的,我參考的這篇。鏈接 ,這篇主要是在原文基礎上補充一些新坑。
因爲FacebookSdk在不斷更新,所以也有了很多新的問題。
好了,開始正文。
Unity版本環境。Unity2018.2.4。 FacebookSdk版本:facebook-unity-sdk-7.15.1
問題1:關於版本選擇,肯定是最新的版本功能最多最全。但是如果你接入最新的版本出現初始化FacebookSdk直接崩潰的問題。就可以退回到這個版本了。在官方社區看到是是Unity和FacebookSdk版本衝突的問題。在Unity2018的版本比較多。要麼你切換Unity版本,要麼你切換FacebookSdk版本。

正式接入:
1、在開發者後臺創建應用。
後臺地址:https://developers.facebook.com/apps/

2、下載Unity版本的SDK, 導入Unity。
下載地址:https://developers.facebook.com/docs/unity/

3、配置方法如下圖。
在這裏插入圖片描述(必須填寫)應用的基本信息,可以在facebook後臺中找到,具體位置可以鼠標移動到 “?”處查看。
在這裏插入圖片描述安卓的配置IOS的後續發佈的時候會補充。
在這裏插入圖片描述上圖紅色箭頭指的兩個部分直接複製到Facebook後臺的中(設置-基本設置)。下圖位置。
在這裏插入圖片描述注意:類名部分如果打包成安卓的話要在安卓的AndroidManifest文件中找。
配置到此結束。

4、關於具體的功能。
文檔地址:https://developers.facebook.com/docs/unity/reference/current
遊戲中,用到的比較常見的功能有,登錄、分享、獲取自己的信息、獲取好友列表(好友信息列表)、邀請、分數排行榜等。還提供了應用內打點統計等其他功能。sdk中自帶的示例項目中都可以查看。

需要注意的是,
1,由於SDK版本更新,原來Demo的邀請已經不可用了。現在需要用新的FB.AppRequest來邀請好友。
2,如果你邀請出現應用不可以使用遊戲邀請。則需要在Facebook後臺的中(設置-基本設置)。下圖位置將類別選爲遊戲。
在這裏插入圖片描述四、獲取自己的信息、好友信息列表。
重點!!! Facebook 通過 Graph API(圖譜API) 來獲取用戶數據,或發佈內容(如分數)。
你必須先了解Graph API是什麼!
文檔地址:https://developers.facebook.com/docs/graph-api

兩個重載的方法:
public static void API(string query, HttpMethod method, FacebookDelegate callback = null, IDictionary<string, string> formData = null);

public static void API(string query, HttpMethod method, FacebookDelegate callback, WWWForm formData);

其中,
第一個參數必須滿足FQL(facebook Query Language)的語法。可以傳入具體的查詢參數,查找自己需要的信息
第二個參數是 選擇獲取Get還是發佈Post。
第三個參數是 結果回調。
第四個參數是 參數二選擇Post時附帶的發佈信息。

1),什麼是FQL?
文檔地址:https://developers.facebook.com/docs/technical-guides/fql/

2),數據的結構是怎樣的?
參考:https://developers.facebook.com/docs/graph-api/reference/user/

3),怎麼樣快速測一下我傳的query參數對不對?
Graph API探索工具:https://developers.facebook.com/tools/explorer

4),如何處理返回結果?
IGraphResult 中的 ResultList 是返回的結果,
但推薦直接使用其父類IResult 中的RawResult。
RawResult是一個Json字符串,可以方便的在各種語言下解析,因爲我們更多的用lua寫業務邏輯。
Facebook官方也提供了在C#中解析的工具:
文檔參考:https://developers.facebook.com/docs/unity/reference/current/Json

重點注意:
1),“me/friends” 查詢到的結果是 已經登錄過該遊戲/應用的facebook好友列表。(官方描述爲:Only friends who installed this app are returned in API v2.0 and higher. total_count in summary represents the total number of friends, including those who haven’t installed the app(我一直以爲是獲取Facebook好友列表,然而實際上是安裝同一個應用的遊戲好友))
2),“me/friends” 需要在登錄時加入 “user_friends” 權限。
(這個權限我以爲是facebookapp設置裏,或者安裝應用時需要授權的權限。然而實際測試的正式應用什麼都獲取不到,用測試賬號可以獲取到。並不需要額外授權。具體正式環境下可能需要在Facebook後臺的中配置一下權限。(見下圖,未正式上線測試,不確定,有人驗證過的話可以留言實錘一下。))

在這裏插入圖片描述

下面貼代碼功能代碼:

using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using Facebook.Unity;
using Facebook.MiniJSON;
using LitJson;

public class FBMgr
{
    public static string FBLog = "MyFbLog:";
    public delegate void OnFBLoginSucced(Facebook.Unity.AccessToken token);
    public delegate void OnFBLoginFaild(bool isCancel, string errorInfo);
    public delegate void OnFBShareLinkSucced(string postId);
    public delegate void OnFBShareLinkFaild(bool isCancel, string errorInfo);
    public delegate void OnGotFBFriendInGame(string resultJsonStr);
    public delegate void OnGotFBMyInfo(string resultJsonStr);
    public delegate void OnFBInvitedSucceed(string resultJsonStr);
    private static string appLinkUrl;
    public String FBID;
    /// <summary>
    /// 初始化
    /// </summary>
    public static void Init()
    {
        FB.Init(() =>
        {
            string logMessage = string.Format("OnInitCompleteCalled IsLoggedIn='{0}' IsInitialized='{1}'", FB.IsLoggedIn, FB.IsInitialized);
            Debug.Log(FBLog+ logMessage);
            Debug.Log(FBLog+"FB.AppId: " + FB.AppId);
            Debug.Log(FBLog+"FB.GraphApiVersion: " + FB.GraphApiVersion);         

        },(isUnityShutDown) =>
        {
            Debug.Log(FBLog+" FB OnHideUnity: " + isUnityShutDown);
        });
    }

    /// <summary>
    /// 登錄
    /// </summary>
    /// <param name="onFBLoginSucced">回調,不需要可不填</param>
    /// <param name="onFBLoginFaild">回調,不需要可不填</param>
    public static void FBLogin(OnFBLoginSucced onFBLoginSucced = null, OnFBLoginFaild onFBLoginFaild = null)
    {
        var perms = new List<string>() { "public_profile", "email", "user_friends" };
        FB.LogInWithReadPermissions(perms, (result) =>
        {
            if (result == null)
            {              
                Debug.Log(FBLog+ "Null Response\n");
                return;
            }
            if (FB.IsLoggedIn)
            {
                Debug.Log(FBLog+"FBLoginSucceed");
                if (onFBLoginSucced != null)
                {
                    onFBLoginSucced(Facebook.Unity.AccessToken.CurrentAccessToken);
                }
            }
            else
            {
                Debug.Log(FBLog+"FBLoginFaild+"+result.Error);
                Debug.Log(FBLog + result.RawResult);
                if (onFBLoginFaild != null)
                {
                    onFBLoginFaild(result.Cancelled, result.Error);
                }
            }
        });
    }


    /// <summary>
    /// 分享。
    /// </summary>
    /// <param name="uri">"https://developers.facebook.com/"</param>
    /// <param name="contentTitle">"ShareLink"</param>
    /// <param name="contentDesc">"Look I'm sharing a link"</param>
    /// <param name="picUri">"http://i.imgur.com/j4M7vCO.jpg"</param>
    /// <param name="onFBShareLinkSucced">回調,不需要可不填</param>
    /// <param name="onFBShareLinkFaild">回調,不需要可不填</param>

    public static void FBShareLink(string uri, string contentTitle=null, string contentDesc=null, string picUri=null, OnFBShareLinkSucced onFBShareLinkSucced = null, OnFBShareLinkFaild onFBShareLinkFaild = null)
    {

        FBShareLink(new Uri(uri), contentTitle, contentDesc, new Uri(picUri), onFBShareLinkSucced, onFBShareLinkFaild);
    }

    private static void FBShareLink(Uri uri, string contentTitle, string contentDesc, Uri picUri, OnFBShareLinkSucced onFBShareLinkSucced = null, OnFBShareLinkFaild onFBShareLinkFaild = null)
    {
       
            FB.ShareLink(uri, contentTitle, contentDesc, picUri, (result) =>
            {
                if (result.Cancelled || !String.IsNullOrEmpty(result.Error))
                {
                    Debug.Log(FBLog + "ShareLink Faild");
                    if (onFBShareLinkFaild != null)
                    {
                        onFBShareLinkFaild(result.Cancelled, result.Error);
                    }
                }
                else
                {
                    Debug.Log(FBLog + "ShareLink success!");
                    if (onFBShareLinkSucced != null)
                    {
                        onFBShareLinkSucced(String.IsNullOrEmpty(result.PostId) ? "" : result.PostId);
                    }
                }
            });
     
    }



    /// <summary>
    /// 獲取自己的信息
    /// </summary>
    /// <param name="onGotFBMyInfo">回調,不需要可不填</param>
    //返回示例
    //{
    //  "id": "581672012697623",
    //  "name": "Guangmao Zhao",
    //  "picture": {
    //    "data": {
    //      "height": 50,
    //      "is_silhouette": false,
    //      "url": "https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=581672012697623&height=50&width=50&ext=1585856586&hash=AeR_BguJ28EVvd-r",
    //      "width": 50
    //    }
    //  }
    //}
    public static void GetMyInfo(OnGotFBMyInfo onGotFBMyInfo = null)
    {
        if (FB.IsLoggedIn == false)
        {
            Debug.Log(FBLog + "FBNotLogin");
            return;
        }
        FB.API("me?fields=id,name,picture", HttpMethod.GET, (result) => {
            Debug.Log(FBLog + result.RawResult);
            if (onGotFBMyInfo != null)
            {
                onGotFBMyInfo(result.RawResult);
            }
        });
    }

    /// <summary>
    /// 獲取遊戲好友
    /// </summary>
    /// <param name="onGotFBFriendInGame">回調,不需要可不填</param>

    //返回示例
    //{
    //  "data": [
    //  ],
    //  "summary": {
    //    "total_count": 3
    //  }
    //}
    public static void GetFBFriendInGame(OnGotFBFriendInGame onGotFBFriendInGame = null)
    {
        Debug.Log("GetFBFriendInGame");
        if (FB.IsLoggedIn == false)
        {
            Debug.Log(FBLog + "FBNotLogin");
            return;
        }

        FB.API("me/friends?fields=id,name,picture", HttpMethod.GET, (result) => {
           
            if (onGotFBFriendInGame != null)
            {
                Debug.Log(FBLog + result.RawResult);
                onGotFBFriendInGame(result.RawResult);
            }
        });
    }

    /// <summary>
    /// 邀請
    /// </summary>
    /// <param name="message">Come play this great game!</param>
    /// <param name="onFBInvitedSucceed">獲取遊戲好友</param>
    public static void FBInvite(string message, OnFBInvitedSucceed onFBInvitedSucceed = null)
    {

        FB.AppRequest(message, null, null, null, null, null, null, (result) => {
            Debug.Log(FBLog + result.RawResult);

            if (onFBInvitedSucceed!=null)
            {
                onFBInvitedSucceed(result.RawResult);
                InviteInfoToArry(result.RawResult);
            }
        });
    }


    /// <summary>
    /// 把邀請返回的數據轉換成數組
    /// </summary>
    /// <param name="info"></param>
    /// <returns></returns>
    public static string[] InviteInfoToArry(string info)
    {
        JsonData jsonData = JsonMapper.ToObject(info);
        JsonData damageValue = jsonData["to"];
        string[] arrStr = damageValue.ToString().Split(',');//按逗號截取 
        Debug.Log(arrStr[0]);
        return arrStr;
    }

}

以上。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章