微信登录的流程与实现

流程

点击查看微信登陆官方文档: 微信登陆官方文档

在这里插入图片描述

二维码生成

一、在页面中先引入如下JS文件(支持https)

head:{
   script:[
       {src:"http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"}
   ]
},

二、在需要使用微信登录的地方实例以下JS对象
可以当页面初始化完成时,生成该对象,注意需要首先在页面部分添加一个

标签来生成二维码

<div id="weixin"></div>
 mounted(){
         var obj = new WxLogin({
            self_redirect:false,     //页面跳转方式 true:在二维码位置跳转 false:全局跳转
            id:"weixin",    //当前二维码出现的位置(id)
            appid: "wx3bdb1192c22883f3",      
            scope: "snsapi_login", 
            redirect_uri: "http://note.java.itcast.cn/weixinlogin",   //手机扫码后页面跳转的url地址(跳转到注册web应用绑定的域名下)
        });
    },

在这里插入图片描述

配置本地host和请求端口

一、为了方便测试,在host文件中将跳转的页面改为127.0.0.1

二、nuxt工程的请求端口改为80
修改package.json文件

 "config":{
    "nuxt":{
      "port":80
    }
  },

此时可以根据域名进入到项目中。
在这里插入图片描述

获取用户信息

当进行到此步时,已经进行了扫码确认操作,此时页面的url为

http://note.java.itcast.cn/weixinlogin?code=061Rr6Ha1w1FEz0aUGGa1b15Ts1Rr6Hk&state=undefined

这时,就已经获取了code,然后我们需要通过code获取access_tokenopenid,获取完成之后,根据access_tokenopenid获取用户信息即可。

注意:获取的用户信息主要是name,avatar和token三个属性,获取完后存储到cookie中,跳转首页。

export default {
    asyncData(context){
        //context.params 获取所有地址参数
        //context.query 获取所有请求参数
        let code = context.query.code
        console.log(code)

        let access_token_url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=${secret}&code=${code}&grant_type=authorization_code`
        
        return axios.get(access_token_url).then(res => {
            let openid = res.data.openid;
            let access_token = res.data.access_token;
            let openid_url = `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}`
            return axios.get(openid_url).then(res2 => {
                return {
                    user:{
                        name:res2.data.nickname,
                        avatar:res2.data.headimgurl,
                        token:access_token
                    }
                }
            })
        })
    },
    mounted(){
        if(this.user!=undefined && this.user != null){
            auth.setUser(this.user)
            location.href="/"
        }
    }
    
}

微信登陆完成
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值