文章目錄
- 一、前言
- 二、下載Facebook SDK
- 三、匯入SDK
- 四、切換到Android平臺
- 五、Dependencies.xml
- 六、執行Play Services Resolver
- 七、Edit Settings
- 八、介面說明
- 1、初始化
- 2、登錄
- 3、快速登錄
- 4、登出
- 5、分享
- 6、支付
- 九、測驗
- 1、制作測驗界面
- 2、測驗腳本
- 3、Editor環境下測驗
- 4、發布成Android apk測驗
- 十、結束語
一、前言
點關注不迷路,持續輸出Unity干貨文章,
嗨,大家好,我是新發,
最近需要接Facebook,那么,寫下這個程序吧,
最終效果如下:

本文Demo工程已上傳到CodeChina,感興趣的同學可自行下載學習(注:Demo中的AppId需要自行修改),
地址:https://codechina.csdn.net/linxinfa/UnityFacebookSdkDemo
注:我使用的Unity版本:2020.2.7f1c1 (64-bit),

二、下載Facebook SDK
Facebook為了方便Unity接入,官方做了封裝,大家直接下載For Unity版本的SDK即可,
地址:https://developers.facebook.com/docs/unity/downloads
注:訪問上面這個地址需要科學上網,
目前最新版本是9.1.0,點擊它進行下載,

下載下來后,它是一個unitypackage檔案,

三、匯入SDK
為了演示,我新建一個空的Unity工程,

把剛剛下載的unitypackage檔案匯入到工程中,

匯入成功后:

四、切換到Android平臺
在Build Settings中切換到Android平臺,

五、Dependencies.xml
在FacebookSDK/Plugins/Editor檔案夾中,有個Dependencies.xml:

里面配置了FacebookSDK依賴的一些庫:
<?xml version="1.0" encoding="utf-8"?>
<dependencies>
<androidPackages>
<androidPackage spec="com.parse.bolts:bolts-android:1.4.0" />
<androidPackage spec="com.facebook.android:facebook-core:[9.0, 10)" />
<androidPackage spec="com.facebook.android:facebook-applinks:[9.0, 10)" />
<androidPackage spec="com.facebook.android:facebook-login:[9.0, 10)" />
<androidPackage spec="com.facebook.android:facebook-share:[9.0, 10)" />
<androidPackage spec="com.facebook.android:facebook-gamingservices:[9.0, 10)" />
</androidPackages>
<iosPods>
<iosPod name="FBSDKCoreKit" version="~> 9.2" />
<iosPod name="FBSDKLoginKit" version="~> 9.2" />
<iosPod name="FBSDKShareKit" version="~> 9.2" />
<iosPod name="FBSDKGamingServicesKit" version="~> 9.2" />
</iosPods>
</dependencies>
我們在打包之前,需要先下載這些依賴的庫,下面執行Play Services Resolver便是下載這些依賴的庫檔案,
六、執行Play Services Resolver
點擊選單Assets / Play Services Resolver / Android Resolver / Resolver,

接著,它就會開始安裝和下載,一路點擊Yes和agree,耐心等待,

如果你本地沒有配置
JAVA_HOME,則會彈出這個報錯
需要在環境變數中配置一下JAVA_HOME環境變數:
如果點擊
Assets / Play Services Resolver / Android Resolver / Resolver沒有任何反應,可以在Player Settings中把Api Compatibility Levell設定為.NET 4.x,然后重試,
下載完成后,即可看到Plugins/Android目錄中多了很多aar檔案,

如果你是內網開發,你需要現在外網下載好這些庫檔案,然后再拷貝到內網工程中,
七、Edit Settings
點擊選單Facebook/Edit Settings:

如下:

關鍵幾個引數說明:
App Name:專案名稱
Facebook App Id:在Facebook開發者平臺上注冊的應用ID
Package Name:專案包名,例:com.linxinfa.game
點擊Regenerate Android Manifest按鈕,會生成AndroidManifest.xml

