TokenManager.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace cuidian.OpenApi.Utils
  7. {
  8. /// <summary>
  9. /// Token 生命周期维护器。平台 Token 生效期为 2 小时,SDK 1小时55分钟为重新获取新 token 的周期。
  10. /// </summary>
  11. public class TokenManager
  12. {
  13. private static long? timestamp;
  14. private const long MILLISECONDS_EXPIRED = 6900000; //1000 * 60 * 60 * 2 - 1000 * 60 * 5 (1小时55分钟);
  15. private static string token = String.Empty;
  16. public static string GetToken()
  17. {
  18. long nowTimestamp = (long)DateTime.Now.Subtract(DateTime.Parse("1970-1-1")).TotalMilliseconds;
  19. if ((timestamp == null)
  20. || (nowTimestamp - timestamp > MILLISECONDS_EXPIRED))
  21. {
  22. BusinessObject bo = (new Token()).Get();
  23. if (!bo.IsError)
  24. {
  25. TokenManager.token = bo.Full.GetObject("token").GetValue("id").ToString();
  26. }
  27. TokenManager.timestamp = (long)DateTime.Now.Subtract(DateTime.Parse("1970-1-1")).TotalMilliseconds;
  28. }
  29. return TokenManager.token;
  30. }
  31. }
  32. }