H5调起微信授权

250 阅读1分钟

详情请看:微信开发这文档

微信H5授权获取用户信息,本地测试需申请测试号:测试号申请

通过连接调起授权后重定向至页面(测试需在微信开发者工具):

 window.location.href =
                        `https://open.weixin.qq.com/connect/oauth2/authorize?appid=appid&redirect_uri=http://172.16.8.88:8081&response_type=code&scope=snsapi_userinfo#wechat_redirect`

本地测试需要在测试号后台修改重定向的页面

image.png

image.png

整体代码:

getCodes() {
        const code = this.getUrlParam(
                'code'
        ) // 截取路径中的code,如果没有就去微信授权,如果已经获取到了就直接传code给后台获取openId
        const local = window.location.href
        let redirect_uri = encodeURIComponent(local) //回调的地址要编码

        if (code == null || code === '') {
                window.location.href =
                        `https://open.weixin.qq.com/connect/oauth2/authorize?appid=appid&redirect_uri=http://172.16.8.88:8081&response_type=code&scope=snsapi_userinfo#wechat_redirect`
        } else {
                storage.set('code', code)
                this.loading = false
                this.code = code
                // 将code传给后端
                // this.submitCode()

        }
},
getUrlParam(name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
        var r = window.location.search.substr(1).match(reg)
        if (r != null) return unescape(r[2])
        return null
},