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;
    }

}

以上。

  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值