C # develop WeChat portals and applications (41) -- Scan code logon Based on the WeChat open platform,

Source: Internet
Author: User
Tags openid

C # development portal and application (41)-scan code logon based on open platforms,

In today's many websites, scanning and logon authentication on the open platform is used, which is equivalent to handing over identity authentication to more authoritative third parties for authentication, you do not need to store your password on the Application website. This article describes how to perform website login Based on the scan code of the open platform.

1. Open Platform Certification

To use scan code to log on to the website, you must first perform the developer qualification certification for the open platform account, submit the relevant information, and deliver the authentication fee of 300 RMB per year.

After Authentication, relevant website applications will be created, and relevant APPID and APPSecret will be available. These key parameters can be used to obtain relevant user information.

The application details page of the website application is as follows.

The entire open platform does not feel a lot of things, but it does not feel great to use these features only after fee-based authentication is required.

 

2. Scan code logon instructions and usage

Website application logon is an OAuth2.0 authorized logon System Based on OAuth2.0 protocol standards.

Before OAuth2. performs authorized OAuth2.0 login and access, register a developer account on the open platform, have a verified website application, and obtain the corresponding AppID and AppSecret, after applying for logon and passing the review, you can start the access process.

OAuth2.0 authorized logon allows users to log on to a third-party application or website using their identities. After authorized users log on to a third-party application already connected to OAuth2.0, the third party can obtain the user's interface call credential (access_token ), access_token can be used to call the open platform authorization Link Interface, so as to obtain basic user open information and help users implement basic open functions.

OAuth2.0 authorized logon currently supports the authorization_code mode, which is suitable for applications with server-side authorization. The overall process of this mode is:

1. after a third party initiates an authorized login request, the user is allowed to authorize a third-party application, the application will be pulled or redirected to a third-party website, with the authorization temporary ticket code parameter; 2. add AppID and AppSecret to the code parameter, and exchange access_token through the API; 3. use access_token to call the interface to obtain basic user data resources or help users perform basic operations.

Obtain the sequence chart of access_token:

 

We can get a rough idea of the whole process of scanning and logging in.

 

3. Scan the QR code to log on.

1) user identity binding

In order to achieve QR code scanning login, We need to bind the user in the existing system so that when the user scans the code, we can determine the user's identity so as to achieve the automatic login process.

We can perform unified settings in user management, or after logging on to a regular user (username + password). This mainly depends on whether we need to retain the username and password for login.

For example, you can bind a user in user management, that is, when creating a user, bind the user to a unique identifier.

You can also bind your username and password to the system after logging on to the system.

The above interface is to pop up a layer in a page, and then request the QR code to display it, as shown in the following interface code.

<Div id = "divWechat" class = "easyui-dialog" style = "width: pixel PX; height: 350px; padding: 10px 20px "closed =" true "resizable =" true "modal =" true "iconcls =" icon-setting "> <div> 

When opening the above layer, we use JS to dynamically obtain the QR code for display. The specific JS Code is as follows.

// BindWechat () {var url = "http://www.iqidi.com/H5/BindWechat? Id = @ Session ["UserID"] "; url = encodeURIComponent (url );$ ("# ImgQRcode"). attr ("src", "/H5/QR? Url = "+ url );// Open the binding window $ ("# divWechat"). dialog ('open'). dialog ('settitle', 'use the scan code for binding ');}

The above JS is only used for front-end data request and display. The specific QR Action is actually the process of generating a QR code scan. This QR code is actually a general method, to build an address pointing to the bound account, so that we can determine the bound account. The QR code generation process is as follows.

/// <Summary> /// convert the QR code to the image format. /// </summary> /// <param name = "url"> QR code connection </param>/ // <returns> </returns> [HttpGet] public ActionResult QR (string url) {// initialize the QR code generation tool QRCodeEncoder qrCodeEncoder = new QRCodeEncoder (); qrCodeEncoder. QRCodeEncodeMode = QRCodeEncoder. ENCODE_MODE.BYTE; qrCodeEncoder. QRCodeErrorCorrect = QRCodeEncoder. ERROR_CORRECTION.M; qrCodeEncoder. QRCodeVersion = 0; qrCodeEncoder. QRCodeScale = 4; // generate the QR code image var image = qrCodeEncoder. encode (url, Encoding. default); // Save As PNG to memory stream MemoryStream MS = new MemoryStream (); image. save (MS, ImageFormat. png); image. dispose (); return File (ms. toArray (), "image/Png ");}

