如何获取微信公众号openid

方法一:用户主动授权
1. 在公众号中添加网页授权的域名(在公众号设置中配置);
2. 引导用户点击相关链接或按钮;
3. 用户点击后,会跳转到你配置的网页;
4. 你可以通过微信网页授权接口获取到用户的openid。

方法二:通过中间转换
1. 用户在公众号中输入指令或点击相关按钮;
2. 公众号向用户发送自定义的链接,将用户重定向到中间页面;
3. 中间页面通过code鉴权,获取到用户的openid,并将openid传递给你的后台服务器。

方法三:使用小程序
1. 提供一款关联着你的公众号的小程序;
2. 用户使用小程序登录,小程序会返回用户的openid;
3. 你可以将openid传递给你的后台服务器。

方法一代码示例

<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>

猜你喜欢

转载自blog.csdn.net/qq_43314341/article/details/131226622