微信小程序登录php实现

本文介绍了一个微信小程序的登录流程,包括前端代码如何获取用户信息和code,以及如何将这些信息发送到后端进行用户登录和注册。同时,后端PHP代码展示了如何验证code,查询或创建用户,并返回相应的登录状态。
摘要由CSDN通过智能技术生成

一.微信小程序前端代码:

login.js

const app = getApp()
import Notify from '../../components/vant/notify/notify';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: [],
    code: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        this.setData({
          code: res.code
        })
        console.log('login中的code的值为++++++', res.code)
      }
    })

    var that = this;
    //查看是否授权
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          console.log(res)
          wx.switchTab({
            url: '../squre/squre',
          })
        } else {
          //用户没有授权
          console.log("用户没有授权");
        }
      }
    });
  },

  bindGetUserInfo: function (res) {
    if (res.detail.userInfo) {
      //用户按了允许授权按钮
      var that = this;
      // 获取到用户的信息了,打印到控制台上看下
      console.log("用户的信息如下:");
      console.log(res.detail.userInfo);
      //授权成功后,通过改变 isHide 的值,让实现页面显示出来,把授权页面隐藏起来
      that.setData({
        isHide: false,
        userInfo: res.detail.userInfo
      });
      app.globalData.userInfo = res.detail.userInfo

      //用户信息后台登录注册并设置cookie
      wx.request({
        url: 'http://localhost/public/index.php/Home/User/sign',
        method: 'POST',
        data: {
          "code": this.data.code,
          "username": this.data.userInfo.nickName,
          "faceUrl": this.data.userInfo.avatarUrl,
        },
        header:{
          'content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
        },
        success: (res) => {
          console.log("登录成功的返回值", res.data)
            app.globalData.user = res.data.data
            console.log("全局变量的user信息",app.globalData.user)
          console.log("cookie信息",res.header['Set-Cookie']) 
          if (res && res.header && res.header['Set-Cookie']) {
            wx.setStorageSync('cookieKey', res.header['Set-Cookie']); //保存Cookie到Storage
          }
        },
        fail: (res) => {
          console.log("登录失败")
          Notify({
            message: '登录失败 , 请连接网络',
            color: '#ad0000',
            background: '#ffe1e1',
          });
        }
      })


      wx.switchTab({
        url: '../squre/squre',
      })
    } else {
      //用户按了拒绝按钮
      wx.showModal({
        title: '警告',
        content: '您点击了拒绝授权,将无法进入小程序,请授权之后再进入!!!',
        showCancel: false,
        confirmText: '返回授权',
        success: function (res) {
          // 用户没有授权成功,不需要改变 isHide 的值
          if (res.confirm) {
            console.log('用户点击了“返回授权”');
          }
        }
      });
    }
  }
})

login.wxss

.headView {
  margin: 90rpx 50rpx 90rpx 50rpx;
}

.headImageView {
  display: flex;
  margin-left: 255rpx;
  margin-top: 50rpx;
  margin-right: 50rpx;
  margin-bottom: 0rpx;
  height: 100rpx;
}

.headImage {
  display: flex;
  width: 100rpx;
  height: 100rpx;
}

.titleText {
  margin-left: 50rpx;
  margin-top: 50rpx;
  margin-bottom: 20rpx;
  font-size: 28rpx;
  color: #020e0f;
  text-align: center;
}

.contentText {
  margin-left: 50rpx;
  margin-top: 0rpx;
  margin-bottom: 0rpx;
  font-size: 28rpx;
  color: #666;
  text-align: center;
}

.authBtn {
  margin-top: 70rpx;
  margin-left: 50rpx;
  margin-right: 50rpx;
  height: 90rpx;
  font-size: 35rpx;
}

login.wxml

<view>
  <view class='headView'>
    <view class='headImageView'>
      <image class='headImage' src='http://a0.att.hudong.com/16/12/01300535031999137270128786964.jpg' mode='scaleToFill'></image>
    </view>

    <view class='titleText'>申请获取以下权限</view>

    <view class='contentText'>获得你的公开信息(昵称,头像,手机等)</view>

    <button class='authBtn' type='primary' open-type='getUserInfo' bindgetuserinfo='bindGetUserInfo'>授权登录</button>
  </view>
</view>

<!-- 在页面内添加对应的节点 -->
<van-notify id="van-notify" />


app.js

//app.js
App({
  onLaunch: function () {
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        this.globalData.code = res.code
      }
    })
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo

              wx.request({
                url: 'http://localhost/public/index.php/Home/User/sign',
                method: 'POST',
                data: {
                  "code": this.globalData.code,
                  "username": this.globalData.userInfo.nickName,
                  "faceUrl": this.globalData.userInfo.avatarUrl,
                },
                header:{
                  'content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
                },
                success: (res) => {
                  console.log("登录成功的返回值", res.data)
                  if(res.data.error_code == 2){
                    this.globalData.user = res.data.data
                  }
                  console.log(this.globalData.user)
                  if (res && res.header && res.header['Set-Cookie']) {
                    wx.setStorageSync('cookieKey', res.header['Set-Cookie']); //保存Cookie到Storage
                  }
                }        
              })
              // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },
  globalData: {
    userInfo: null,
    user:null
  }
})

php后端代码

   public function sign()
    {
        if (!$_POST['code']) {
            $return_data = array();
            $return_data['error_code'] = 1;
            $return_data['msg'] = '参数不足:code';
            $this->ajaxReturn($return_data);
        }

        if (!$_POST['username']) {
            $return_data = array();
            $return_data['error_code'] = 1;
            $return_data['msg'] = '参数不足:username';
            $this->ajaxReturn($return_data);
        }

        if (!$_POST['faceUrl']) {
            $return_data = array();
            $return_data['error_code'] = 1;
            $return_data['msg'] = '参数不足:faceUrl';
            $this->ajaxReturn($return_data);
        } else {
            $appid = "wx199470d6a408f9d2"; //appid
            $secret = "07d10517c4c6dce324aa2536082424d1"; //app密钥
            $code = $_POST['code'];//小程序传来的code值
            $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $secret . '&js_code=' . $code . '&grant_type=authorization_code';

            $info = file_get_contents($url);//发送HTTPs请求并获取返回的数据,推荐使用curl
            $json = json_decode($info);//对json数据解码
            $arr = get_object_vars($json);
            $openid = $arr['openid'];

            //实例化数据表
            $User = M('User');

            //设置查询条件
            $where = array();
            $where['user_id'] = $openid;

            //执行查询条件
            $user = $User->where($where)->find();

            if ($user) {
                $return_data = array();
                $return_data['error_code'] = 2;
                $return_data['msg'] = '已存在数据表中';
                $return_data['data'] = $user;

                $this->ajaxReturn($return_data);
            } else {
                //构建插入的数据
                $data = array();
                $data['user_id'] = $openid;
                $data['username'] = $_POST['username'];//用户名
                $data['face_url'] = $_POST['faceUrl'];

                //插入数据
                $result = $User->add($data);//add函数添加数据成功之后返回的是该数据的id

                if ($result){
                    $return_data = array();
                    $return_data['error_code'] = 0;
                    $return_data['msg'] = '登录成功';
                    $return_data['data']['user_id'] = $openid;
                    $return_data['data']['username'] = $_POST['username'];
                    $return_data['data']['face_url'] = $_POST['faceUrl'];

                    $this->ajaxReturn($return_data);
                }
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值