八、介面說明
1、初始化
在呼叫登錄之前,需要先執行初始化介面,官方示例:
// Include Facebook namespace
using Facebook.Unity;
// Awake function from Unity's MonoBehavior
void Awake ()
{
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.Log("Failed to Initialize the Facebook SDK");
}
}
private void OnHideUnity (bool isGameShown)
{
if (!isGameShown) {
// Pause the game - we will need to hide
Time.timeScale = 0;
} else {
// Resume the game - we're getting focus again
Time.timeScale = 1;
}
}
2、登錄
登錄介面,會拉起Facebook授權頁,
var perms = new List<string>(){"public_profile", "email"};
FB.LogInWithReadPermissions(perms, AuthCallback);
private void AuthCallback (ILoginResult result) {
if (FB.IsLoggedIn) {
// AccessToken class will have session details
var aToken = Facebook.Unity.AccessToken.CurrentAccessToken;
// Print current access token's User ID
Debug.Log(aToken.UserId);
// Print current access token's granted permissions
foreach (string perm in aToken.Permissions) {
Debug.Log(perm);
}
} else {
Debug.Log("User cancelled login");
}
}
3、快速登錄
如果登錄過一次,本地會快取票據,可以呼叫快速登錄,
判斷本地票據是否過期:
using Facebook.Unity;
if(null != AccessToken.CurrentAccessToken &&
AccessToken.CurrentAccessToken.ExpirationTime > System.DateTime.Now)
{
// 本地快取票據有效,可以呼叫快速登錄介面
}
快速登錄:
FB.Android.RetrieveLoginStatus(LoginStatusCallback);
private void LoginStatusCallback(ILoginStatusResult result) {
if (!string.IsNullOrEmpty(result.Error)) {
Debug.Log("Error: " + result.Error);
} else if (result.Failed) {
Debug.Log("Failure: Access Token could not be retrieved");
} else {
// Successfully logged user in
// A popup notification will appear that says "Logged in as <User Name>"
Debug.Log("Success: " + result.AccessToken.UserId);
}
}
4、登出
FB.LogOut();
5、分享
FB.ShareLink(
new Uri("https://developers.facebook.com/"),
callback: ShareCallback
);
private void ShareCallback (IShareResult result) {
if (result.Cancelled || !String.IsNullOrEmpty(result.Error)) {
Debug.Log("ShareLink Error: "+result.Error);
} else if (!String.IsNullOrEmpty(result.PostId)) {
// Print post identifier of the shared content
Debug.Log(result.PostId);
} else {
// Share succeeded without postID
Debug.Log("ShareLink success!");
}
}
6、支付
有三個介面:
public static void Pay(string product, string action = "purchaseitem", int quantity = 1,
int? quantityMin = null, int? quantityMax = null, string requestId = null,
string pricepointId = null, string testCurrency = null,
FacebookDelegate<IPayResult> callback = null);
public static void PayWithProductId(string productId, string action = "purchaseiap", int quantity = 1,
int? quantityMin = null, int? quantityMax = null, string requestId = null,
string pricepointId = null, string testCurrency = null,
FacebookDelegate<IPayResult> callback = null);
public static void PayWithProductId(string productId, string action = "purchaseiap",
string developerPayload = null, string testCurrency = null,
FacebookDelegate<IPayResult> callback = null);
呼叫示例:
FB.Canvas.Pay(this.payProduct, callback: this.HandleResult);
九、測驗
1、制作測驗界面
為了演示,我用UGUI制作一個簡單的界面,如下:

對應的Hierarchy視圖如下:

2、測驗腳本
寫個測驗腳本FacebookSdkTest.cs,掛到Canvas節點上,并賦值對應的ui變數:

FacebookSdkTest.cs代碼如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Facebook.Unity;
using System;
public class FacebookSdkTest : MonoBehaviour
{
public Text logText;
public Button loginBtn;
public Button logoutBtn;
public Button payBtn;
public Button shareBtn;
void Awake()
{
// 初始化
FB.Init(() =>
{
if (FB.IsInitialized)
{
FB.ActivateApp();
Debug.Log("Init Ok, AppId: " + FB.AppId);
}
else
{
Debug.Log("Failed to Initialize the Facebook SDK");
}
});
}
void Start()
{
logText.text = "";
Application.logMessageReceived += (string condition, string stackTrace, LogType type) =>
{
logText.text += condition + "\n";
};
loginBtn.onClick.AddListener(DoLogin);
logoutBtn.onClick.AddListener(DoLogout);
payBtn.onClick.AddListener(DoPay);
shareBtn.onClick.AddListener(DoShare);
}
private void DoLogin()
{
if(FB.IsLoggedIn)
{
Debug.Log("You have logined!");
return;
}
if (null != AccessToken.CurrentAccessToken && AccessToken.CurrentAccessToken.ExpirationTime > System.DateTime.Now)
{
// 快速登錄
FB.Android.RetrieveLoginStatus((result) =>
{
if (!string.IsNullOrEmpty(result.Error))
{
Debug.Log("Error: " + result.Error);
}
else if (result.Failed)
{
Debug.Log("Failure: Access Token could not be retrieved");
}
else
{
Debug.Log("Success: " + result.AccessToken.UserId);
}
});
}
else
{
// 登錄
var perms = new List<string>() { "public_profile", "email" };
FB.LogInWithReadPermissions(perms, (result) =>
{
if (FB.IsLoggedIn)
{
var aToken = AccessToken.CurrentAccessToken;
Debug.Log(aToken.UserId);
foreach (string perm in aToken.Permissions)
{
Debug.Log(perm);
}
}
else
{
Debug.Log("User cancelled login");
}
});
}
}
private void DoLogout()
{
FB.LogOut();
if (!FB.IsLoggedIn)
{
Debug.Log("Logout Successfully");
}
else
{
Debug.Log("Logout Failed");
}
}
private void DoPay()
{
FB.Canvas.Pay("diamond", callback: (result) =>
{
Debug.Log(result);
});
}
public void DoShare()
{
FB.ShareLink(new Uri("https://developers.facebook.com/"),
callback: (result) =>
{
if (result.Cancelled || !String.IsNullOrEmpty(result.Error))
{
Debug.Log("ShareLink Error: " + result.Error);
}
else if (!String.IsNullOrEmpty(result.PostId))
{
// Print post identifier of the shared content
Debug.Log(result.PostId);
}
else
{
// Share succeeded without postID
Debug.Log("ShareLink success!");
}
});
}
}
3、Editor環境下測驗
在Editor環境下測驗,效果如下:

4、發布成Android apk測驗
發布成Android apk測驗,在模擬器上的效果如下:

十、結束語
完畢,
喜歡Unity的同學,不要忘記點擊關注,如果有什么Unity相關的技術難題,也歡迎留言或私信~
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/278889.html
標籤:其他



