WexTokenManager.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Hotline.CallCenter.Configs;
  7. using Hotline.CallCenter.Devices;
  8. using Microsoft.Extensions.DependencyInjection;
  9. using Microsoft.Extensions.Options;
  10. using Wex.Sdk;
  11. using XF.Domain.Cache;
  12. using XF.Domain.Dependency;
  13. using XF.Domain.Exceptions;
  14. namespace Hotline.Wex
  15. {
  16. public class WexTokenManager : ITokenManager, ISingletonDependency
  17. {
  18. private readonly IServiceScopeFactory _serviceScopeFactory;
  19. private const string WexToken = "WexToken";
  20. public WexTokenManager(IServiceScopeFactory serviceScopeFactory)
  21. {
  22. _serviceScopeFactory = serviceScopeFactory;
  23. }
  24. public async Task<string> GetTokenAsync(CancellationToken cancellationToken)
  25. {
  26. using var scope = _serviceScopeFactory.CreateScope();
  27. var cacheWexToken = scope.ServiceProvider.GetService<ITypedCache<WexToken>>();
  28. var token = await cacheWexToken.GetAsync(WexToken, cancellationToken);
  29. if (token is null)
  30. {
  31. token = await GetWexTokenAsync(scope, cancellationToken);
  32. if (token == null) throw new UserFriendlyException("未获取到呼叫中心请求token");
  33. var success = DateTime.TryParse(token.ExpireTime, out var expire);
  34. var ts = success ? expire.AddMinutes(-5) - DateTime.Now : TimeSpan.FromHours(2);
  35. await cacheWexToken.SetAsync(WexToken, token, ts, cancellationToken);
  36. }
  37. return token.Token;
  38. }
  39. public async Task RefreshTokenAsync(CancellationToken cancellationToken)
  40. {
  41. using var scope = _serviceScopeFactory.CreateScope();
  42. var cacheWexToken = scope.ServiceProvider.GetService<ITypedCache<WexToken>>();
  43. var token = await GetWexTokenAsync(scope, cancellationToken);
  44. if (token == null) throw new UserFriendlyException("未获取到呼叫中心请求token");
  45. var success = DateTime.TryParse(token.ExpireTime, out var expire);
  46. var ts = success ? expire.AddMinutes(-5) - DateTime.Now : TimeSpan.FromHours(2);
  47. await cacheWexToken.SetAsync(WexToken, token, ts, cancellationToken);
  48. }
  49. private async Task<WexToken> GetWexTokenAsync(IServiceScope scope, CancellationToken cancellationToken)
  50. {
  51. var callCenterConfiguration =
  52. scope.ServiceProvider.GetService<IOptionsSnapshot<CallCenterConfiguration>>();
  53. var wexClient = scope.ServiceProvider.GetService<IWexClient>();
  54. var wexConfig = callCenterConfiguration.Value.Wex;
  55. var request = new TokenRequest
  56. {
  57. Username = wexConfig.Username,
  58. Password = wexConfig.Password,
  59. };
  60. return await wexClient.GetTokenAsync(request, cancellationToken);
  61. }
  62. }
  63. }