Unity 接入Facebook

最近由于项目需要,接入Fackbook。原先的已经有登录模块了,不过是shaderSDK的,考虑到国内这些插件会对数据动手脚,只有换掉了。


回到正题,接入的过程还是遇到不少问题,先整理下我的资料,以下Fackbook都简称为FB
1.unity 5.6.5f1
2.jdk 1.8.0_144
3.SDK 25.2.5
4.fackbook 7.15.1
此外还装了
5.friebase 5.4.1(为啥会提这个,是因为FB与firebase含有共同的文件引起冲突了,这个接下来会说明)

 

问题1:

在初次导入FB后u3d输出提示说有文件重复了,经过排查,发现FB与firebase都含有“PlayServicesResolver”文件夹,我删掉一个就没问题了


问题2:


原先u3d的Android编译是Interal,在打包后报错如下:(截取一部分LOG)

CommandInvokationFailure: Failed to re-package resources.
D:\Program Files\android sdk\build-tools\23.0.2\aapt.exe package --auto-add-overlay -v -f -m -J "gen" -M "AndroidManifest.xml" -S "res" -I "D:/Program Files/android sdk\platforms\android-27\android.jar" -F bin/resources.ap_ --extra-packages
	io.agora.gaming.unity.video:android.support.graphics.drawable.animated
							   :android.support.v7.appcompat
							   :android.support.v7.cardview
							   :android.support.customtabs
							   :android.support.compat
							   :android.support.coreui
							   :android.support.coreutils
							   :android.support.fragment
							   :android.support.mediacompat
							   :android.support.v4
							   :android.support.graphics.drawable
							   :com.unity.purchasing
							   :com.facebook.android
							   :com.facebook.applinks
							   :com.facebook.common
							   :com.facebook.core
							   :com.facebook.login
							   :com.facebook.marketing
							   :com.facebook.messenger
							   :com.facebook.places
							   :com.facebook.share
							   :com.android.vending.billing
							   :com.unity.purchasing.googleplay
							   :com.JieQu.games
							   :com.unity.udp.sdk
							   :com.unity.udp.udpsandbox
							   :com.JieQu.games.resources
							   :com.unity.udp.sdk.common 
							
	-S "F:\Work\BigBoss\Run\Temp\StagingArea\android-libraries\com.android.support.animated-vector-drawable-25.3.1\res" 
	-S "F:\Work\BigBoss\Run\Temp\StagingArea\android-libraries\com.android.support.appcompat-v7-25.3.1\res" 
	-S "F:\Work\BigBoss\Run\Temp\StagingArea\android-libraries\com.android.support.cardview-v7-25.3.1\res" 
	-S "F:\Work\BigBoss\Run\Temp\StagingArea\android-libraries\com.android.support.customtabs-25.3.1\res" 
	-S "F:\Work\BigBoss\Run\Temp\StagingArea\android-libraries\com.android.support.support-compat-25.3.1\res" 
	-S "F:\Work\BigBoss\Run\Temp\StagingArea\android-libraries\com.android.support.support-core-ui-25.3.1\res" 
	-S "F:\Work\BigBoss\Run\Temp\StagingArea\android-libraries\com.android.support.support-core-utils-25.3.1\res" 
	-S "F:\Work\BigBoss\Run\Temp\StagingArea\android-libraries\com.android.support.support-fragment-25.3.1\res" 
	-S "F:\Work\BigBoss\Run\Temp\StagingArea\android-libraries\com.android.support.support-media-compat-25.3.1\res" 
	-S "F:\Work\BigBoss\Run\Temp\StagingArea\android-libraries\com.android.support.support-v4-25.3.1\res" 
	-S "F:\Work\BigBoss\Run\Temp\StagingArea\android-libraries\com.android.support.support-vector-drawable-25.3.1\res" 
	-S "F:\Work\BigBoss\Run\Temp\StagingArea\android-libraries\common\res" 
	-S "F:\Work\BigBoss\Run\Temp\StagingArea\android-libraries\facebook-android-wrapper-7.15.1\res" 
	-S "F:\Work\BigBoss\Run\Temp\StagingArea\android-libraries\facebook-common\res" 
	-S "F:\Work\BigBoss\Run\Temp\StagingArea\android-libraries\facebook-login\res" 
	-S "F:\Work\BigBoss\Run\Temp\StagingArea\android-libraries\facebook-messenger\res" 
	-S "F:\Work\BigBoss\Run\Temp\StagingArea\android-libraries\facebook-share\res" 
	-S "F:\Work\BigBoss\Run\Temp\StagingArea\android-libraries\GoogleAIDL\res" 
	-S "F:\Work\BigBoss\Run\Temp\StagingArea\android-libraries\GooglePlay\res" 
	-S "F:\Work\BigBoss\Run\Temp\StagingArea\android-libraries\udpsandbox\res" 
	-S "F:\Work\BigBoss\Run\Temp\StagingArea\android-libraries\unity-android-resources\res" 
	-S "F:\Work\BigBoss\Run\Temp\StagingArea\android-libraries\utils\res"

