How to get WeChat official account openid

Method 1: Active authorization by the user
1. Add the domain name authorized by the web page in the official account (configured in the official account settings);
2. Guide the user to click the relevant link or button;
3. After the user clicks, it will jump to the web page you configured ;
4. You can obtain the user's openid through the WeChat webpage authorization interface.

Method 2: Through intermediate conversion
1. The user enters an instruction in the official account or clicks a related button;
2. The official account sends a custom link to the user, redirecting the user to the intermediate page;
3. The intermediate page passes code authentication to obtain to the user's openid, and pass the openid to your backend server.

Method 3: Using Mini Program
1. Provide a Mini Program associated with your official account;
2. The user logs in with the Mini Program, and the Mini Program will return the user's openid;
3. You can pass the OpenID to your background server.

Method 1 code example

<template>
  <div>
    <button @click="redirectToAuth">点击授权</button>
  </div>
</template>

<script>
export default {
  methods: {
    redirectToAuth() {
      const appid = 'YOUR_APP_ID';
      const redirectUri = encodeURIComponent('http://yourwebsite.com/callback.html');
      const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;

      window.location.href = authUrl;
    },
  },
  mounted() {
    const code = (new URLSearchParams(window.location.search)).get('code');

    if (code) {
      const appid = 'YOUR_APP_ID';
      const requestUrl = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=YOUR_APP_SECRET&code=${code}&grant_type=authorization_code`;

      fetch(requestUrl)
        .then(response => response.json())
        .then(data => {
          if (data && data.openid) {
            const openid = data.openid;
            // 在这里可以存储或使用用户的openid
            // ...
          }
        })
        .catch(error => {
          console.error(error);
        });
    }
  }
}
</script>

Guess you like

Origin blog.csdn.net/qq_43314341/article/details/131226622