需求:从微信公众号跳转到小程序,获取到公众号的openid
1.openid?
openId 是用户在当前公众号下的唯一标识(‘身份证’),就是说通过这个openId,就能区分在这个公众号下具体是哪个用户。
2.获取openid
- 登录微信公众平台后台获取公众号的AppID。
2.设置回调地址:开发 > 接口权限 > 网页服务 > 网页授权 > 修改
(1) 需要自己写的H5页面放到已经解析好服务器域名的服务器下,同时把Mp***.txt文件下载下来放到服务器根目录下,此时你的服务器必须能联通外网也就是有公网IP,并且80端口是打开的。
3.H5页面代码:index2.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
user-scalable=no,initial-scale=1.0,maximum=1.0,minimum=1.0">
<title></title>
<!-- 引入jquery-->
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- 引入 1.3.2的js-sdk文件 -->
<script src="https://res.wx.qq.com/open/js/jweixin-1.3.2.js"></script>
</head>
<body>
</body>
<script>
function getCode() {
var code = "";
var local = window.location.href; // 获取页面url
var appid = "wxxxxxxxxxxxxxxx";
code = getUrlCode().code; // 截取code
if (code == null || code === "") {
// 如果没有code,则去请求
window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(
local
)}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`;
// scope=snsapi_base 静默授权,自动跳转到回调页的 特点:用户无感知;
// scope=snsapi_userinfo 非静默授权,第一次有弹框
} else {
// 你自己的业务逻辑
// 在这里跳回自己的小程序,并且把获取到的code传递给小程序
//参考文档:https://developers.weixin.qq.com/miniprogram/dev/component/web-view.html
wx.miniProgram.redirectTo({
url: '/pages/login/login?code=' + code
})
}
}
getCode()
// 截取url中的code方法
function getUrlCode() {
var url = location.search;
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
var strs = str.split("&");
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
}
}
return theRequest;
}
</script>
</html>
4.小程序代码
(1) 小程序中login页面中设置web-view组件,src是刚才的回调地址,地址中的appid就是公众号的appid;redirect_uri是公众号中配置的域名
<web-view v-if="isShow" src="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxxxxxxxxxxxxxxx0&redirect_uri=http://xxx.xxx.com/index2.html&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect" />
<!-- scope=snsapi_base 静默授权,自动跳转到回调页的 特点:用户无感知;-->
<!-- scope=snsapi_userinfo 非静默授权,第一次有弹框 -->
(2) 这里有一个小细节,需要根据条件判断web-view是否显示,因为不设置这个的话,会进入循环(就是H5页面和小程序来回跳转)
data(){
return {
isShow:false
}
},
onLoad(options) {
console.log('获取到的code' + options.code)
if(options.code){
this.isShow = false
// 在这里可以调后台接口,把拿到的code传给后台,获取openid
}else{
this.isShow = true
}
}
现在就可以拿到公众号的 openid了