The login and registration modes of Web site users include user name and password, verification code, and OAuth third-party authorization.

Commonly used third-party login QQ, wechat, Weibo, GitHub, Zhihu, etc. General users commonly use the login method of wechat scanning code authorization. Today, I would like to introduce the method of website access to wechat login.

Application to apply for

Access to wechat login in website application is a wechat OAuth2.0 authorized login system constructed based on OAuth2.0 protocol standard.

Before wechat OAuth2.0 authorized login access, you need to register a developer account on wechat open platform, have an approved website application, and obtain the corresponding AppID and AppSecret. After applying for wechat login and passing the approval, you can start the wechat login process.

The basic information of the website should be improved in the management center – Website Application – Website application creation. The content and operator information of the website should be improved in the second step and submitted to wechat open platform for review.

AppID and AppSecret will be generated for the website application after the website application is approved. AppID and AppSecret will be used in the following access process.

After detail letter

The website application document of wechat open platform explains in detail how to access wechat login for application. Here we introduce how to access wechat login in detail in the way of practical application. My station has access to wechat login, and if you want to see the effect, you can move here.

Access to wechat login needs to obtain the user’s OpenID and UnionID, which can be divided into three steps simply:

  1. Call the open interface to get authorization
  2. Obtain the access_token using the authorized code
  3. Obtain user information using access_token

To obtain authorization

The process of obtaining authorization is to let wechat users use mobile devices such as mobile phones to scan the OAuth standard QR code link provided by the website, and then the user authorizes the application in wechat to use the user’s personal information.

Below is the sequence diagram of access_token acquisition provided by wechat Open Platform:

A brief explanation of the steps in the figure follows:

  1. Request to log in to a third-party application

    That is, the user searches for a website keyword from the browser, or enters a website address into our website application.

  2. Request wechat OAuth2.0 to authorize login

    In this step, we only need to add the hyperlink of wechat authorized login to the login page of the website, and add the AppID of the website application in wechat open platform and the website address redirected after successful authorization in the address of the link.

    Form of link:

    https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state= STATE#wechat_redirectCopy the code

    Among them:

    • Appid: indicates the appID of the application

    • Redirect _URI: indicates the address where users are redirected to the website after authorization. You need to configure the Authorization Callback field in the wechat open platform website application.

      For example, the callback field in my website application is configured with the domain name of the website, so the callback page can be as long as it is under the domain name:

    • Response_type: address for requesting user authorization and fill in the code here.

    • Scope: application authorization scope. If multiple scopes exist, separate them with commas (,). Currently, only snSAPi_login is required for web applications.

    • State: This parameter is optional. It preserves the status of the request and callback and sends the request back to a third party. This parameter is used to prevent CSRF attacks (cross-site request forgery attacks). You are advised to set this parameter to a simple random number plus session for verification.

    The link in my website app is as follows:

    https://open.weixin.qq.com/connect/qrconnect?appid=wxb6a3d3490ab4c2cd&redirect_uri=https://zi.pongj.com/oauth/wechat/log in&response_type=code&scope=snsapi_login&state=STATE#wechat_redirectCopy the code

    Then add a hyperlink to the link address on the login page:

    <a href="https://open.weixin.qq.com/connect/qrconnect?appid=wxb6a3d3490ab4c2cd&redirect_uri=https://zi.pongj.com/oauth/wech At /login&response: code&scope=snsapi_login&state= state #wechat_redirect" > <img title="微信" Alt ="微信" src="//sf6-scmcdn2-tos.pstatp.com/xitu_juejin_web/img/wechat.e0ff124.svg" class="oauth-btn" /> </a>Copy the code

  3. Request user confirmation

    The hyperlink of wechat login is added to the login page. After clicking the button of wechat login, the user will enter the wechat domain. The basic information of the website application and the authorized TWO-DIMENSIONAL code will appear on the page to request the user to scan code authorization.

    As can be seen from the page, the address information in the address bar contains our configured address information, and the two-dimensional code in the page displays the name of our website application below the two-dimensional code.

    At this point, after the user scans the TWO-DIMENSIONAL code, the two-dimensional code will display the user’s authorization status synchronously:

    At the same time, we can also see the basic information of the application name and Logo in the wechat client:

  4. The user to confirm

    After the user “agrees” authorization in the mobile phone, the wechat login page in the website application will be redirected to the redirect_URL page configured in the link address

  5. Pull up a third-party application or redirect to a third party with an authorized temporary ticket (code)

    After the user agrees to authorize, the wechat login page will add a temporary code after the redirect_URI address when redirecting to the redirect_URI page. When developing the redirect_URI page, we can determine whether the address contains code to determine whether the user is authorized.

    For example, my website callback page would read:

    https://zi.pongj.com/oauth/login/wechat?code=code&state=state
    Copy the code
  6. Access_token is obtained by code plus AppID and AppSecret

    We check in the redirect_URI page that the address contains a code parameter and that the user is authorized. Then we can use code to obtain the access_token.

    It should be noted that AppSecret is a private data in the application, so the access_token need to be called in the server, do not call in the browser to cause the disclosure of AppSecret.

