用vue开发完静态界面后,在index.html文件中添加微信授权操作
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="screen-orientation" content="portrait" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no, minimal-ui">
<meta name="full-screen" content="yes">
<meta name="x5-fullscreen" content="true">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title>微信网页开发</title>
<script src="http://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
<script>
// 网页授权之获取code
const code = getUrlParam("code"),
openId = window.localStorage.getItem("openId");
if (!openId && !code) {
const appid = "xxxxxxxxxxxxxx",
url = encodeURIComponent(location.href.split('#')[0]);
window.location.href = 'http://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appid + '&redirect_uri=' + url +
'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'
}
//获取url中参数
function getUrlParam(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r != null) return decodeURI(r[2]);
return null;
}
</script>
</head>
然后我就拿着vue的本地运行IP地址 http://192.168.10.67:8080/ 粘贴到微信公众号开发工具,结果提示redirect_uri参数错误。
看微信文档,得知这个redirect_uri是微信授权成功之后,需要跳转的页面路径地址,且需要在后台配置。配置方法是
1、在微信公众号请求用户网页授权之前,开发者需要先到公众平台官网中的“开发 - 接口权限 - 网页服务 - 网页帐号 - 网页授权获取用户基本信息”的配置选项中,修改授权回调域名。请注意,这里填写的是域名(是一个字符串),而不是URL,因此请勿加 http:// 等协议头;
2、授权回调域名配置规范为全域名,比如需要网页授权的域名为:www.qq.com,配置以后此域名下面的页面http://www.qq.com/music.html 、 http://www.qq.com/login.html 都可以进行OAuth2.0鉴权。但http://pay.qq.com 、 http://music.qq.com 、 http://qq.com无法进行OAuth2.0鉴权
注意:是这个地方配置:
配置的时候有3个点需要注意:
1、必须使用域名,这个时候就需要使用工具将内网地址映射到公网了,我使用的是花生壳;
2、配置的时候需要将一个txt文件放置到vue的根目录,这里我放到了前端项目的public目录,配置完成后,就可以授权成功了;
3、订阅号是没有“网页授权获取用户基本信息”这个权限的,需要认证为服务号才有,所以刚开始用自己的号测试,走了很多弯路,以为“开发-基本配置-服务器配置”中的url是redirect_uri,其实不是。
开发-基本配置-服务器配置是配置服务器接口地址的
这里配置token,保存的时候微信会发一个get请求到刚填的URL中,验证通过后才能保存成功的。