preface

When users visit third-party web pages in the wechat client, the public account can obtain the basic information of users through the wechat web page authorization mechanism, so as to realize the business logic. Next, learn how to achieve wechat webpage silent authorization.

Configure wechat before development

In order to help developers quickly understand and get familiar with the development of wechat public account and the invocation of various interfaces, we have launched the wechat public account test number, which can be obtained by scanning the TWO-DIMENSIONAL code on wechat mobile phone. Enter the wechat public account test number application system

Development of wechat webpage authorization function must have a service number (for enterprises), individuals can only apply for a subscription number. But we can complete the function development by applying for the interface test number.

The specific approach is:

  1. Enter your server address in the interface configuration information, Token(custom optional write)
  2. The wechat service will send a request to your server with a list of parameters and ask you to return the corresponding parameters
Token router.get()'/token',async ctx=>{
  const token = 'customToken'Const {signature, timestamp, nonce, echostr} = ctx.querylet str = [token, timestamp, nonce].sort().join("");
  letSha = sha1(STR) // echostr is returned to verify wechat encryption signatureif (sha === signature) {
    ctx.body = echostr
  } else {
    ctx.body = "wrong"}})Copy the code

After the server verification is successful, scan the qr code of the test number and add the user list, you can start the development.

Development steps

Post link format

Place the link in the service number in the following format (manually concatenated) :

Open.weixin.qq.com/connect/oau…

One thing to note

  1. The domain name of the redirect_URI address must correspond to the security domain name of the JS interface.

  2. Scope Application authorization scope: snsapi_base (the authorization page is not displayed, and only the user OPENID can be obtained), snsapi_userinfo (the authorization page is displayed, and the nickname, gender, and location can be obtained through the OpenID.

Exchange web page authorization access_token with code

There is no code in the redirect_URI redirected link. When we open the link in wechat browser, wechat will automatically jump to the target address and splicetogether the code value after the link. To facilitate viewing, I opened the above link in wechat developer tool and got the following link.

https://open.weixin.qq.com/connect/oauth2/authorize

router.get('/access-token',async ctx=>{
  const grant_type = 'authorization_code'Const code = ctx.query.code // Get access_tokenlet wechatInfo = await fetchGet('/oauth2/access_token',{
    appid,
    secret,
    code,
    grant_type
  })
  console.log('wechatInfo',wechatInfo); / / {"access_token":"28_pC4LZEoIa2boBlUlT2X3itT_yDAzrwiPXgqbxEAgf2XC7Eye2jHj3_WW4Xqf8ra0b-gPaCIC6bmiuS5O_VMQ4g"."expires_in": 7200,"refresh_token":"28_m5hfO9IYieZKJUCU7I_0LzJMdfFLmO10nX0IHiBEkW63yNTy2XBJS2wvke1uISSrKbsS9f3n7PpEjRRQgjl8CA"."openid":"oNqRVxFO4TCF0CehAJfWGJI_kU14"."scope":"snsapi_base"}})Copy the code

Obtaining User information

If the scope is snSAPi_userinfo, the address of redirect_URI is redirect_URI. The server obtains access_token and OpenID after requesting connect/ OAuth2 / Authorize interface. Next pull the user information with these two parameters.

const { access_token,refresh_token,openid } = wechatInfo
let userinfo = await fetchGet('/userinfo',{
  access_token,
  openid,
  lang:'zh_CN'
})
console.log('userinfo',userinfo); / / {"openid":"oNqRVxFO4TCF0CehAJfWGJI_kU14"."nickname":"Mei 氶 "."sex": 0."language":"zh_CN"."city":""."province":""."country":""."headimgurl":"http:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/QpnatTdwxlVfGO1ZdZYlACghRbXhq8sibI2GF8x0XhVqcmPKl7OQxI5wOobHiaiblOr0kaojXLGbi cibc8pa8zk2wPg\/132"."privilege": []}Copy the code

Verify the validity of access_Token and refresh the access_token

This interface is used to check the validity of the Access_token

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

To refresh the access_token, use the refresh_token returned by the/oAUTH2 / Access_token interface as a parameter to call the refreshed interface and get the latest interface

https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN
Copy the code

“errcode”:40163,”errmsg”:”code been used

Code Description: The code is used as an access_token token. The code on the authorization strip is different each time. The code can be used only once and expires automatically if it is not used within 5 minutes.

This error is reported if the connect/ oAuth2 / Authorize interface is called with the same code.

Pay attention to the point

If the user has followed the public account, only openID can pull the user’s information

• Use silent authorization for users who enter the public account

• Use by copying the link to share, or the form of secondary sharing so the user may not pay attention to the public account, want to get their link need to box authorization.

Invalid code

• After silent authorization, you need to adjust the code in the link; otherwise, code reuse will cause invalid errors.

    const url = location.href.replace(/code=\w+&/g,' ')
        history.replaceState(history.state,document.title,url)
Copy the code

The secondary sharing link Settings should be consistent with those in the wechat background setting point security domain name list

• Link cannot share open.weixin.qq.com/.. directly during secondary sharing. The second solution is to determine if there is a code in the link. If there is no code in the link, use location.href = url to jump directly to open.weixin.qq.com/… However, the page will flash, and the interactive experience is not good.

• The negative effect is that if a page is authorized to a second page with code, the page will be forced to brush through location.href again after the code has been processed on the first page, which needs to be considered using keep-alive.

• Parameters uploaded to the link are unstable. If you add parameters on subsequent pages, the page will be forcibly refreshed when you return to the home page. You can save the parameters locally

Official wechat document