微信网页授权获取用户openid

参考微信授权获取用户openId的方法和步骤 - 简书

设置与开发/公众号设置

1.设置网页授权回调域名(https) domain,下载MP_verify_RTxPGFBmE6RJmFFY.txt验证文件,设置80端口响应微信验证。

server {
        listen       80;
        server_name  domain;
        location 
            /MP_verify_RTxPGFBmE6RJmFFY.txt {
            alias /home/path/MP_verify_RTxPGFBmE6RJmFFY.txt;
            autoindex on;
        }
}
    <a
      id="myLink"
      href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=appid&redirect_uri=https%3A%2F%2Fdomain%2Fdsp&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
    >
    </a>
//点击访问微信接口
    onMounted(() => {
  let router = useRouter();
  if (main.openId) {
    router.push("/login");
  } else {
    let a = document.getElementById("myLink");
    a!.addEventListener("click", function (event) {
      event.preventDefault();
      let targetLocation: any = this.getAttribute("href");
      window.location.href = targetLocation;
    });
    a?.click();
  }
});

//回调重定向URL并获取code
//获取code后,请求以下链接获取access_token:
//https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
onMounted(async () => {
  //获取缓存openid
  if (window.location.href.split("code=")[1] && code.value == "") {
    var params = window.location.href.split("code=")[1].split("&")[0];
    code.value = params;
    let res = await getAccessToken({
      appid: "appid",
      secret: "secret",
      code: code.value,
      grant_type: "authorization_code",
    });
    openId.value = res.data.openid;
    setOpenId(res.data.openid);
  } else {
    router.push("/");
  }
});

server{
       listen 443 ssl
       location / {
                 root  /home/dsp;
                 index index.html index.htm; 
                #解决Failed to load module script: Expected a JavaScript module script but the server错误
                 try_files $uri $uri/ /index.html;
           }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值