FBHandler.cs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. using Facebook.Unity;
  2. using Facebook.Unity.Editor;
  3. using GUPS.Obfuscator.Attribute;
  4. using Newtonsoft.Json;
  5. using Newtonsoft.Json.Linq;
  6. using System;
  7. using System.Collections;
  8. using System.Collections.Generic;
  9. using System.Globalization;
  10. using System.Runtime.InteropServices;
  11. using System.Security.Cryptography;
  12. using UnityEngine;
  13. using Cysharp.Threading.Tasks;
  14. #if UNITY_IOS
  15. using Unity.Advertisement.IosSupport;
  16. #endif
  17. public static class DictionaryExtensions
  18. {
  19. public static bool TryGetParams<T>(this Dictionary<string, object> parameters, string key, out T value)
  20. {
  21. if (parameters == null || !parameters.TryGetValue(key, out var rawValue) || rawValue == null)
  22. {
  23. value = default;
  24. return false;
  25. }
  26. if (rawValue is T typedValue)
  27. {
  28. value = typedValue;
  29. return true;
  30. }
  31. try
  32. {
  33. var targetType = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);
  34. if (targetType.IsEnum)
  35. {
  36. value = (T)Enum.Parse(targetType, rawValue.ToString(), ignoreCase: true);
  37. return true;
  38. }
  39. value = (T)Convert.ChangeType(rawValue, targetType, CultureInfo.InvariantCulture);
  40. return true;
  41. }
  42. catch (Exception)
  43. {
  44. value = default;
  45. return false;
  46. }
  47. }
  48. }
  49. [DoNotObfuscateClass]
  50. [DoNotObfuscateMethodBody]
  51. public class FBHandler
  52. {
  53. #if UNITY_IOS && !UNITY_EDITOR
  54. [DllImport("__Internal")]
  55. private static extern void IOS_FBSetDynamicCredentials(string appId, string clientToken);
  56. #endif
  57. struct EventData
  58. {
  59. public string eventName;
  60. public string data;
  61. }
  62. private const string EVENT_REGISTER = "completeregistration";
  63. private const string EVENT_ADDTOWISHLIST = "addtowishlist";
  64. private const string EVENT_PURCHASED = "purchased";
  65. private const string EVENT_ADDTOCART = "addtocart";
  66. private const string LOCAL_ATT_STATUS = "LOCAL_ATT_STATUS";
  67. private static readonly Queue<EventData> pendingFBEvents = new Queue<EventData>();
  68. public static void Init(string appID = "", string token = "")
  69. {
  70. appID = appID?.Trim();
  71. token = token?.Trim();
  72. if (FB.IsInitialized) return;
  73. #if UNITY_IOS
  74. try
  75. {
  76. var att = PlayerPrefs.GetInt(LOCAL_ATT_STATUS, 0);
  77. bool authorized = att == (int)ATTrackingStatusBinding.AuthorizationTrackingStatus.AUTHORIZED;
  78. OnInit(appID, token, () =>
  79. {
  80. FB.Mobile.SetAdvertiserTrackingEnabled(authorized);
  81. FB.Mobile.SetAdvertiserIDCollectionEnabled(authorized);
  82. });
  83. }
  84. catch (Exception e)
  85. {
  86. Debug.LogError($"FBHandler Init Error: {e}");
  87. }
  88. #else
  89. OnInit(appID, token);
  90. #endif
  91. }
  92. public static async void RequestAtt()
  93. {
  94. var att = await GetATT();
  95. await UniTask.SwitchToMainThread();
  96. PlayerPrefs.SetInt(LOCAL_ATT_STATUS, att);
  97. }
  98. private static UniTask<int> GetATT()
  99. {
  100. var completionSource = new UniTaskCompletionSource<int>();
  101. #if UNITY_IOS
  102. try
  103. {
  104. ATTrackingStatusBinding.RequestAuthorizationTracking(status =>
  105. {
  106. completionSource.TrySetResult(status);
  107. });
  108. }
  109. catch
  110. {
  111. completionSource.TrySetResult(0);
  112. }
  113. #endif
  114. return completionSource.Task;
  115. }
  116. private static void OnInit(string appID = "", string token = "", Action callback = null)
  117. {
  118. InitDelegate handleInit = () =>
  119. {
  120. if (!FB.IsInitialized)
  121. {
  122. pendingFBEvents.Clear();
  123. Debug.LogError("Facebook SDK initialization failed; pending WebView events were discarded.");
  124. return;
  125. }
  126. callback?.Invoke();
  127. FB.ActivateApp();
  128. while (pendingFBEvents.Count > 0)
  129. {
  130. var pendingEvent = pendingFBEvents.Dequeue();
  131. OnLogEvent(pendingEvent.eventName, pendingEvent.data);
  132. }
  133. };
  134. if (!string.IsNullOrEmpty(appID) && !string.IsNullOrEmpty(token))
  135. {
  136. #if UNITY_IOS && !UNITY_EDITOR
  137. IOS_FBSetDynamicCredentials(appID, token);
  138. #endif
  139. FB.Init(appID, token, onInitComplete: handleInit);
  140. }
  141. else
  142. {
  143. FB.Init(handleInit);
  144. }
  145. }
  146. public static void LogEvent(string eventName, string data)
  147. {
  148. if (string.IsNullOrWhiteSpace(eventName))
  149. {
  150. Debug.LogWarning("Ignored FB event with an empty event name.");
  151. return;
  152. }
  153. if (!FB.IsInitialized)
  154. {
  155. AppRuntimes.Log("Fb not initialized!!");
  156. pendingFBEvents.Enqueue(new EventData
  157. {
  158. eventName = eventName,
  159. data = data,
  160. });
  161. return;
  162. }
  163. AppRuntimes.Log("Fb log event: " + eventName);
  164. OnLogEvent(eventName, data);
  165. }
  166. private static void OnLogEvent(string eventName, string data)
  167. {
  168. var json = JToken.Parse(data);
  169. if (!(json is JObject jsonObject)) return;
  170. float valueToSum = 0;
  171. string currency = string.Empty;
  172. if (jsonObject.TryGetValue("value", out var valueToken))
  173. {
  174. valueToSum = valueToken.Value<float>();
  175. }
  176. if (jsonObject.TryGetValue("currency", out var currentToken))
  177. {
  178. currency = currentToken.Value<string>();
  179. }
  180. var fbParams = new Dictionary<string, object>()
  181. {
  182. [AppEventParameterName.Currency] = currency,
  183. };
  184. eventName = eventName.Trim();
  185. switch (eventName)
  186. {
  187. case EVENT_REGISTER:
  188. FB.LogAppEvent(AppEventName.CompletedRegistration, valueToSum, fbParams);
  189. return;
  190. case EVENT_ADDTOWISHLIST:
  191. FB.LogAppEvent(AppEventName.AddedToWishlist, valueToSum, fbParams);
  192. return;
  193. case EVENT_PURCHASED:
  194. FB.LogPurchase((decimal)valueToSum, currency, fbParams);
  195. return;
  196. case EVENT_ADDTOCART:
  197. FB.LogAppEvent(AppEventName.AddedToCart, valueToSum, fbParams);
  198. return;
  199. }
  200. FB.LogAppEvent(eventName, valueToSum, fbParams);
  201. }
  202. }