Wechat website login authorization process is not clear, but also said that he was the front end of 3 years?

Time:2021-10-18

The following is the development document from wechat

Wechat website login authorization process is not clear, but also said that he was the front end of 3 years?

The steps are shown in the figure:

Step 1: the user agrees to authorize and obtains the code

Step 2: exchange code for web access authorization_ token

Step 3: refresh access_ token

Step 4: pull user information

Next, I will paste the code of the actual project, the front end nuxt.js

Front end part

Encapsulate methods in app.js under plug-in plugins

export default ({ app }, inject) => {
    inject('wxLogin', (pageURI) => {
        let url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + process.env.WXPAGEAPPID + "&scope=snsapi_userinfo&state=STATE&redirect_uri=" + encodeURIComponent(pageURI);
        return url
    })
}
methods:{
     login() {
        let url = location.href.split("#")[0];
        location.href = this.$wxLogin(url);
    }
}

If you redirect the current page through this wechat login authorization, you will get the code and send it to the back end

Back end part

<? php
$wxchat = new \thago\util\Wechat($wxconfig['app_id'],$wxconfig['secret']);
 $token = $wxchat->getAccessToken($code);
 $openid = isset($token['openid']) ? $token['openid'] : '';
 $access_token = isset($token['access_token']) ? $token['access_token'] : '';
  if(!empty($openid)){
         $wxUserinfo = $wxchat->getUserinfo($access_token,$openid);
  }

The steps are as follows:

1, according to the code imported from the front end, the official account appid and secret get access_. token

2. Then according to access_ The token pulls user information

Summary:

When you encounter problems in wechat development, you must understand its principle before development in combination with wechat official documents.

More interview questions: click here

This work adoptsCC agreement, reprint must indicate the author and the link to this article