c1_unity/Assets/Scripts/Common/SDK/BFLoginSDKManager.cs
2023-04-21 20:37:42 +08:00

506 lines
16 KiB
C#

using System.Diagnostics;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using BF.NativeCore;
using BF.NativeCore.ThirdPlatform;
using BestHTTP;
using System.Text;
using Facebook.MiniJSON;
using Newtonsoft.Json;
#if UNITY_IOS
using UnityEngine.SignInWithApple;
#endif
namespace BF
{
[Serializable]
public class BFLoginInfo
{
public int loginType;
public string msg;
public BFLoginInfo(int loginType, string msg)
{
this.loginType = loginType;
this.msg = msg;
}
}
public class BFLoginSDKManager : MonoBehaviour, IULoginListener
{
private const string LOGIN_TOKEN = "LOGIN_TOKEN";
private const string SDK_LOGIN_TYPE = "SDK_LOGIN_TYPE";
private const string SDK_UID = "SDK_UID";
private const string SDK_TOKEN = "SDK_TOKEN";
public int AccountLoginSeq = 0;
//lua回调接口
public Action<int, string> luaLoginCallback;
public Action<int, string> luaLogoutCallback;
public Action<int, string> luaBindCallback;
public Action<bool, string> luaServerListCallback;
public Action<bool, string> luaAccountLoginCallback;
public Action<bool, string> luaAccountChangeCallback;
// public FacebookSdk FBSdk = new FacebookSdk();
public BFAccountInfo accountInfo; // 账号信息
public string firebaseToken = string.Empty;
public Action<string> luaFirebaseTokenCallback;
#if UNITY_IOS
public SignInWithApple signInWithApple;
#endif
/// <summary>
/// 是否处于登陆状态
/// </summary>
/// <value></value>
public bool SDKLogin
{
get;
private set;
}
void Awake()
{
// facebook
BFLog.Log("FBSdk.Init");
// FBSdk.Init();
// FBSdk.SetULoginListener(this);
// appid 登陆
#if UNITY_IOS
signInWithApple = gameObject.AddComponent<SignInWithApple>();
#endif
}
void OnApplicationPause(bool pauseStatus)
{
// FBSdk.OnApplicationPause(pauseStatus);
}
void Start()
{
SDKLogin = false;
InitListener();
}
public void InitListener()
{
// string url = BFPlatform.GetLoginCenterURL();
// BFLog.Log("初始化登陆SDK URL:" + url);
// Dictionary<string, string> gameInfo = new Dictionary<string, string>();
// gameInfo["channel"] = CHANNEL;//预留字段 暂无用
// gameInfo["language"] = LANGUAGE;//预留字段 暂无用
// gameInfo["game_cd"] = GAME_CD;//game_cd 地址 AOD约定为1004
// ULogin.Initialize(url, gameInfo);
// ULogin.UseOnceBFIdForInstall(USE_ONCE_BFID_FOR_INSTALL);
// ULogin.SetULoginListener(this);
// google
BFMain.Instance.SDKMgr.BFNativeSDKMgr.InitGoogleLogin();
}
public void SetLuaLoginCallback(Action<int, string> callback)
{
luaLoginCallback = callback;
}
public void SetLuaLogoutCallback(Action<int, string> callback)
{
luaLogoutCallback = callback;
}
public void SetLuaBindCallback(Action<int, string> callback)
{
luaBindCallback = callback;
}
public void SetLuaServerListCallback(Action<bool, string> callback)
{
luaServerListCallback = callback;
}
public void SetLuaAccountLoginCallback(Action<bool, string> callback)
{
luaAccountLoginCallback = callback;
}
public void SetLuaAccountChangeCallback(Action<bool, string> callback)
{
luaAccountChangeCallback = callback;
}
public string GetNewPlayerGuid()
{
Guid g = Guid.NewGuid();
return g.ToString();
}
/// <summary>
/// 统一登陆接口
/// </summary>
/// <param name="type"></param>
public void Login(LoginType type)
{
BFLog.Log("新版 登陆中心 Login:" + type);
if (type == LoginType.Facebook)
{
// FBSdk.Login();
}
else if(type == LoginType.Google)
{
BFMain.Instance.SDKMgr.BFNativeSDKMgr.GoogleLogin();
}
else if(type == LoginType.Apple)
{
#if UNITY_IOS
if (!ReferenceEquals(signInWithApple, null))
{
signInWithApple.Login(AppleLoginCallback);
}
#endif
}
}
/// <summary>
/// 登出
/// </summary>
public void Logout(LoginType type)
{
if (type == LoginType.Facebook)
{
// FBSdk.Logout();
}
else if(type == LoginType.Google)
{
BFMain.Instance.SDKMgr.BFNativeSDKMgr.GoogleLogout();
}
}
/// <summary>
/// 获取登陆中心的Token
/// </summary>
/// <returns></returns>
public string GetBFToken()
{
// return ULogin.GetBFToken();
return "";
}
public byte[] GetBFTokenToBytes()
{
// string token = ULogin.GetBFToken();
string token = "";
if (!string.IsNullOrEmpty(token))
{
return System.Text.Encoding.Default.GetBytes(token);
}
else
{
return null;
}
}
public void SetAccountInfo(string json)
{
if(string.IsNullOrEmpty(json))
{
return;
}
var info = JsonConvert.DeserializeObject<BFAccountInfo>(json);
if (info.code != 0)
{
return;
}
accountInfo = info;
PlayerPrefs.SetString(LOGIN_TOKEN, accountInfo.token);
}
public void SetAccountInfoBind(string json)
{
if(string.IsNullOrEmpty(json))
{
return;
}
var bind = JsonConvert.DeserializeObject<List<string>>(json);
accountInfo.bind = bind;
}
public BFAccountInfo GetAccountInfo(string json)
{
// accountInfo = JsonConvert.DeserializeObject<BFAccountInfo>(json);
return accountInfo;
}
public void GoogleLoginComplete(bool succ, string msg)
{
if (succ)
{
LoginComplete(LoginType.Google, ULoginResult.Success, msg);
}
else
{
LoginComplete(LoginType.Google, ULoginResult.Failed, msg);
}
}
public void GoogleLogoutComplete(bool succ)
{
if(succ)
{
LogoutComplete(LoginType.Google, ULoginResult.Success, "");
}
else
{
LogoutComplete(LoginType.Google, ULoginResult.Failed, "");
}
}
#region IULoginListener
public void LoginComplete(LoginType loginType, ULoginResult result, string msg)
{
BFLog.Log(string.Format("LoginComplete : LoginType = {0}, result = {1}, msg = {2}", loginType, result, msg));
//更新状态
if (result == ULoginResult.Success)
{
SDKLogin = true;
}
//lua 回调
if (luaLoginCallback != null)
{
BFLoginInfo info = new BFLoginInfo((int)loginType, msg);
string json = JsonUtility.ToJson(info);
BFLog.Log(string.Format("json = {0}", json));
luaLoginCallback((int)result, json);
}
}
public void LogoutComplete(LoginType loginType, ULoginResult result, string msg)
{
BFLog.Log(string.Format("LogoutComplete : LoginType = {0}, result = {1}, msg = {2}", loginType, result, msg));
//更新状态
if (result == ULoginResult.Success)
{
SDKLogin = false;
}
if (luaLogoutCallback != null)
{
BFLoginInfo info = new BFLoginInfo((int)loginType, msg);
string json = JsonUtility.ToJson(info);
luaLogoutCallback((int)result, json);
}
}
public void BindComplete(ULoginResult result, string msg)
{
}
#endregion
public void PostWithURL(string url, string data, Action<HTTPRequest, HTTPResponse> callback)
{
var httpRequest = new HTTPRequest(new Uri(url), HTTPMethods.Post, (req, httpResponse) =>
{
callback?.Invoke(req, httpResponse);
});
httpRequest.SetHeader("Content-Type", "application/x-www-form-urlencoded");
httpRequest.RawData = Encoding.UTF8.GetBytes(data);
httpRequest.Send();
}
public void GetWithURL(string url, Action<HTTPRequest, HTTPResponse> callback)
{
var httpRequest = new HTTPRequest(new Uri(url), HTTPMethods.Get, (req, httpResponse) =>
{
callback?.Invoke(req, httpResponse);
});
httpRequest.Send();
}
public void GetServerList(string requestUrl)
{
GetWithURL(requestUrl, (req, httpResponse) =>
{
if(null != httpResponse){
luaServerListCallback?.Invoke(httpResponse.IsSuccess, Encoding.UTF8.GetString(httpResponse.Data));
}
else{
luaServerListCallback?.Invoke(false, "");
}
});
}
public void StartAccountChange(string url, string requestArgsJson, int sdkLoginType)
{
if (sdkLoginType == Convert.ToInt32(LoginType.None) || sdkLoginType == Convert.ToInt32(LoginType.Guest))
{
string requestUrl = string.Format("{0}/guestlogin", url);
OnStartAccountChange(requestUrl, requestArgsJson);
return;
}
if (sdkLoginType == Convert.ToInt32(LoginType.Facebook))
{
string requestUrl = string.Format("{0}/facebooklogin", url);
OnStartAccountChange(requestUrl, requestArgsJson);
return;
}
if (sdkLoginType == Convert.ToInt32(LoginType.Google))
{
string requestUrl = string.Format("{0}/googlelogin", url);
OnStartAccountChange(requestUrl, requestArgsJson);
return;
}
if (sdkLoginType == Convert.ToInt32(LoginType.Test))
{
string requestUrl = string.Format("{0}/testlogin", url);
OnStartAccountChange(requestUrl, requestArgsJson);
return;
}
}
public void StartAccountBind(int sdkLoginType, string url, string requestArgsJson, Action<bool, string> luaBindCallback)
{
string requestUrl;
if (sdkLoginType == Convert.ToInt32(LoginType.Google))
{
requestUrl = string.Format("{0}/bindgoogle", url);
}
else if(sdkLoginType == Convert.ToInt32(LoginType.Facebook))
{
requestUrl = string.Format("{0}/bindfacebook", url);
}
else
{
return;
}
PostWithURL(requestUrl, requestArgsJson, (req, httpResponse) =>
{
if(null != httpResponse){
luaBindCallback?.Invoke(httpResponse.IsSuccess, Encoding.UTF8.GetString(httpResponse.Data));
}
else{
luaBindCallback?.Invoke(false, "");
}
});
}
public void StartAccountLogin(string url, string requestArgsJson)
{
string loginToken = PlayerPrefs.GetString(LOGIN_TOKEN, "");
if (!string.IsNullOrEmpty(loginToken))
{
string requestUrl = string.Format("{0}/tokenlogin", url);
OnStartAccountLogin(requestUrl, requestArgsJson);
return;
}
int sdkLoginType = PlayerPrefs.GetInt(SDK_LOGIN_TYPE, 0);
if (sdkLoginType == Convert.ToInt32(LoginType.None) || sdkLoginType == Convert.ToInt32(LoginType.Guest))
{
string requestUrl = string.Format("{0}/guestlogin", url);
OnStartAccountLogin(requestUrl, requestArgsJson);
return;
}
if (sdkLoginType == Convert.ToInt32(LoginType.Facebook))
{
string requestUrl = string.Format("{0}/facebooklogin", url);
OnStartAccountLogin(requestUrl, requestArgsJson);
return;
}
if (sdkLoginType == Convert.ToInt32(LoginType.Google))
{
string requestUrl = string.Format("{0}/googlelogin", url);
OnStartAccountLogin(requestUrl, requestArgsJson);
return;
}
if (sdkLoginType == Convert.ToInt32(LoginType.Test))
{
string requestUrl = string.Format("{0}/testlogin", url);
OnStartAccountLogin(requestUrl, requestArgsJson);
return;
}
PlayerPrefs.DeleteKey(LOGIN_TOKEN);
PlayerPrefs.SetInt(SDK_LOGIN_TYPE, 0);
StartAccountLogin(url, requestArgsJson);
}
public void OnStartAccountLogin(string url, string requestArgsJson)
{
PostWithURL(url, requestArgsJson, (req, httpResponse) =>
{
if(null != httpResponse){
var rspData = Encoding.UTF8.GetString(httpResponse.Data);
luaAccountLoginCallback?.Invoke(httpResponse.IsSuccess, rspData);
}
else{
luaAccountLoginCallback?.Invoke(false, "");
}
});
}
public void OnStartAccountChange(string url, string requestArgsJson)
{
PostWithURL(url, requestArgsJson, (req, httpResponse) =>
{
if(null != httpResponse){
luaAccountChangeCallback?.Invoke(httpResponse.IsSuccess, Encoding.UTF8.GetString(httpResponse.Data));
}
else{
luaAccountChangeCallback?.Invoke(false, "");
}
});
}
public void SetFirebaseToken(string token)
{
this.firebaseToken = token;
this.luaFirebaseTokenCallback?.Invoke(this.firebaseToken);
}
public void GetFirebaseToken(Action<string> callback)
{
this.luaFirebaseTokenCallback = callback;
if(this.firebaseToken != string.Empty)
{
this.luaFirebaseTokenCallback?.Invoke(this.firebaseToken);
}
else
{
BFMain.Instance.SDKMgr.BFNativeSDKMgr.GetFirebaseToken();
}
}
#if UNITY_IOS
private void AppleLoginCallback(SignInWithApple.CallbackArgs args)
{
if (!string.IsNullOrEmpty(args.error))
{
LoginComplete(LoginType.Apple, ULoginResult.Failed, args.error);
return;
}
//登录成功
if (!args.userInfo.userId.Equals(""))
{
string str = "{\"Token\":\"" + args.userInfo.idToken + "\",\"UserId\":\"" + args.userInfo.userId + "\"}";
LoginComplete(LoginType.Apple, ULoginResult.Success, str);
}
else
{
LoginComplete(LoginType.Apple, ULoginResult.Failed, "");
}
}
#endif
}
}