执行流程
前端 --> 后端服务 --> 微信服务(openId/UnionID)
微信公众号网页开发授权:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html#0
<template>
<div></div>
</template>
<script>
export default {
name: 'Index',
data () {
return {
}
},
created () {
this.getCode()
},
// ***放main.js中;放入口文件中
methods: {
getCode () { // 非静默授权,第一次有弹框
const code = getUrlParam('code') // 截取路径中的code,如果没有就去微信授权,如果已经获取到了就直接传code给后台获取openId
const local = window.location.href
if (code == null || code === '') {
window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + window.APPID + '&redirect_uri=' + encodeURIComponent(local) + '&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect'
} else {
this.getOpenId(code) //把code传给后台获取用户信息
}
},
getOpenId (code) { // 通过code获取 openId等用户信息,/api/user/wechat/login 为后台接口
let _this = this
// 后端接口实现:获取code后,请求以下连接获取access_token: https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
this.$http.post('/api/user/wechat/login', {code: code}).then((res) => {
let datas = res.data
/* // 前端--> 应用后台 --> 微信后台
{
"access_token": "ACCESS_TOKEN",
"expires_in": 7200,
"refresh_token": "REFRESH_TOKEN",
"openid": "OPENID",
"scope": "SCOPE"
}
*/
if (datas.code === 0 ) {
console.log('成功')
}
}).catch((error) => {
console.log(error)
})
},
getUrlParam (name) { // 获取url指定参数
var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)') // 构造一个含有目标的正则表达式对象
var r = window.location.search.substr(1).match(reg) // 匹配目标参数
if (r != null) return unescape(r[2])
return null // 返回参数值
}
}
}
</script>
<style lang="less" scoped>
</style>
微信h5静默、非静默授权获取用户openId的方法和步骤https://blog.csdn.net/qq_35430000/article/details/79299529
解决微信授权成功后点击按返回键出现空白页和报错的问题https://blog.csdn.net/qq_35430000/article/details/79299529