验证中...
码云 Gitee IDE 全新上线——支持 Git 管理的轻量在线编码环境
公共方法获取Access_token
原始数据 复制代码
//公共方法获取Access_token,定时更新
//我得ORM是用的Subsonic 比较快速
//用的时候new Select().From<TUserMpWechat>().ExecuteTypedList<TUserMpWechat>(); 替换成自己得就可以
//最后在公共方法里在存回到数据库就好了
//TUserMpWechat 数据库表,我是将微信公众号得信息放在数据库里,定时拿出来便利,每一个都更新
//表结构
public class TUserMpWechat
{
public static string Id { get; set; }
public static string OriginalId { get; set; }
public static string AppID { get; set; }
public static string AppSecret { get; set; }
public static string Token { get; set; }
public static string EncodingAESKey { get; set; }
public static string WechartId { get; set; }
public static string WechartName { get; set; }
public static string CreateDate { get; set; }
public static string CreateAdminId { get; set; }
public static string AccessToken { get; set; }
public static string AccessTokenEndTime = { get; set; }
public static string ExtStr { get; set; }
}
//公共方法获取Access_token 得公共方法
public string GetAccessToken(string id)
{
var resultJson = new WebResult();
var result = string.Empty;
try
{
var mpWechat = new Select().From<TUserMpWechat>().Where(TUserMpWechat.IdColumn).IsEqualTo(id).ExecuteTypedList<TUserMpWechat>().FirstOrDefault();
if (mpWechat.AccessTokenEndTime != null)
{
var ts = DateTime.Parse(mpWechat.AccessTokenEndTime.ToString()) - DateTime.Now;
if (ts.TotalMinutes > 80)
{
resultJson.State = ResultState.Success;
resultJson.Result = "上次获取的有效时间大于80分钟,不用重新获取";
resultJson.Object = mpWechat;
goto buyonghuoqu;
}
}
string wApiUrl = ConfigurationSettings.AppSettings["wApi"];
new PushWebHelper().PostToGet($@"https://{wApiUrl}/cgi-bin/token?grant_type=client_credential&appid={mpWechat.AppID}&secret={mpWechat.AppSecret}", ref result, Encoding.UTF8);
if (result.IndexOf("errcode") != -1)
{
throw new Exception("请求异常,详情请查看微信服务器返回的错误代码,参照微信官网排查问题");
}
var accessToken = (TencentAccessTokenModel)JsonConvert.DeserializeObject(result, typeof(TencentAccessTokenModel));
mpWechat.AccessToken = accessToken.access_token;
mpWechat.AccessTokenEndTime = DateTime.Now.AddSeconds(accessToken.expires_in);
mpWechat.Save();
resultJson.State = ResultState.Success;
resultJson.Result = "重新获取成功";
resultJson.Object = mpWechat;
}
catch (Exception e)
{
resultJson.State = ResultState.Error;
resultJson.Result = "重新获取失败";
resultJson.Object = result;
}
buyonghuoqu:
return JsonConvert.SerializeObject(resultJson);
}
//启动器 需要放到 Global.asax 程序启动时激活
public void TimerGet()
{
System.Timers.Timer timer = null;
int Interval = 1000 * 60 * 30;
timer = new System.Timers.Timer(Interval);
timer.Elapsed += GetAccessTokenAll;
timer.Interval = Interval;
timer.Enabled = true;
timer.Start();
}
private void GetAccessTokenAll(object sender, ElapsedEventArgs e)
{
var mpList = new Select().From<TUserMpWechat>().ExecuteTypedList<TUserMpWechat>();
foreach (var mpWechat in mpList)
{
GetAccessToken(mpWechat.Id.ToString());
}
}

评论列表( 0 )

你可以在登录后,发表评论

搜索帮助