C# wx获取token的基本方法
程序员文章站
2023-12-10 23:40:46
本文实例为大家分享了c# wx获取token的具体代码,供大家参考,具体内容如下
#region 请求url,不发送数据
///
本文实例为大家分享了c# wx获取token的具体代码,供大家参考,具体内容如下
#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"); }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。