. NET WeChat development-PC-side WeChat scan code registration and login function implementation,. netpc

Source: Internet
Author: User
Tags openid

. NET development-scan code registration and logon on the PC side,. netpc

I. Preface

The focus of this article is the implementation idea. The code and database design mainly aims to demonstrate the idea. If there are strict code efficiency requirements, do not copy them.

I believe that developers have never done this much, but we generally do more authorization for mobile websites. Specifically, it is an authorization for terminals. One problem encountered today is that the project support end and PC end are available for registration. It is required that you can log on to another terminal either after registration on the PC or after registration on the client. That is to say, no matter the PC or you have to "You Are you" (in some way ).

2. Find a solution

In the traditional way, users can register through authorization. However, on the PC side, the traditional method is to fill in the mobile phone number or Email. If you use this method for registration, the following problems will occur:

1. I first authorize registration on the client. If I want to log on to the PC, I still have to register.

This solution can be: "forced" after authorization Registration requires the user to fill in basic information, such as mobile phone number, Email. In this way, we can generate a PC-based Logon account and password for the user, for example, using the user's nick name as the account, the mobile phone number as the password, and so on.

Disadvantages: poor user experience and security risks. After all, your nickname, Email or mobile phone number are exposed.

2. If I register on the PC, how can I associate the mobile terminal with the mobile terminal during authorization?

Of course, there will always be solutions to all problems. The idea is as follows:

Solution 1: After a user registers on the PC, the "force" user must enter a nickname. This serves as an association condition for authorization. Unfortunately, the nickname can be changed. How can it be used for association instead of the only one? Solution 1 was killed.

Solution 2: after authorization on the terminal and after registration on the PC end, users are required to enter the mobile phone number for this association. In this way, a problem arises, and it is necessary to ensure that the user's mobile phone's real information is correct. This can be achieved through the mobile phone Verification Code (the same is true for Email ). However, assume that the following situations exist: If I have two mobile phone numbers, enter one for PC registration and the other for registration. Is it associated? The answer is sorry. In addition, after I register on the PC end, I just leave it blank (the reason why I forcibly add double quotation marks), and then I use terminal authorization to log on. Well, there will be two pieces of data waiting for you to find a way to associate, typical developer self-mining. This method works to some extent, but it is not acceptable to developers to be rigorous.

Iii. Solution to regression Origin

Analysis: Since there are problems with the above solutions, we should first put them aside. Sort out our ideas and let us go back to the root of the problem. Association issues require a unique identifier. The unique ID is like our ID card number. When we handle a credit card, the ID card is required. If you purchase a number card under the real name system, the ID card is required. If we are the system administrator, I can use your ID card number to find your mobile phone number and bank card number.

With the above idea, we need to find a unique identifier to associate. There is an important role openid. It works with the ID card number we mentioned above, and the account is the unique identifier of a public number.

Users who have obtained openid for development should have no problem. The problem is how to obtain the openid when registering or logging on to the PC. The author's Implementation ideas are as follows. Register on the PC, or display a QR code to guide the user to scan the code to redirect to the authorization page. This step has the most critical details. Please add a unique authorization code (authCode) to the QR code ). Think about writing openid and authCode to the database after user authorization. Then we can get the openid associated with authCode through an API on the PC end. If we do this, we can know who is performing scan code registration or logon on the PC end. (If you have not registered, you can directly log on to the PC ). Is it so easy? If you think the text is abstract, see the figure below

PC-side QR code Logon Process

Core code

After figuring out the ideas and procedures, let's go directly to the code. The development ideas are common, and the development languages should be different.

Note: The following Code uses the C # language as an example and uses MVC + EF (Note: uuid is equivalent to the above authCode)

Background code on the logon page

Public ActionResult Login () {// if you have logged on, go 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 uuidreturn View ();}

The jquery. qrcode. js plug-in is used to generate the QR code. For more information, see Github. Note that this plug-in can be used to generate two-dimensional codes. For canvas or table, you must specify table generation by using IE.

The Code is as follows:

jQuery('#qrcode').qrcode({render : "table",text : "http://baidu.com"});

Return to the question. The main code on the logon page is as follows:

<! -- Generate the container div of the QR code --> <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 the QR code jQuery ('# qrcode-iner '). qrcode ("@ ViewBag. url "); // poll 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 authorized successfully => jump to if (" success "= data) {window. location. href = '@ Url. action ("Index", "Home") '; clearInterval (interval) ;}}) ;}, 200) ;}</script>

Poll to determine whether a user authorizes API code

Public string UserLogin (string uuid) {// verify whether the parameter is valid 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 cookieFormsAuthentication. setAuthCookie (user. openId, false); // clear uuiduser. uuId = null; db. saveChanges (); return "success ";}

Terminal Authorization Action

Public ActionResult Loginfor (string uuid) {# region get basic information-snsapi_userinfo/** create a common class-here the code is complicated. I will sort the entire Demo a little later and put it on Github */WechatUserContext wxcontext = new WechatUserContext (System. web. httpContext. current, uuid); // use a common class to obtain basic user information wxcontext. getUserInfo (); if (! String. isNullOrEmpty (wxcontext. openid) {uuid = Request ["state"]; // determines whether the database has 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 () ;}# endregionreturn View ();}

Attached Database Table Design

Nothing special is that each of the returned parameters is added with a custom uuId.

For parameter descriptions, see the developer documentation.

Running Effect

1. Scan the logon page

2. Request user authorization

3. user authorization confirmation

4. PC-side logon completed

The above is a small series for you to introduce. NET development PC terminal scan code registration and login function implementation, hope to help everyone, if you have any questions, please leave a message, xiaobian will reply to you in a timely manner. Thank you very much for your support for the help House website!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.