其他分享
首页 > 其他分享> > 微信公众号之获取token

微信公众号之获取token

作者:互联网

/// <summary>
/// 实时获取accessToken
/// </summary>
/// <returns></returns>
private static string RetrieveToken()
{
lock (_locker)
{
var resultToke = WebServiceApi.GetService(GetResultTokeUrl);
if (string.IsNullOrEmpty(resultToke))
{
throw new ArgumentNullException("发送微信消息获取_Access_token失败");
}
var result = Newtonsoft.Json.JsonConvert.DeserializeObject<Token>(resultToke);
if (result != null && !string.IsNullOrEmpty(result.access_token))
{
var _cacheManager = ServiceLocator.Instance.GetService<IStaticCacheManager>();
_cacheManager.SetRedisString("AdminWeixinToken", Newtonsoft.Json.JsonConvert.SerializeObject(result));
return result.access_token;
}
return null;
}
}

 

public class Token
{
//"{\"errcode\":40164,\"errmsg\":\"invalid ip 111.22.58.107 ipv6 ::ffff:111.22.58.107, not in whitelist hint: [YEIvkA09034078]\"}"
[DataMember]
public string access_token { get; set; }
[DataMember]
public int expires_in { get; set; }
}

 

/// <summary>
/// 获取微信Toke的URL
/// </summary>
protected static string GetResultTokeUrl
{
get
{
var apolloData = ApolloToConfigure.GetWChat();
return "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + apolloData.AppId + "&secret=" + apolloData.AppSecret;
}
}

 

/// <summary>
/// 根据URL远程获取服务数据(同步)
/// </summary>
/// <param name="_Url"></param>
/// <returns></returns>
public static string GetService(string _Url)
{
if (string.IsNullOrEmpty(_Url) || _Url.IndexOf("http") < 0)
{
return null;
}
HttpWebResponse response = null;
Stream ResStream = null;
StreamReader streamReader = null;
try
{
var request = (HttpWebRequest)WebRequest.Create(_Url);
response = (HttpWebResponse)request.GetResponse();

ResStream = response.GetResponseStream();
Encoding encoding = Encoding.GetEncoding("utf-8");
streamReader = new StreamReader(ResStream, encoding);

return streamReader.ReadToEnd();
}
catch (Exception e)
{
throw e;
}
finally
{
if (response != null)
{
response.Dispose();
response.Close();
}
if (ResStream != null)
{
ResStream.Dispose();
ResStream.Close();
}
if (streamReader != null)
{
streamReader.Dispose();
streamReader.Close();
}
}
}

标签:ResStream,string,微信,streamReader,获取,token,null,response
来源: https://www.cnblogs.com/wang150601/p/16291390.html