【微信小程序】实现登录功能

前端实现

    goLogin() {
        wx.getUserProfile({
            desc: '获取你的昵称、头像',
            // 如果获得授权,发起请求,向服务器提交code
            success: ress => {
                wx.login({
                    timeout: 5000,
                    success(res) {
                        if (res.code) {
                            wx.request({
                                url: 'http://127.0.0.1:8080/api/login',
                                data: {
                                    code: res.code,
                                    userInfo: ress.userInfo
                                },
                                success(res) {
                                  // 全局数据共享
                                    const app=getApp()
                                    
                                    if(res.data.status===200){
                                        app.globalData.userInfo = ress.userInfo
                                        wx.setStorage({
                                            key:'openid',
                                            data:res.data.data.openid
                                        })
                                        wx.switchTab({
                                        url: '/pages/me/me',
                                        })
                                        wx.showToast({
                                            title: '登录成功',
                                            icon: 'success',
                                            duration: 2000
                                        });
                                    }
                                },
                                fail() {
                                    wx.showToast({
                                        title: '登录失败',
                                        icon: 'error',
                                        duration: 2000
                                    });
                                }
                            })
                        }
                    }
                })
            },
            fail(err) {
                //拒绝授权
                wx.showToast({
                    title: '登录失败',
                    icon: 'error',
                    duration: 2000
                });

            }
        })
    },

后端实现

需要向微信服务器发起请求拿到该code的对应属性

function login(req,res) {
    console.log(req.query);
    axios({
      method:'get',
      url:'https://api.weixin.qq.com/sns/jscode2session',
      params:{
        appid:'wx46ed2cf7b729029f',
        secret:'53fdc2da35319c2f7962e4430bf3151e',
        js_code:req.query.code,
        grant_type:'authorization_code'
      }
    }).then(function (response) {
      console.log(response.data);
      res.send({
        status:200,
        data:response.data
      })
    })
    }
posted @ 2022-08-07 21:12  一个大不刘blog  阅读(256)  评论(0编辑  收藏  举报