1、需要引入微信的Js
<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
2、拿用户Code
//直接让用户点击或跳转到该页面,带以下参数
const APPID = "wx7b4b9c0f2bc48ba7"
// const SCOPE = "snsapi_userinfo"
const SCOPE = "snsapi_base"
const REDIRECT_URI = ""
window.location.href="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+APPID+"&redirect_uri="+REDIRECT_URI+"&response_type=code&scope="+SCOPE+"&state=STATE#wechat_redirect"
- 以上的回调地址需要在公众号后台配置回调地址,在接口权限中设置
3、跳转到的页面,需要携带code跳回来
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" id="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>远程</title>
</head>
<body>
code:<h5 id="code"></h5>
state:<h5 id="state"></h5>
<script>
function getUrlParam(paramName) {
let url = window.location.href;
let oRegex = new RegExp("[\?&]" + paramName + "=([^&]+)", "i");
let oMatch = oRegex.exec(url);
if (oMatch && oMatch.length > 1) {
return decodeURI(oMatch[1]);
} else {
return "";
}
}
// 获取code和state
let code = getUrlParam("CODE")
let state = getUrlParam("STATE")
document.getElementById("code").innerHTML = code
document.getElementById("state").innerHTML = state
window.location.href="http://localhost:8082/get-code.html?code="+code
</script>
</body>
</html>
4、后端接口编写