1.首先需要公眾號綁定好微信小程序。
https://jingyan.baidu.com/article/f96699bbfc499b894e3c1b00.html 這個是百度上綁定的案例可以參考綁定。
2.創建H5頁面,獲取授權,拿到公眾號的code。下面是頁面代碼,直接復制即可。
<!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 = "wx064d2db6a22696a5";
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 {
// url 填寫的是授權成功后調轉到小程序的頁面並且把獲取到的code傳遞給小程序
wx.miniProgram.redirectTo({
url: '/page/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>
3.在小程序中用web-view 將H5引入到小程序中。下面直接上代碼:

前人種樹,后人乘涼。記住小程序的獲取小程序的openid是沒有用的,只能獲取公眾號的openid才可以。