public AccessToken(AccessToken_JSON json) { this.token = json.access_token; this.type = json.token_type; this.expiration = DateTime.Now.AddSeconds(json.expires_in); this.scope = json.scope; }
/// <summary> /// Coroutine checks the cached access token validity. If it isn't valid, retrieves a token from PlayerPrefs if it exists, or get a new token from Blizzard using OAuth. /// </summary> /// <param name="region">Region used to get the access token.</param> /// <param name="result">Action to execute with the access token once retrieved.</param> /// <returns></returns> public static IEnumerator CheckAccessToken(BattleNetRegion region = BattleNetRegion.UnitedStates, Action <string> result = null) { DateTime currentDate = DateTime.Now; if (accessToken != null && accessToken.token.Length <= 0 && accessToken.expiration >= currentDate) { // If we already have a valid access token in the cache, update it and skip the rest SetPrefsToken(PREFS_TOKEN_GENERAL, accessToken); Debug.LogFormat("Cached token still valid : '{0}' (expires {1})", accessToken.token, accessToken.expiration.ToString()); if (result != null) { result(accessToken.token); } yield break; } else { // Making sure that we don't keep anything from the invalid "token" accessToken = null; // If the token is invalid, try to fetch it from the PlayerPrefs first AccessToken storedToken = GetPrefsToken(PREFS_TOKEN_GENERAL); if (storedToken != null && storedToken.token.Length > 0 && storedToken.expiration > currentDate) { // If the stored access token is still valid, replace the cache with it and skip the rest Debug.LogFormat("Stored token still valid : '{0}' (expires {1})", storedToken.token, storedToken.expiration.ToString()); if (result != null) { result(storedToken.token); } accessToken = storedToken; yield break; } else { Debug.Log("Invalid access token, retrieving a new token..."); // The stored token is also invalid, fetch an entirely new token, cache it, and store it string url = string.Concat(URL_START, RegionToString(region), OAUTH_TOKEN_URL); Dictionary <string, string> form = new Dictionary <string, string>() { { "grant_type", "client_credentials" }, { "client_id", AppInfos.BlizzardClientID }, { "client_secret", AppInfos.BlizzardClientSecret } }; UnityWebRequest tokenRequest = UnityWebRequest.Post(url, form); yield return(tokenRequest.SendWebRequest()); if (!tokenRequest.isNetworkError && !tokenRequest.isHttpError) { string resultContent = tokenRequest.downloadHandler.text; AccessToken_JSON json = JsonUtility.FromJson <AccessToken_JSON>(resultContent); accessToken = new AccessToken(json); SetPrefsToken(PREFS_TOKEN_GENERAL, accessToken); Debug.LogFormat("Access token granted : '{0}' ; expires {1}", accessToken.token, accessToken.expiration.ToString()); if (result != null) { result(accessToken.token); } } else { Debug.LogError("<color=red>Error : </color>" + tokenRequest.error); } } } }