English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Recently developed WeChat Public Platform, make some notes, have also developed before, this time development again forgot, took half a day, it is better to make a note.
Note: The framework is for developing WeChat Public Platform. The scenario is, in the template page, get the user openid, and want to verify the page, integrate the template page is enough.
Add the following code to _Layout.cshtml
<head> <meta charset="utf-8">-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - My ASP.NET Application</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") @{ var code = HttpContext.Current.Request["code"]; Log.logmsg(code); string urlpath = HttpContext.Current.Request.Url.AbsoluteUri.ToString(); ViewBag.at = AdminUtil.GetOpenID(urlpath, code); } </head>
Add GetOpenID method to the AdminUtil class
#region Retrieve OpenID /// summary> /// Retrieve OpenID /// </summary> public static string GetOpenID(string redirect_url, string code) { string AppID = WXModel.AppID; string AppSecret = WXModel.AppSecret; string openid = ""; openid = WXApi.GetOpenID(AppID, redirect_url, code, AppSecret); return openid; } #endregion
Add GetOpenID method in WXApi class
#region Get OpenId /// summary> /// Get OpenId /// </summary> public static string GetOpenID(string appid, string redirect_url, string code, string screct) { string strJson = ""; if (string.IsNullOrEmpty(code)) { redirect_url = HttpUtility.UrlEncode(redirect_url); HttpContext.Current.Response.Redirect(string.Format("https://open.weixin.qq.com/connect/oauth2/authorize#63;appid={0}&redirect_uri={1&response_type=code&scope=snsapi_base&state={2})#wechat_redirect", appid, redirect_url, new Random().Next(1000, 200000).ToString())); } else { strJson = HttpRequestUtil.RequestUrl(string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1&code={2&grant_type=authorization_code", appid, screct, code)); } return Tools.GetJsonValue(strJson, "openid"); } #endregion
public static class WXModel { public static string access_token; public static string AppID; public static string AppSecret; }
/// summary> /// Utility class /// </summary> public class Tools { #region Get the value of a node in the Json string /// summary> /// Get the value of a node in the Json string /// </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) { //First cut the comma, if it is the last one, cut the "}" mark, take the minimum value int end = jsonStr.IndexOf(',', index); if (end == -1) { end = jsonStr.IndexOf('}', index); } result = jsonStr.Substring(index, end - index); result = result.Trim(new char[] { '"', ' ', '\'' }); //Filter quotes or spaces } } return result; } #endregion }
public class HttpRequestUtil { #region Request URL without sending data /// summary> /// Request URL without sending data /// </summary> public static string RequestUrl(string url) { return RequestUrl(url, "POST"); } #endregion #region Request URL without sending data /// summary> /// Request URL without sending data /// </summary> public static string RequestUrl(string url, string method) { // Set parameters HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = method; request.ContentType = "text/html"; request.Headers.Add("charset", "utf-8"); //Send request and get the corresponding response data HttpWebResponse response = request.GetResponse() as HttpWebResponse; //The program only starts to send a POST request to the target web page after request.GetResponse() Stream responseStream = response.GetResponseStream(); StreamReader sr = new StreamReader(responseStream, Encoding.Default); //Return result web page (html) code string content = sr.ReadToEnd(); return content; } #endregion }
Attention: You need to set the authorization callback domain in the official WeChat public platform
That's all for this article, I hope it will be helpful to everyone's study, and I also hope everyone will support Yell Tutorial more.
Declaration: The content of this article is from the Internet, the copyright belongs to the original author, the content is contributed and uploaded by Internet users spontaneously, this website does not own the copyright, does not undergo manual editing, and does not bear relevant legal liabilities. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)