C# wx获取token的基本方法

时间:2022-02-18 04:28:29

本文实例为大家分享了C# wx获取token的具体代码,供大家参考,具体内容如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#region 请求Url,不发送数据
 
/// <summary>
/// 请求Url,不发送数据
/// </summary>
public static string RequestUrl(string url)
{
return RequestUrl(url, "POST");
}
 
#endregion
 
#region 请求Url,不发送数据
 
/// <summary>
/// 请求Url,不发送数据
/// </summary>
public static string RequestUrl(string url, string method)
{
// 设置参数
var request = WebRequest.Create(url) as HttpWebRequest;
var cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Method = method;
request.ContentType = "text/html";
request.Headers.Add("charset", "utf-8");
//发送请求并获取相应回应数据
var response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
Stream responseStream = response.GetResponseStream();
var sr = new StreamReader(responseStream, Encoding.UTF8);
//返回结果网页(html)代码
string content = sr.ReadToEnd();
 
return content;
}
 
#endregion
 
 
 
#region 获取Json字符串某节点的值
 
/// <summary>
/// 获取Json字符串某节点的值
/// </summary>
public static string GetJsonValue(string jsonStr, string key)
{
string result = string.Empty;
if (!string.IsNullOrEmpty(jsonStr))
{
key = "\"" + key.Trim('"') + "\"";
int index = jsonStr.IndexOf(key) + key.Length + 1;
if (index > key.Length + 1)
{
//先截逗号,若是最后一个,截"}"号,取最小值
int end = jsonStr.IndexOf(',', index);
if (end == -1)
{
end = jsonStr.IndexOf('}', index);
}
result = jsonStr.Substring(index, end - index);
result = result.Trim(new [] {'"', ' ', '\"'}); //过滤引号或空格
}
}
return result;
}
 
#endregion
 
#region 验证Token是否过期
 
/// <summary>
/// 验证Token是否过期
/// </summary>
public static bool TokenExpired(string access_token)
{
string jsonStr =
RequestUrl(string.Format("https://api.weixin.qq.com/cgi-bin/menu/get?access_token={0}",
access_token));
if (GetJsonValue(jsonStr, "errcode") == "42001")
{
return true;
}
return false;
}
 
#endregion
 
#region 获取Token
 
/// <summary>
/// 获取Token
/// </summary>
public static string GetToken(string appid, string secret)
{
string strJson =
RequestUrl(
string.Format(
"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}",
appid, secret));
return GetJsonValue(strJson, "access_token");
}
 
#endregion
 
//获取Openid
 
public static string GetOpenId(string appid, string secret, string code)
{
string strJson =
RequestUrl(
string.Format(
"https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code",
appid, secret, code));
//LogUtil.WriteLog(strJson);
return GetJsonValue(strJson, "openid");
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。