You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
DS7/DSWeb/Dispatch/Helper/TokenHelper.cs

131 lines
4.6 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using DSWeb.Areas.Dispatch.DB;
using log4net;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
namespace DSWeb.Areas.Dispatch.Helper
{
public class TokenHelper
{
private static readonly int TokenRefreshInMiniute = 5;
public static bool GetMpToken(string appid, out string token, out string errorMsg)
{
ILog logger = LogManager.GetLogger("TokenHelper");
DataContext dataContext = new DataContext();
var config = dataContext.MpConfigs.FirstOrDefault(c => c.AppId == appid);
if (config == null)
{
token = null;
errorMsg = $"未找到指定的AppId配置:{appid}";
logger.Error(errorMsg);
return false;
}
if (string.IsNullOrWhiteSpace(config.Token) || !config.ExpireTime.HasValue || config.ExpireTime.Value < DateTime.Now.AddMinutes(TokenRefreshInMiniute))
{
int expireIn = 0;
bool success = GetToken(appid, config.AppSecret, out token, out expireIn, out errorMsg);
if (success)
{
config.Token = token;
config.LastUpdate = DateTime.Now;
config.ExpireTime = DateTime.Now.AddSeconds(expireIn);
dataContext.SaveChanges();
return true;
}
else
{
return false;
}
}
else
{
token = config.Token;
errorMsg = "";
return true;
}
}
public static string RefreshTokens()
{
ILog logger = LogManager.GetLogger("TokenHelper");
try
{
DataContext dataContext = new DataContext();
DateTime dtExpire = DateTime.Now.AddMinutes(TokenRefreshInMiniute);
var list = dataContext.MpConfigs.Where(c => !c.ExpireTime.HasValue || c.ExpireTime.Value < dtExpire).ToList();
StringBuilder sbError = new StringBuilder();
foreach (var item in list)
{
string token = string.Empty;
int expireIn = 0;
string errorMsg = string.Empty;
bool success = GetToken(item.AppId, item.AppSecret, out token, out expireIn, out errorMsg);
if (success)
{
logger.Debug($"获取公众号token发送成功{item.AppId} {token}");
item.Token = token;
item.LastUpdate = DateTime.Now;
item.ExpireTime = DateTime.Now.AddSeconds(expireIn);
}
else
{
sbError.AppendLine($"获取AppId为{item.AppId}的token时出错{errorMsg}");
}
}
dataContext.SaveChanges();
if (sbError.Length > 0)
{
logger.Error($"获取公众号token发送错误{sbError}");
}
return sbError.ToString();
}
catch (Exception ex)
{
logger.Error($"获取公众号token发送错误{ex.Message}");
logger.Error(ex.StackTrace);
return ex.Message;
}
}
private static bool GetToken(string appid, string appsecret, out string token, out int expiresIn, out string errorMsg)
{
string tokenUrl = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={appsecret}";
string tokenStr = WebRequestHelper.DoGet(tokenUrl);
if (tokenStr.IndexOf("errcode") > -1)
{
var obj = new { errcode = 0, errmsg = "" };
var errorJson = JsonConvert.DeserializeAnonymousType(tokenStr, obj);
errorMsg = errorJson.errmsg;
token = null;
expiresIn = 0;
return false;
}
else
{
var obj = new { access_token = "", expires_in = 0 };
var tokenJson = JsonConvert.DeserializeAnonymousType(tokenStr, obj);
token = tokenJson.access_token;
expiresIn = tokenJson.expires_in;
errorMsg = null;
return true;
}
}
}
}