Obtaining User information

As a developer, I supplemented the data interaction process of the front and back end of the website application on the basis of the sequence diagram of wechat open platform:

After obtaining user authorization, that is, code, the next steps of the website application are shown in step 5-11 in the figure above. The previous steps have been introduced above. Next steps 5-11 are introduced in detail:

Step 5:

Add the path detection logic in the redirect_URI page of the website application to check whether there is a code parameter: If there is a code parameter, it indicates that the user has agreed to authorize; If no code parameter is set, the user rejects or closes the authorization page. In this case, you need to redirect the user to the login page and remind the user of the login failure.

Here is the verification block in my nuxt.js project:

const { code } = this.$route.query
if(! code) {this.$notify.warning('Please log in again')
  return this.$router.push('/login')}Copy the code

Step 6:

After obtaining the code parameter, we need to obtain the authorized Access_token. To obtain the Access_token, we need to use AppID and AppSecret. Because of the security of AppSecret, we send the request to the back end for operation.

Step 7:

Access_token is obtained by passing the code parameter to the back end and by AppSecret stored in an environment variable or configuration file.

The request address for access_token is in the following format:

https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
Copy the code

Among them:

  • Appid: The unique identifier of the application, which is obtained after the application is approved on wechat open platform
  • Secret: The application key AppSecret is obtained after the application is submitted and approved on wechat open platform
  • Code: Enter the obtained code parameter
  • Grant_type: fill authorization_code

Send GET requests to wechat development platform by using modules such as Request or got in Node.js.

Step 8:

After the request is successfully sent, wechat Open Platform will return the return value containing the access_token.

Return result:

{ 
  "access_token":"ACCESS_TOKEN"."expires_in":7200."refresh_token":"REFRESH_TOKEN"."openid":"OPENID"."scope":"SCOPE"."unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
}
Copy the code

The validity period of access_token is short (currently 2 hours). When the access_token times out, refresh_token can be used to refresh the interface. To refresh, you just need to add refresh_token and call the interface. For details, please refer to the official documentation

It can be seen that the returned result contains the user’s OpenID and UnionID. The users in these two fields are fixed for the website application. Therefore, we can judge whether the wechat user has been registered in our website through openID and UnionID. Directly generate legitimate token value and return to the front-end page; If the user has not registered in the website, we need to obtain the user’s personal information first and then regenerate the token

Step 9:

After obtaining the access_token and determining that the user is not registered in the website application, we need to obtain the user information to save the user’s authorized login information.

To obtain user information, call the following API interface:

https://api.weixin.qq.com/sns/userinfo?access_token=access_token&openid=openid
Copy the code

Among them:

  • Access_token: Enter the value we obtainedaccess_token
  • Openid: Personal information of the useropenidIs contained in the return result of the previous stepopenid

Step 10:

The wechat open platform will return the user’s basic personal information, including nickname, profile picture and gender, after the request is verified.

Return result:

{
  "openid":"OPENID"."nickname":"NICKNAME"."sex":1."province":"PROVINCE"."city":"CITY"."country":"COUNTRY"."headimgurl": "https://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eav HiaiceqxibJxCfHe/0"."privilege": ["PRIVILEGE1"."PRIVILEGE2"]."unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"

}
Copy the code

At this stage, we have obtained the user’s personal information, now we need to save the user’s information in our database, the next time the user scans the code wechat login, can directly return the user’s login token, without the need to obtain personal information from the wechat platform.

If the website application also needs the user to add other personal information, we can store the user’s wechat information in this step, and then redirect the request to the page of supplementary information, prompting the user to add additional information.

Since my website needs to use the user’s email address and mobile phone number information to notify, SO I added a page of supplementary information in the callback address, students who want to see the effect can have a try.

Step 11:

The user login authorization information is generated in the database. The system generates a valid token value and returns it to the front page. The front page indicates that the user has logged in successfully and goes to the home page of the website.

if (result.token) {
  await this.$store.dispatch('user/oauth', result.token)
  this.$notify.success('Successful landing')
  setTimeout(() = > {
    this.$router.push('/')},3000)
  return
}

this.$notify.success('Please log in again')
setTimeout(() = > {
  this.$router.push('/login')},3000)
Copy the code

reference

  • Official document address of wechat Open Platform website application

More content

Front-end development to the full stack, the current technical stack is Node.js, Python, daily research C and Rust, diligently eat system development and network design ~

More content please go to GitHub@ruxf, zhihu @ Meng Taibai, nuggets, or follow my public account @ full stack developer, welcome to hijack ~

Never too old to learn, never too old to write

Come on, workers