如何获取微信公众号openid
买泛域名SSL证书 送5斤装现摘猕猴桃一箱、同时提供技开源商城搭建免费技术支持。
泛域名ssl证书 239元1年送1个月、单域名39元1年,Sectigo(原Comodo证书)全球可信证书,强大的兼容性,高度安全性,如有问题7天内可退、可开发票
加微信VX 18718058521 备注SSL证书
【腾讯云】2核2G4M云服务器新老同享99元/年,续费同价
泛域名ssl证书 239元1年送1个月、单域名39元1年,Sectigo(原Comodo证书)全球可信证书,强大的兼容性,高度安全性,如有问题7天内可退、可开发票
加微信VX 18718058521 备注SSL证书
【腾讯云】2核2G4M云服务器新老同享99元/年,续费同价
方法一:用户主动授权
1. 在公众号中添加网页授权的域名(在公众号设置中配置);
2. 引导用户点击相关链接或按钮;
3. 用户点击后,会跳转到你配置的网页;
4. 你可以通过微信网页授权接口获取到用户的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>1 //截取URL字段
2 GetQueryString: function(name) {
3 var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
4 var r = window.location.search.substr(1).match(reg);
5 if (r != null) {
6 return unescape(r[2]);
7 }
8 return null;
9 },
10 getToken: function() {
11 //判断是否有openid
12 if (this.$cookieStore.getCookie("openid") == null) {
13 var url =
14 "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx1234567890&redirect_uri=" +
15 encodeURIComponent(
16 "
17 ) +
18 "&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect&connect_redirect=1#wechat_redirect";
19 location.href = url;
20 var code = this.GetQueryString("code");
21 // console.log(code);
22 axios({
23 url: "接口名" + code
24 }).then(res => {
25 // console.log(res);
26 if (res.data.code == 0) {
27 this.$cookieStore.setCookie("openid", res.data.result);
28 }
29 });
30 } else {
31 this.openid = this.$cookieStore.getCookie("openid");
32 }
33 },方法二:通过中间转换
1. 用户在公众号中输入指令或点击相关按钮;
2. 公众号向用户发送自定义的链接,将用户重定向到中间页面;
3. 中间页面通过code鉴权,获取到用户的openid,并将openid传递给你的后台服务器。
方法三:使用小程序
1. 提供一款关联着你的公众号的小程序;
2. 用户使用小程序登录,小程序会返回用户的openid;
3. 你可以将openid传递给你的后台服务器。