stderr[
F:\Work\BigBoss\Run\Temp\StagingArea\android-libraries\com.android.support.appcompat-v7-25.3.1\res\layout\abc_action_mode_close_item_material.xml:17: note: removing attribute http://schemas.android.com/apk/res/android:layout_marginEnd from <ImageView>
F:\Work\BigBoss\Run\Temp\StagingArea\android-libraries\com.android.support.appcompat-v7-25.3.1\res\layout\abc_action_mode_close_item_material.xml:17: note: removing attribute http://schemas.android.com/apk/res/android:paddingStart from <ImageView>

主要看stderr部分,大致就是com.android.support.appcompat-v7-25.3.1的abc_action_mode_close_item_material.xml里面某个字段无法生效,去网上找相关资料后,其中的解决办法就是直接把相关的字段删除掉。
挺无奈的,看着还有将近100条的bug,只好一个个去删除了。。。
重点来了,当我全部清除后再次打包,又报错了,说我的AndroidManifest.xml文件含有违法字符"$",经过查找字段为package="${applicationId}" ,这个符号只有在u3d编译Android为Gradle才会被识别,但工程用Internal的时候也没报错过,只好转为Gradle打包编译了,幸运的是,在转为Gradle后,问题2的报错就消失了。
解决办法:转Gradle打包
 

问题3
 

在成功打包后就开始接入fb了,目前需要接入登录与分享,这个两块我参考了https://blog.csdn.net/NRatel/article/details/84241100 的经验,我先把代码贴出来,再说说的心得
 

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

public class FacebookTool : MonoBehaviour
{

    public static FacebookTool _FBTool;
    public Action successFun = null;
    public Action failFun = null;

    public Action onFBShareFaild = null;
    public Action onFBShareSucced = null;

    
    [HideInInspector]
    public string userName = "";
    [HideInInspector]
    public string email = "";
    [HideInInspector]
    public string headUrl = "";
    [HideInInspector]
    public string openId = "";
    [HideInInspector]
    public string gender = "";
    [HideInInspector]
    public string token = "";

    // Use this for initialization
    void Start()
    {
        _FBTool = this;
        DontDestroyOnLoad(gameObject);
    }

    public void Init()
    {
        if (!FB.IsInitialized)
        {
            // Initialize the Facebook SDK
            FB.Init(InitCallback, OnHideUnity);
        }
        else
        {
            // Already initialized, signal an app activation App Event
            FB.ActivateApp();
        }

    }

    private void InitCallback()
    {
        if (FB.IsInitialized)
        {
            // Signal an app activation App Event
            FB.ActivateApp();
            // Continue with Facebook SDK
        }
        else
        {
            Debug.LogError("Failed to Initialize the Facebook SDK");
        }
    }

    private void OnHideUnity(bool isGameShown)
    {

        Debug.LogWarningFormat("Success Response: OnHideUnity Called:{0}", isGameShown);

        if (!isGameShown)
        {
            // Pause the game - we will need to hide

        }
        else
        {
            // Resume the game - we're getting focus again

        }
    }

    //登出
    public void LogOut()
    {
        if (FB.IsLoggedIn)
        {
            FB.LogOut();          
        }

        userName = "";
        email = "";
        headUrl = "";
        openId = "";
        gender = "";
        token = "";
    }

    //登录
    public void Login()
    {
        var perms = new List<string>() { "public_profile", "email" };
        FB.LogInWithReadPermissions(perms, AuthCallback);
    }

    private void AuthCallback(ILoginResult result)
    {
        if (result == null)
        {
            Debug.LogWarning("Null Response");
            if (failFun != null)
                failFun();
            return;
        }

        var LastResponse = "";
        // Some platforms return the empty string instead of null.
        if (!string.IsNullOrEmpty(result.Error))
        {
            LastResponse = "Error Response: " + result.Error;
            if (failFun != null)
                failFun();
        }
        else if (result.Cancelled)
        {
            LastResponse = "Cancelled Response: " + result.RawResult;
            if (failFun != null)
                failFun();
        }
        else if (!string.IsNullOrEmpty(result.RawResult))
        {
            LastResponse = "Success Response: " + result.RawResult;
            if (result.AccessToken != null)
            {
                var AccessToken = result.AccessToken;
                token = AccessToken.TokenString;
            }
            GetMyInfo();
        }
        else
        {
            if (failFun != null)
                failFun();
            LastResponse = "Empty Response";
        }
        Debug.LogWarning(LastResponse);
    }

    //获取个人信息,在登录成功后执行
    public void GetMyInfo()
    {
        FB.API("me?fields=id,name,gender,picture,email", HttpMethod.GET, (result) =>
        {
            ReadJsonInfo(result.RawResult);
        });
    }

    public void ReadJsonInfo(string jsonString)
    {
        Debug.LogWarning(jsonString);
        var dict = Json.Deserialize(jsonString) as Dictionary<string, object>;

        if (dict.ContainsKey("name"))
        {
            userName = dict["name"].ToString();
        }
        if (dict.ContainsKey("id"))
        {
            openId = dict["id"].ToString();
        }
        if (dict.ContainsKey("gender"))
        {
            gender = dict["gender"].ToString();
        }
        if (dict.ContainsKey("email"))
        {
            email = dict["email"].ToString();
        }

        if (dict.ContainsKey("picture"))
        {
            var picture = dict["picture"] as Dictionary<string, object>;
            if (picture.ContainsKey("data"))
            {
                var pictureData = picture["data"] as Dictionary<string, object>;
                if (pictureData.ContainsKey("url"))
                {
                    headUrl = pictureData["url"].ToString();
                }
            }
        }
        
        if (successFun != null)
            successFun();

        //Debug.LogFormat("userName:{0} , userID:{1}  userGender:{2} userUrl:{3}", userName, openId, gender, headUrl);
    }

    public void FBShare(Uri uri, string contentTitle, string contentDesc, Uri picUri)
    {
        //uri = new Uri("https://play.google.com/store/apps/details?id=com.dominosamgong.poker");
        FB.ShareLink(uri, contentTitle, contentDesc, picUri, (result) =>
        {
            if (result.Cancelled || !String.IsNullOrEmpty(result.Error))
            {
                Debug.Log("ShareLink Faild");
                if (onFBShareFaild != null)
                {
                    Debug.LogError(result.Error);
                    onFBShareFaild();
                }
            }
            else
            {
                Debug.Log("ShareLink success!");
                if (onFBShareSucced != null)
                {
                    var postID = String.IsNullOrEmpty(result.PostId) ? "" : result.PostId;
                    onFBShareSucced();
                }
            }
        });
    }
}


FB初始化不必说明了,就几行。
登录时需要用的函数FB.LogInWithReadPermissions(perms, AuthCallback);
传入的参数perms有好几种,因为我这边需要获得用户的ID,名字,性别,照片url,邮箱等等。官网上说明需要传入特定的参数,并对app进行审查,实际操作过程中发现不需要。就用默认的"public_profile", "email"

而获取个人信息需要在登录后再调用FB.API()就行了。参数及具体的用法可以参考这个https://developers.facebook.com/tools/explorer
用于检测自己传入的参数是否正确。
FB在获取用户信息回传时数据类型是JSON的,关于解析的方式参考这个https://developers.facebook.com/docs/unity/reference/current/Json
我根据他写的教程自己也整了个,因为获取的字段都是固定的,所以我就写死了


问题4

此为u3d中FB的分享API
 

public static void ShareLink(Uri contentURL = null, string contentTitle = "", string contentDescription = "", Uri photoURL = null, FacebookDelegate<IShareResult> callback = null);

字面上看着说都可以传空参数,打包实测时发现报错了,说我的没有传入标题与内容。于是就传入contentTitle 与contentDescription,再次打包,发现还是同样的错误??这就纳闷了,接着我把两个url地址也传进去,都为百度首页地址。
实测时发现不会报错了,但又有新的问题,我所传入的contentTitle 与contentDescription内容并没有看到,取而代之的是标题与内容竟然是“www.baidu.com”与“百度”.。接下来试着去掉photoURL,contentTitle ,contentDescription,只传入contentURL。实测发现木有问题,和上次的现象一模一样,由此推测FB中u3d分享api仅仅只有contentURL生效了,其他3个都不需要。在官方上查询相关api时发现牛头不对马嘴,实实在在被坑了一把。。。
解决办法:只有contentURL有效,其他三个没有用处

问题5

关于Key Hash,如果手机没装FB的APP,是可以正常分享的,在装了FB之后,分享会报错,内容如下:
error: Invalid key hash. The【key hash】 does
not match any stored key hashes. Configure your app key hashes at https://developers.facebook.com/apps/(游戏的appid)/
将提示的Key hash 配到后台即可。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值