微信公眾號之獲取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();
}
}
}