h5 development website, detailed steps to authorize WeChat login

The detailed steps are as follows:

  1. Create an application on the WeChat open platform and obtain the corresponding AppID.

  2. Introduce WeChat JS-SDK in your website, you can introduce it in the following ways:

<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
  1. After the page is loaded, initialize the WeChat JS-SDK and configure it with your AppID. Configuration parameters can be obtained through the background interface, and then configured on the front end:
// 后台接口返回的配置参数
const wxConfig = {
    
    
  appId: 'your-app-id',
  timestamp: 'your-timestamp',
  nonceStr: 'your-noncestr',
  signature: 'your-signature',
};

// 初始化微信 JS-SDK
wx.config({
    
    
  ...wxConfig,
  jsApiList: ['checkJsApi', 'login', 'getUserInfo'], // 需要使用的微信 API 列表
});

Among them, timestamp, nonceStrand signatureare obtained through the background interface, and are used to verify the signature of WeChat JS-SDK.

  1. Add a button to the page to trigger WeChat login authorization:
<button id="loginBtn">微信登录</button>
  1. In the click event of the button, call the method of WeChat JS-SDK wx.loginto authorize WeChat login:
document.querySelector('#loginBtn').addEventListener('click', function() {
    
    
  wx.login({
    
    
    success: function(res) {
    
    
      if (res.code) {
    
    
        // 使用 res.code 发起后台接口请求,获取用户的 openid 和 access_token
        // 可以将 res.code 发送到后台,后台通过调用微信接口获取用户的 openid 和 access_token
        // 然后可以根据 openid 进行用户登录或注册操作
      } else {
    
    
        console.log('登录失败:' + res.errMsg);
      }
    }
  });
});

In wx.loginthe callback function of the method, if it is successfully obtained res.code, it can be sent to the background, and the background can obtain the user's and res.codeby calling the WeChat interface , and then perform user login or registration operations based on .openidaccess_tokenopenid

  1. wx.getUserInfoIf you need to get the user's detailed information, you can call the method to get the user information after the login is successful :
wx.getUserInfo({
    
    
  success: function(res) {
    
    
    const userInfo = res.userInfo;
    // 可以将用户信息发送到后台进行处理
  }
});

The above are the detailed steps to implement WeChat login authorization in the H5 development website. It should be noted that the WeChat login authorization needs to be performed in the internal environment of WeChat, so in a non-WeChat environment, the WeChat login authorization function may not be used normally. In addition, according to WeChat's latest policy requirements, user information encryption needs to be performed in the background interface to protect user privacy.

Guess you like

Origin blog.csdn.net/weixin_48596030/article/details/131835863