Laravel 微信小程序后端实现用户登录的示例代码(2)

微信的头像 / 0

小头像默认 / 132

4. 后端上面就写好了,再看下小程序端怎么做的哈,打开小程序的 app.json,添加 "pages/auth/auth",

{
 "pages": [
  "pages/index/index",
  "pages/auth/auth",//做一个登录页面
  "pages/logs/logs"
 ],
 "window": {
  "backgroundTextStyle": "light",
  "navigationBarBackgroundColor": "#fff",
  "navigationBarTitleText": "WeChat",
  "navigationBarTextStyle": "black"
 },
 "sitemapLocation": "sitemap.json",
 "permission": {
  "scope.userLocation": {
   "desc": "你的位置信息将用于小程序位置接口的效果展示"
  }
 }
}

5. 打开 auth.js

const app = getApp();
Page({
 /**
  * 页面的初始数据
  */
 data: {
  UserData: [],
  isClick: false,
 },
 /**
  * 生命周期函数--监听页面加载
  */
 onLoad: function(options) {

 },
 login: function(e) {
  let that=this
  that.setData({
   isClick: true
  })
  wx.getUserInfo({
   lang: "zh_CN",
   success: response => {
    wx.login({
     success: res => {
      let data = {
       code:res.code,
       nickname: response.userInfo.nickName,
       avatar: response.userInfo.avatarUrl,
       country: response.userInfo.country ? response.userInfo.country : '',
       province: response.userInfo.province ? response.userInfo.province : '',
       city: response.userInfo.city ? response.userInfo.city : '',
       gender: response.userInfo.gender ? response.userInfo.gender : '',
       language: response.userInfo.language ? response.userInfo.language : '',
      }
      console.log(data)
      app.globalData.userInfo = data;
      wx.request({
       url: '你的后端地址',//我用的valet,http://ak.name/api/v1/user/login
       method: 'POST',
       data: data,
       header: {
        'Content-Type': 'application/x-www-form-urlencoded'
       },
       success: function (res) {
        console.log(res)
        if (res.statusCode != '200') {
         return false;
        }
        wx.setStorageSync('access_token', res.data.access_token)
        wx.setStorageSync('UserData', res.data.data ? res.data.data : '')
        wx.redirectTo({
         url: '/pages/index/index',
        })
       },
       fail: function (e) {
        wx.showToast({
         title: '服务器错误',
         duration: 2000
        });
        that.setData({
         isClick: false
        })
       },
      });
     }
    })
   },
   fail: function (e) {
    that.setData({
     isClick: false
    })
   },
  })

 }
})