Home > Article > WeChat Applet > Timely obtain the current user Openid and precautions in the WeChat public account development webpage
Preface
This article mainly follows the previous article's web page authorization to obtain the user's basic information. It is also about how to obtain the current user again when the user clicks on the link in the official account after the first silent authorization. A general explanation of OpenId and some precautions.
Everyone who has read the previous article knows that we have already stored the user’s basic information in the database when the user pays attention, so if the user waits for a long time Click on the web link in the official account, so how do we obtain this unique identifier again?
Re-obtain openid
Specific implementation
First, we define a method to obtain openid ReGetOpenId
public static void ReGetOpenId() { string url = System.Web.HttpContext.Current.Request.Url.AbsoluteUri;//获取当前url if (System.Web.HttpContext.Current.Session["openid"] == "" || System.Web.HttpContext.Current.Session["openid"] == null) { //先要判断是否是获取code后跳转过来的 if (System.Web.HttpContext.Current.Request.QueryString["code"] == "" || System.Web.HttpContext.Current.Request.QueryString["code"] == null) { //Code为空时,先获取Code string GetCodeUrls = GetCodeUrl(url); System.Web.HttpContext.Current.Response.Redirect(GetCodeUrls);//先跳转到微信的服务器,取得code后会跳回来这页面的 } else { //Code非空,已经获取了code后跳回来啦,现在重新获取openid Log log = new Log(AppDomain.CurrentDomain.BaseDirectory + @"/log/Log.txt"); string openid = ""; openid = GetOauthAccessOpenId(System.Web.HttpContext.Current.Request.QueryString["Code"]);//重新取得用户的openid System.Web.HttpContext.Current.Session["openid"] = openid; } } }
Note : It is best to have a domain name in the url. The domain name of the peanut shell will not work. When adjusting the WeChat platform interface, an incorrect link error will be reported
The GetCodeUrl method above is as follows
#region 重新获取Code的跳转链接(没有用户授权的,只能获取基本信息) /// <summary>重新获取Code,以后面实现带着Code重新跳回目标页面(没有用户授权的,只能获取基本信息(openid))</summary> /// <param name="url">目标页面</param> /// <returns></returns> public static string GetCodeUrl(string url) { string CodeUrl = ""; //对url进行编码 url = System.Web.HttpUtility.UrlEncode(url); CodeUrl = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + Appid + "&redirect_uri=" + url + "?action=viewtest&response_type=code&scope=snsapi_base&state=1#wechat_redirect"); return CodeUrl; } #endregion
The GetOauthAccessOpenId method above is as follows
#region 以Code换取用户的openid、access_token /// <summary>根据Code获取用户的openid、access_token</summary> public static string GetOauthAccessOpenId(string code) { Log log = new Log(AppDomain.CurrentDomain.BaseDirectory + @"/log/Log.txt"); string Openid = ""; string url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Appid + "&secret=" + Secret + "&code=" + code + "&grant_type=authorization_code"; string gethtml = MyHttpHelper.HttpGet(url); log.log("拿到的url是:" + url); log.log("获取到的gethtml是" + gethtml); OAuth_Token ac = new OAuth_Token(); ac = JsonHelper.ToObject<OAuth_Token>(gethtml); log.log("能否从html里拿到openid=" + ac.openid); Openid = ac.openid; return Openid; } #endregion
You can get the user's Openid through the above method. As shown above, the user id is stored in System.Web.HttpContext.Current.Session["openid"], so get it It is also very simple
Execute where you need to obtain it
#region 获取当前用户Openid ReGetOpenId(); log.log("走完获取openid的方法之后,当前Session的值是:" + System.Web.HttpContext.Current.Session["openid"]); #endregion
Note: The OAuth_Token class mentioned above is as follows:
public class OAuth_Token { /// <summary> /// 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同 /// </summary> public string access_token { get; set; } /// <summary> /// access_token接口调用凭证超时时间,单位(秒) /// </summary> public string expires_in { get; set; } /// <summary> /// 用户刷新access_token /// </summary> public string refresh_token { get; set; } /// <summary> /// 用户唯一标识,请注意,在未关注公众号时,用户访问公众号的网页,也会产生一个用户和公众号唯一的OpenID /// </summary> public string openid { get; set; } /// <summary> /// 用户授权作用域 /// </summary> public string scope { get; set; } }
Log file
The simple log class used is also provided by the way:
/// <summary> /// 日志类 /// </summary> public class Log { private string logFile; private StreamWriter writer; private FileStream fileStream = null; public Log(string fileName) { logFile = fileName; CreateDirectory(logFile); } public void log(string info) { try { System.IO.FileInfo fileInfo = new System.IO.FileInfo(logFile); if (!fileInfo.Exists) { fileStream = fileInfo.Create(); writer = new StreamWriter(fileStream); } else { fileStream = fileInfo.Open(FileMode.Append, FileAccess.Write); writer = new StreamWriter(fileStream); } writer.WriteLine(DateTime.Now + ": " + info); } finally { if (writer != null) { writer.Close(); writer.Dispose(); fileStream.Close(); fileStream.Dispose(); } } } public void CreateDirectory(string infoPath) { DirectoryInfo directoryInfo = Directory.GetParent(infoPath); if (!directoryInfo.Exists) { directoryInfo.Create(); } } }
The call is very simple. The calling method is as follows:
Log log = new Log(AppDomain.CurrentDomain.BaseDirectory + @"/log/Log.txt"); log.log("我会被输入在日志文件中")
Finally, get the current user Openid, and then Other basic information about the user can be obtained from the database again. This can better assist you in completing other business modules in your project.