ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

微信公众号之获取token

2022-05-20 10:33:36  阅读:29  来源: 互联网

标签:ResStream string 微信 streamReader 获取 token null response


/// <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

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有