To bind a user, we need to obtain the identity information of the current user. Therefore, we need to perform a redirection in the BindWeChat operation, as shown in the following interface.

/// <Summary> /// generate the bound address /// </summary> /// <returns> </returns> public ActionResult BindWechat ()

In this function processing, we need to re-targeting the processing, we direct it to the BindAccount function, to facilitate the acquisition of the user's openid and other necessary information.

In addition, we established a connection with account information based on the application of the open platform. Therefore, the information for creating a database is as follows.

That is, a specific open platform application corresponds to a specific account, so that we can make full use of the configuration for processing.

The logic of BindAccount processing mentioned above is to obtain necessary information and then verify the identity information at the database layer. The specific code is as follows.

/// <Summary> /// bind the user id /// </summary> /// <param name = "ID"> account id </param> /// <returns> </returns> public ActionResult BindAccount () {WebAppInfo appInfo = GetWebApp (ConfigData. webAppId); AccountInfo accountInfo = GetAccount (appInfo. accountNo); var htResult = GetOpenIdAndUnionId (accountInfo. uniteAppId, accountInfo. uniteAppSecret); // store openid to facilitate the use of string openid = htResult ["openid"]. toString (); var union Id = htResult ["unionid"]. ToString (); var userid = Request. QueryString ["id"]; var state = Request. QueryString ["state"]; if (! String. IsNullOrEmpty (openid )&&! String. isNullOrEmpty (userid) {CommonResult result = BLLFactory <User>. instance. bindUser (openid, unionid, userid. toInt32 (); if (result. success) {return BindSuccess () ;}else {return BindFail () ;}} else {throw new WeixinException ("unable to get openid" + string. format (", openid: {0}, userid: {1}", openid, userid ));}}

During the binding process, we need to consider binding the correct account, rebinding other accounts, and binding invalid accounts. If the correct account is successfully bound (the same result can be processed multiple times ), the page is as follows (the style of this interface adopts the weui style ).

 

2) User Login handling by scanning code

After the account is bound to the above, you can scan the code to log on. We have our own judgment and processing during the scan code callback, the scan code interface is shown as follows (in addition to retaining the username and password for login, we added a scan code for login ).

For the Bootstrap interface effect

For EasyUI

This is similar to the preceding two-dimensional code Display rules, but their connection addresses are different. The Open Platform interface is used here, that is, the open platform authentication interface we mentioned earlier.

The above code is as follows.

<! -- QR code scan logon interface layer --> <div id = "divWechat" class = "easyui-dialog" style = "width: 550px; height: 500px; padding: 10px 20px "closed =" true "resizable =" true "modal =" true "iconcls =" icon-setting "> <div id =" login_container "align =" center "> </div> <div align = "right"> <a href = "javascript: void (0) "class =" easyui-linkbutton "iconcls =" icon-cancel "onclick =" javascript: $ ('# divWechat '). dialog ('close') "> close </a> </div>

The above code needs to introduce the JS file and display it using the jssdk api.

