Scan the QR code on PC to register and log in
1. Preface
Let me first state that the focus of this article is on implementation ideas, and the code and database design are mainly for showing ideas. If you have strict requirements on code efficiency, do not copy them.
I believe that people who have done WeChat development have done many authorizations, but generally speaking, we are more authorizing mobile websites, or rather, it is an authorization under the WeChat terminal. One problem I encountered today is that the project supports WeChat and PC terminals and opens registration. It is required to log in on the other end whether you register on the PC or on the WeChat side. In other words, whether it is PC or WeChat, you must do "you are you" (related in some way).
2. Find a solution
Thinking in the traditional way, the WeChat side can be registered through authorization, but on the PC side, the traditional way is nothing more than filling in the mobile phone number, or email, etc. If you register in this way, the following problem will arise
1. I first authorize the registration on the WeChat side, so if I want to log in to the PC side, I still have to register.
This solution can be: after WeChat authorization registration, it is "forced" to require users to fill in basic information, such as mobile phone number and email. In this way, we can generate the account password for the user to log in to the PC in some way. For example, use the user's nickname as the account, the mobile phone number as the password, etc.
Disadvantages: The user experience is not good, and there are also safety risks. After all, your WeChat nickname, email or mobile phone number are exposed.
2. If I register on the PC first, how do I connect to the mobile terminal when I authorize on WeChat? Of course, there will always be solutions to any problem. The idea is as follows:
Solution 1: After the user registers on the PC, the "force" user must fill in the WeChat nickname. This is used as the relevant condition for WeChat authorization. But unfortunately, the WeChat nickname can be changed, but it is not the only one, how can it be used to make associations? The plan was killed in a desperate situation.
Plan 2: After authorization on the WeChat side and registration on the PC side, users are required to fill in their mobile phone numbers as the link. This leads to a problem, and it is necessary to ensure the authenticity of the user's mobile phone, and there is no problem. This can be achieved through the mobile phone verification code (the same is true for Email). But you might as well assume that the following situation is present. If I have two mobile phone numbers, fill in one when registering on the PC and another when registering on WeChat. Is it related? The answer is a pity. Furthermore, after I registered on the PC, I just didn't fill in it (the reason why I forced the double quotes), and then I used the WeChat authorization to log in. Well, there will be two pieces of data waiting for you to find a way to associate, and a typical developer will dig a hole. This method works to some extent, but it is unacceptable to developers to be rigorous.
3. Solution to return to the origin
Analysis: Since there are all problems with the above solutions, let’s put them aside first. Put some thoughts back to the root of the problem. The associated problem requires a unique identifier. The unique identification is just like our ID number. When we apply for a credit card, the ID card is necessary. If you purchase a number card under the real name system, the ID card is necessary. Assuming we are the system administrators, then I can find out your mobile phone number and bank card number through your ID number.
With the above idea, all we need to do is find a unique identifier to be associated. There is an important role on WeChat. It has this common function with the ID number we mentioned above, the unique identification of a certain official account by the WeChat account.
Authorization from WeChat is available to openid. Anyone who has done WeChat development should have no problem. The question is how to achieve the PC terminal to get openid when registering or logging in. The author’s implementation idea is as follows. Register on the PC, or display a QR code when logging in, guide the user to scan the code using WeChat, so that it jumps to the authorization page. This step has the most critical detail. Please bring a unique authorization code (authCode) to the QR code. Just imagine if the user authorizes us to write openid and authCode to the database. Then we can obtain the openid associated with authCode through an API on the PC side. If we do this, we can know who is currently scanning the code to register or log in on the PC (register if not registered, and whoever has registered will log in directly). Do you suddenly feel so easy? If you think the text is more abstract, please see the following picture
PC WeChat scan code login process
Core code
After clarifying the ideas and processes, we will directly upload the code. The development ideas are common, so please show your magical powers when developing the language.
Note: The following code takes C# language as an example and uses MVC + EF (Note: uuid is equivalent to our authCode above)
Scan the code to log in to the background page
public ActionResult Login(){ //If you are logged in, jump directly to the homepage if (User.Identity.IsAuthenticated) return RedirectToAction("Index", "Home"); string url = Request.Url.Host; string uuid = Guid.NewGuid().ToString(); ViewBag.url = "http://" + url + "/home/loginfor?uuid=" + uuid;//Construct authorization link ViewBag.uuid = uuid;//Save uuid return View();}
The QR code is generated using the plug-in jquery.qrcode.js. If you want to know more, please move to Github. One thing to note here is that this plugin can specify the generation method of QR code, canvas or table. Please specify the use of table generation for friends who support IE.
The code is as follows:
jQuery('#qrcode').qrcode({ render : "table", text : "http://baidu.com"});Go back to the topic, the main code of the login page is as follows
<!--Container for generating QR code div--><div id="qrcode-container"></div><script src="~/Plugins/Jquery/jquery-1.9.1.min.js"></script><script src="~/Plugins/jquery-qrcode/jquery.qrcode.min.js"></script><script> jQuery(function () { //Generate QR code jQuery('#qrcode-container').qrcode("@ViewBag.url"); //Poling to determine whether the user authorizes var interval = setInterval(function () { $.post("@Url.Action("UserLogin","Home")", { "uuid": "@ViewBag.uuid" }, function (data, status) { if ("success" == status) { //User Success Authorization => Jump if ("success" == data) { window.location.href = '@Url.Action("Index", "Home")'; clearInterval(interval); } } }); }, 200); })</script>
Poll to determine whether the user authorizes the API code
public string UserLogin(string uuid){ //Verify whether the parameter is legal if (string.IsNullOrEmpty(uuid)) return "param_error"; WX_UserRecord user = db.WX_UserRecord.Where(u => u.uuId == uuid).FirstOrDefault(); if (user == null) return "not_authcode"; //Write cookie FormsAuthentication.SetAuthCookie(user.OpenId, false); //Clear uuid user.uuId = null; db.SaveChanges(); return "success";}WeChat authorization action
public ActionResult Loginfor(string uuid){ #region Get basic information - snsapi_userinfo /* * Create WeChat general class - The code here is more complicated and not posted here * I will sort out the entire demo on Github */ WechatUserContext wxcontext = new WeChatUserContext(System.Web.HttpContext.Current, uuid); //Use WeChat general class to get basic user information wxcontext.GetUserInfo(); if (!string.IsNullOrEmpty(wxcontext.openid)) { uuid = Request["state"]; //Judge whether the database exists WX_UserRecord user = db.WX_UserRecord.Where(u => u.OpenId == wxcontext.openid).FirstOrDefault(); if (null == user) { user = new WX_UserRecord(); user.OpenId = wxcontext.openid; user.City = wxcontext.city; user.Country = wxcontext.country; user.CreateTime = DateTime.Now; user.HeadImgUrl = wxcontext.headimgurl; user.Nickname = wxcontext.nickname; user.Province = wxcontext.province; user.Sex = wxcontext.sex; user.Unionid = wxcontext.unionid; user.uuId = uuid; db.WX_UserRecord.Add(user); } user.uuId = uuid; db.SaveChanges(); } #endregion return View();}
Finally, the database table design is attached
There is nothing special, we add one more custom uuId for each parameter returned by WeChat.
For details of WeChat parameter description, please refer to the WeChat developer documentation
Running effect
1. Scan the QR code to log in to the page
2. Request user authorization
3. User confirms authorization
4. PC login is completed
There are inevitably shortcomings in the article, please forgive me. If you find any errors, please leave a message to point them out. I am very grateful! Scan the QR code on WeChat to register and log in to Demo. After the author sorts out, put it on Github. I hope to help more friends. Please pay attention to the update of this article.
The above are examples of scanning the QR code on WeChat on PC. Friends in need can refer to it. Thank you for your support for this site!