ActivityFacebookService.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. using System;
  2. using System.Collections.Generic;
  3. using Facebook.Unity;
  4. using UnityEngine;
  5. #if UNITY_IOS && !UNITY_EDITOR
  6. using Unity.Advertisement.IosSupport;
  7. #endif
  8. [Serializable]
  9. public sealed class ActivityFacebookConfig
  10. {
  11. public bool enabled;
  12. public string appId;
  13. public string clientToken;
  14. }
  15. public static class ActivityFacebookService
  16. {
  17. const int MaxPendingEvents = 32;
  18. public const string DefaultAppId = "1899769634516757";
  19. public const string DefaultClientToken = "ddd8dfb525bbe84b81fd0bb212a76475";
  20. static bool initializing;
  21. static string activeAppId;
  22. static readonly List<PendingFacebookEvent> pendingEvents = new List<PendingFacebookEvent>();
  23. #if UNITY_IOS && !UNITY_EDITOR
  24. static bool iosSdkInitialized;
  25. #endif
  26. [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
  27. static void ResetStatics()
  28. {
  29. initializing = false;
  30. activeAppId = null;
  31. pendingEvents.Clear();
  32. #if UNITY_IOS && !UNITY_EDITOR
  33. iosSdkInitialized = false;
  34. #endif
  35. }
  36. public static void ApplyConfig(ActivityFacebookConfig webConfig)
  37. {
  38. #if UNITY_IOS && !UNITY_EDITOR
  39. if (!IosAppTrackingService.IsCompleted)
  40. {
  41. IosAppTrackingService.RunOnce(() => ApplyConfig(webConfig));
  42. return;
  43. }
  44. #endif
  45. ApplyConfigImmediate(webConfig);
  46. }
  47. static void ApplyConfigImmediate(ActivityFacebookConfig webConfig)
  48. {
  49. string webAppId = webConfig != null ? webConfig.appId : null;
  50. string webClientToken = webConfig != null ? webConfig.clientToken : null;
  51. if (webConfig != null && webConfig.enabled && HasCredentials(webAppId, webClientToken))
  52. {
  53. Debug.Log("[Activity][Facebook] Using Facebook config from the activity webview.");
  54. Configure(true, webAppId, webClientToken);
  55. return;
  56. }
  57. if (webConfig == null)
  58. Debug.Log("[Activity][Facebook] Facebook config from the activity webview is empty; using default settings.");
  59. else if (!webConfig.enabled)
  60. Debug.Log("[Activity][Facebook] Facebook config from the activity webview is disabled; using default settings.");
  61. else
  62. Debug.LogWarning("[Activity][Facebook] Facebook config from the activity webview is incomplete; using default settings.");
  63. string defaultAppId = DefaultAppId;
  64. string defaultClientToken = DefaultClientToken;
  65. bool defaultEnabled = true;
  66. ActivityWebViewSettings settings = ActivityWebViewSettings.Instance;
  67. if (settings != null)
  68. {
  69. defaultEnabled = settings.facebookEnabled;
  70. if (HasCredentials(settings.facebookAppId, settings.facebookClientToken))
  71. {
  72. defaultAppId = settings.facebookAppId.Trim();
  73. defaultClientToken = settings.facebookClientToken.Trim();
  74. }
  75. }
  76. Configure(defaultEnabled, defaultAppId, defaultClientToken);
  77. }
  78. public static void Configure(bool enabled, string appId, string clientToken)
  79. {
  80. if (!enabled)
  81. {
  82. Debug.Log("[Activity][Facebook] Facebook SDK is disabled.");
  83. return;
  84. }
  85. appId = appId != null ? appId.Trim() : string.Empty;
  86. clientToken = clientToken != null ? clientToken.Trim() : string.Empty;
  87. if (!HasCredentials(appId, clientToken))
  88. {
  89. Debug.LogWarning("[Activity][Facebook] Facebook App ID or Client Token is empty.");
  90. return;
  91. }
  92. if (FB.IsInitialized)
  93. {
  94. if (string.IsNullOrEmpty(activeAppId) && !string.IsNullOrEmpty(FB.AppId))
  95. activeAppId = FB.AppId;
  96. if (!string.IsNullOrEmpty(activeAppId) && activeAppId != appId)
  97. {
  98. Debug.LogWarning(
  99. "[Activity][Facebook] Ignoring App ID '" + appId +
  100. "'. The SDK is already initialized with '" + activeAppId +
  101. "'. Apply the config before the first FB.Init call.");
  102. }
  103. #if UNITY_IOS && !UNITY_EDITOR
  104. LogIosTrackingStatus();
  105. #endif
  106. FB.ActivateApp();
  107. return;
  108. }
  109. if (initializing)
  110. return;
  111. initializing = true;
  112. activeAppId = appId;
  113. #if UNITY_IOS && !UNITY_EDITOR
  114. try
  115. {
  116. FacebookNativeBridge.IOS_FBSetDynamicCredentials(appId, clientToken);
  117. if (!iosSdkInitialized)
  118. {
  119. FacebookNativeBridge.IOS_FBInitializeSDK();
  120. iosSdkInitialized = true;
  121. }
  122. }
  123. catch (Exception exception)
  124. {
  125. Debug.LogWarning("[Activity][Facebook] Failed to initialize the iOS Facebook SDK: " + exception.Message);
  126. }
  127. #endif
  128. try
  129. {
  130. Debug.Log("[Activity][Facebook] Initializing Facebook SDK. App ID: " + appId + ".");
  131. FB.Init(appId, clientToken, onInitComplete: OnInitComplete);
  132. }
  133. catch (Exception exception)
  134. {
  135. initializing = false;
  136. activeAppId = null;
  137. Debug.LogWarning("[Activity][Facebook] Facebook initialization failed: " + exception.Message);
  138. }
  139. }
  140. public static void LogEvent(string action, float value, string currency = "USD")
  141. {
  142. var payload = new ActivityFacebookEventPayload { value = value, currency = currency };
  143. LogEvent(action, JsonUtility.ToJson(payload));
  144. }
  145. public static void LogEvent(string action, string data)
  146. {
  147. if (string.IsNullOrWhiteSpace(action))
  148. return;
  149. if (!FB.IsInitialized)
  150. {
  151. if (pendingEvents.Count < MaxPendingEvents)
  152. {
  153. pendingEvents.Add(new PendingFacebookEvent(action, data));
  154. Debug.Log("[Activity][Facebook] SDK is not ready; queued event: " + action);
  155. }
  156. else
  157. {
  158. Debug.LogWarning("[Activity][Facebook] Event queue is full; dropped event: " + action);
  159. }
  160. return;
  161. }
  162. ActivityFacebookEventPayload payload = null;
  163. if (!string.IsNullOrWhiteSpace(data))
  164. {
  165. try
  166. {
  167. payload = JsonUtility.FromJson<ActivityFacebookEventPayload>(data);
  168. }
  169. catch (Exception exception)
  170. {
  171. Debug.LogWarning("[Activity][Facebook] Invalid event payload: " + exception.Message);
  172. }
  173. }
  174. float value = payload != null ? payload.value : 0f;
  175. string currency = payload != null ? payload.currency : null;
  176. Dictionary<string, object> parameters = BuildParameters(currency);
  177. switch (action.Trim().ToLowerInvariant())
  178. {
  179. case "purchased":
  180. FB.LogPurchase((decimal)value, string.IsNullOrWhiteSpace(currency) ? "USD" : currency, parameters);
  181. break;
  182. case "addtocart":
  183. FB.LogAppEvent(AppEventName.AddedToCart, value, parameters);
  184. break;
  185. case "addtowishlist":
  186. FB.LogAppEvent(AppEventName.AddedToWishlist, value, parameters);
  187. break;
  188. case "completeregistration":
  189. FB.LogAppEvent(AppEventName.CompletedRegistration, value, parameters);
  190. break;
  191. case "rated":
  192. FB.LogAppEvent(AppEventName.Rated, value, parameters);
  193. break;
  194. default:
  195. FB.LogAppEvent(action, value, parameters);
  196. break;
  197. }
  198. }
  199. static void OnInitComplete()
  200. {
  201. initializing = false;
  202. if (!FB.IsInitialized)
  203. {
  204. Debug.LogWarning("[Activity][Facebook] Facebook SDK initialization failed.");
  205. return;
  206. }
  207. #if UNITY_IOS && !UNITY_EDITOR
  208. LogIosTrackingStatus();
  209. #endif
  210. FB.ActivateApp();
  211. string initializedAppId = string.IsNullOrEmpty(FB.AppId) ? activeAppId : FB.AppId;
  212. Debug.Log("[Activity][Facebook] Facebook SDK initialized. App ID: " +
  213. (string.IsNullOrEmpty(initializedAppId) ? "unknown" : initializedAppId) + ".");
  214. FlushPendingEvents();
  215. }
  216. static bool HasCredentials(string appId, string clientToken)
  217. {
  218. return !string.IsNullOrWhiteSpace(appId) && !string.IsNullOrWhiteSpace(clientToken);
  219. }
  220. static void FlushPendingEvents()
  221. {
  222. if (pendingEvents.Count == 0)
  223. return;
  224. var events = pendingEvents.ToArray();
  225. pendingEvents.Clear();
  226. foreach (var pending in events)
  227. LogEvent(pending.action, pending.data);
  228. }
  229. #if UNITY_IOS && !UNITY_EDITOR
  230. static void LogIosTrackingStatus()
  231. {
  232. if (!FB.IsInitialized)
  233. return;
  234. var status = ATTrackingStatusBinding.GetAuthorizationTrackingStatus();
  235. Debug.Log("[Activity][Facebook] ATT authorization status: " + status);
  236. }
  237. #endif
  238. static Dictionary<string, object> BuildParameters(string currency)
  239. {
  240. var parameters = new Dictionary<string, object>();
  241. if (!string.IsNullOrWhiteSpace(currency))
  242. parameters[AppEventParameterName.Currency] = currency;
  243. return parameters;
  244. }
  245. #pragma warning disable 0649
  246. [Serializable]
  247. sealed class ActivityFacebookEventPayload
  248. {
  249. public float value;
  250. public string currency;
  251. }
  252. #pragma warning restore 0649
  253. sealed class PendingFacebookEvent
  254. {
  255. public readonly string action;
  256. public readonly string data;
  257. public PendingFacebookEvent(string action, string data)
  258. {
  259. this.action = action;
  260. this.data = data;
  261. }
  262. }
  263. }