【微信】微信授权获取openid

1. 介绍

页面加载之前先通过微信授权获取openid(账号唯一标识)

2. 公众号管理者授权

添加开发人员为该公众号的开发者和运营者

在这里插入图片描述

3. 使用测试账号

  1. 配置测试账号信息,可以使用本地 ip 测试公共号授权功能,192.168.xx.xx是本机局域网ip,8080是项目启动端口,要记得关注测试号的公众号

    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

    在这里插入图片描述

  2. 使用微信开发者工具本地测试,这里数据上面配置的本地 ip 和 port

    在这里插入图片描述

  3. vue 项目,在 app.vue 中获取 openid

    <template>
      <div id="app">
        <router-view />
      </div>
    </template>
    
    <script>
    export default {
      created() {
        let code = this.getUrlCode("code");
        const appId = "xxxxxxxxxxxxxx"; // 使用测试账号中的 appid
        const secret = "xxxxxxxxxxxxxxxxxxxxxxxx"; // 使用测试账号中的 appsecret
        // 获取 code
        if (!code) {
          const redirectUri = encodeURIComponent(window.location.href);
          const scope = "snsapi_userinfo";
          const state = "123";
          const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`;
          window.location.href = url;
        }
        // 获取 access_token、openId
        if (code) {
          this.axios
            .get("/sns/oauth2/access_token", {
              params: {
                appid: appId,
                secret: secret,
                code: code,
                grant_type: "authorization_code"
              }
            })
            .then(resp => {
              console.log(resp.data);
              window.localStorage.setItem("pms_openid", resp.data.openid);
            });
        }
      },
      methods: {
        // 获取地址栏的参数
        getUrlCode(name) {
          return (
            (new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(
              location.href
            ) || [, ""])[1].replace(/\+/g, "%20") || null
          );
        }
      }
    };
    </script>
    
    
  4. 需要注意的地方:获取 access_token、openId 是调用微信api接口,会出现跨域,以下是通过 nginx 代理解决办法

    // 开发
    module.exports = {
      devServer: {
        host: "0.0.0.0",
        open: true,
        proxy: {
          '/sns': {
            target: 'https://api.weixin.qq.com',
            secure: true,  // 如果是https接口,需要配置这个参数
            changeOrigin: true,
          }
        }
      }
    }
    
    // 线上
     # 请求微信获取openid接口
    	location /sns {
    		proxy_pass https://api.weixin.qq.com;
    	}
    
    
  5. 开发需要的 appid 和 appsecret

    在这里插入图片描述

更多细节可以参考微信官方文档
https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值