微信—前端获取openId方法和步骤

执行流程
前端 --> 后端服务 --> 微信服务(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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值