微信网页授权获取用户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;}
}
<aid="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 () => {//获取缓存openidif (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 ssllocation / {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;}
}