从现在开始正式进入公众号H5开发,首先需要先获取用户openid。
由于获取openid需要先跳转到微信然后带参数跳转回来,因此只能在前端实现openid的获取。
可能以后很多页面都需要获取openid,因此把获取方法直接写在根目录的App.vue文件的methods里
完整的代码请在官方插件市场下载:https://ext.dcloud.net.cn/plugin?id=4829
代码已经加了详细的说明
methods: {
async getOpenid() {
//如果缓存存在,则直接返回
let openid = uni.getStorageSync('openid')
if (openid) return openid
//本地无法跳转,不能获取openid
if (window.location.href.indexOf('localhost') != -1) return false;
//先读取公众号配置
let config = await this.bctosCommon('config')
let appid = config.result.appId
let secret = config.result.appSecret
//获取微信跳转带回来的参数
let option = this.getGetParam()
if (typeof(option.state) == "undefined" || option.state != 'bctos') {
//第一步:用户同意授权,获取code
let redirect_uri = encodeURIComponent(location.href.split('#')[0])
window.location.href = 'https://open.weixin.qq.com/connect/oauth2/' +
`authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=bctos#wechat_redirect`
} else if (typeof(option.state) != "undefined" && option.state == 'bctos') {
//第二步:通过code换取网页授权access_token
if (!typeof(option.code) || option.code == '') {
this.error('获取code失败')
} else {
//前端不能跨域请求微信服务器,只能通过云函数代请求
let res = await this.bctosCommon('jsonp', {
url: 'https://api.weixin.qq.com/sns/oauth2/access_token?grant_type=authorization_code' +
`&appid=${appid}&secret=${secret}&code=${option.code}`
})
console.log('resres', res);
if (typeof(res.result.data) != "object" || typeof(res.result.data.openid) == "undefined") {
this.error(JSON.stringify(res.result.data))
} else {
uni.setStorageSync('openid', res.result.data.openid)
return res.result.data.openid
}
}
}
return false
}
}
把pages/index/index
里的onLoad方法修改成下面
onLoad() {
getApp().getOpenid().then(res => {
console.log('openid', res);
})
},
让页面一进入就获取openid。保存在内置浏览器看到获取的openid是false
这是因为本地不能直接获取,我们必须上传到前端网页托管
,然后使用正式域名访问才能获取
由于第一次上传,因此需要一次性上传所有内容
由于之前的章节介绍如何把域名(weixin-h5.bctos.cn)部署到前端网页托管,因此这次只需要上传代码即可
设置点击打开根目录下的manifest.json文件,点击H5配置
选用hash路由模式,因为前端网页托管不支持配置rewrite,使用history会导致微信跳转回来时页面找不开。
运行的基础路径不要设置,我们直接使用域名访问,不要加二级目录
也不要勾选启用https协议,因为之前我们没有加证书,如果你的域名已经加证书,就可以选
然后在项目上右键--发布--上传网站到服务器
然后选择我们之前配置的bctos-weixin-h5空间
在控制台看到这些提示就说明上传成功了
里面提示的域名还是加了https,访问时注意自己不要加就行。
然后打开微信开发工具
(就是微信提供开发小程序那个工具),在网页调试里输入网址:weixin-h5.bctos.cn
就可以看到能正常获取到的openid了
本文由小韦云原创,转载请注明出处:http://www.bctos.cn/doc/18/1960,否则追究其法律责任
关键词:openid