using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Linq; public class WeChatUtil { /// <summary> /// 获取TOKEN /// </summary> /// <param name="strCorpid">企业号标识</param> /// <param name="strSecret">微信获取token地址</param> /// <param name="strSecret">具体应用Secret</param> /// <param name="strWeChatServiceUrl">微信接口处理地址</param> /// <returns></returns> public string GetAccessToken(string strCorpid, string strSecret, string accesstokenurl, string strWeChatServiceUrl) { string strAccessToken = string.Empty; string strGetTokenUrl = strWeChatServiceUrl + "?action=gettoken"; Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("corpid", strCorpid); dic.Add("corpsecret", strSecret); HttpRequestUtil httpUtil = new HttpRequestUtil(); strAccessToken = httpUtil.SendHttpGetRequest(strGetTokenUrl, dic); if (!string.IsNullOrEmpty(strAccessToken)) { return strAccessToken; } //重新获取AccessToken HttpRequestUtil util = new HttpRequestUtil(); string strResult = util.SendHttpGetRequest(accesstokenurl, dic); //解析出token //{"access_token":"DGubVxT5W-SaeYgGjJA6anTzkl6XnlP-WlsWpoKcUNGkha5ZI6ePHRefmTlG7-IB","expires_in":7200} JObject jobject = JsonConvert.DeserializeObject<JObject>(strResult); strAccessToken = jobject["access_token"].ToString(); string strExpire = jobject["expires_in"].ToString(); //更新数据库 string strUpdateTokenUrl = strWeChatServiceUrl; Dictionary<string, string> dicUpdateToken = new Dictionary<string, string>(); dic.Add("action", "updatetoken"); dic.Add("token", strAccessToken);//传递四个参数过去 dic.Add("expires_in", strExpire); strResult = httpUtil.SendHttpGetRequest(strUpdateTokenUrl, dic); return strAccessToken; } }