uni-app H5授权微信登录怎么获取code?

按照微信官方要准备一个链接:



注意链接中的几个参数:



在methods中写上这两个方法:
getCode() {
                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=xxx&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
                } else {
                    uni.setStorageSync('code', code)
                    this.code = code
                    let that = this
                    shop({
                        url: "/api/user/code",
                        method: "POST",
                        data: {
                            code: that.code
                        }
                    }).then((res) => {
                        res = JSON.parse(res)
                        uni.setStorageSync('user_id', res.data.userinfo.user_id) //存储用户id
                        console.log(res)
                    })
                }
            },
            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
            },

这样就可以在回调的地址里拿到code了

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容