<! -- Use scan code to log on --> <script src = "http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"> </script> <script language = "javascript"> function OpenJSLogin () {var obj = new WxLogin ({id: "login_container", appid: "@ ViewBag. appid ", scope:" snsapi_login ", redirect_uri:" @ ViewBag. redirect_uri ", state:" @ ViewBag. state ", style:" black ", href :". impowerBox. qrcode {width: 200px;} "}); // open the binding window $ (" # divWechat "). dialog ('open '). dialog ('settitle', 'use scan code for login ');} </script>

For example, APPID is the open platform parameter after the source is authenticated.

This information is obtained after the MVC controller and bound to the ViewBag to facilitate the use of the front-end interface.

// Use JSLogin to log on to WebAppInfo appInfo = BLLFactory <WebApp>. Instance. FindByID (ConfigData. WebAppId); ArgumentValidation. CheckForNullReference (appInfo, "Web application appInfo"); if (appInfo! = Null) {ViewBag. appid = appInfo. OpenAppID; ViewBag. redirect_uri = appInfo. LoginCallBackUrl; ViewBag. state = ConfigData. AuthState ;}

The redirect_uri is the LoginCallBackUrl address obtained through the database, which is similar to the following format: http://www.iqidi.com/H5/callback? Uid = iqidiSoftware

That is, the callback processing we perform after processing the returned results on the open platform.

Through the APPID and APPSecret of the open platform, we can obtain the corresponding interface call credential, and then obtain the unified UnionID of the user's public platform based on the Interface credential and openid, this is the unique identifier of our users. The Code is as follows.

                var result = baseApi.GetAuthToken(appid, appsecret, code);                if (result != null && !string.IsNullOrEmpty(result.openid))                {                    openid = result.openid;                    var unionResult = baseApi.GetSnsapiUserInfo(result.access_token, result.openid);                    ht.Add("openid", openid);                    ht.Add("unionid", unionResult != null ? unionResult.unionid : "");                }

With unionid, we can find the corresponding user in our user database based on this ID, as shown in the following code.

// OpenID of the open platform. It is not the OpenID of the public account and must be converted to unionid if (! String. IsNullOrEmpty (openid )&&! String. IsNullOrEmpty (unionid) {UserInfo userInfo = BLLFactory <User>. Instance. FindByUnionId (unionid );

Then determine whether the user information we are going to is correct, as shown in the following code:

If (userInfo! = Null) {CommonResult loginResult = CheckLogin (userInfo. Name); if (! LoginResult. success) {LogHelper. info (string. format ("User Login Failed, {0}", loginResult. errorMessage);} // The redirected url after successful login var url = appInfo. homeUrl; // example: http://www.iqidi.com/Home return Redirect (url );}

If it fails, we can direct it to the specified interface.

// If it fails, the system prompts ViewBag. Error = "failed to obtain information, logon Error"; return View ("LoginError ");

If you need to set some Session information or Cookie information after logging in successfully, you can use the CheckLogin function for processing.

The above is the process of implementing scan code login with the open platform. The whole process is to use the following processes.

1) Use the JSSDK script to scan the code to obtain the code.

Main Purpose of JS Logon: the website allows users to log on to the website without having to jump to the domain to log on and return. This improves the smoothness and success rate of logon. How to log on to JS with a QR code embedded in the website:

Step 1: first introduce the following JS files (supporting https) on the page ):

<script src="http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>

Step 2: Use the following JS objects for Logon:

                          var obj = new WxLogin({                              id:"login_container",                               appid: "",                               scope: "",                               redirect_uri: "",                              state: "",                              style: "",                              href: ""                            });
2) Step 2: Get access_token through code

Get access_token through code

Https://api.weixin.qq.com/sns/oauth2/access_token? Appid = APPID & secret = SECRET & code = CODE & grant_type = authorization_code

3) Step 3: Call the interface through access_token

Call the interface after obtaining the access_token,

For the interface scope, the interfaces that can be called include the following:

Scope) Interface Interface Description
Snsapi_base /Sns/oau2/ access_token Use code in exchange for access_token, refresh_token, and authorized scope
/Sns/oau2/ refresh_token Refresh or renew access_token
/Sns/auth Check access_token Validity
Snsapi_userinfo /Sns/userinfo Obtain user personal information

Snsapi_base is a basic interface. If the application already has other scope permissions, it has snsapi_base permissions by default. Using snsapi_base allows mobile webpage authorization to bypass redirect authorization logon page request user authorization action, directly jump to a third-party webpage with authorization temporary ticket (code ), however, the scope authorized by the user is only snsapi_base. As a result, the data and basic functions that must be authorized by the user cannot be obtained.

4) Obtain information before logon in the callback Interface

Through the above interface, we can obtain the corresponding user identity information, so we can combine our user database for user identity identification and processing, and set the necessary Session or Cookie information, etc, finally, go to the main application interface.

 

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.