PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

博客列表 > PHP+TP小程序授权登陆实现

PHP+TP小程序授权登陆实现

樂成的开发笔记
樂成的开发笔记 原创
2019年07月09日 14:15:25 4383浏览

仅供大家参考学习
1、先说明一下官方:为优化用户体验,使用 wx.getUserInfo 接口直接弹出授权框的开发方式将逐步不再支持。
小程序与小游戏获取用户信息接口调整,请开发者注意升级。
2、使用 button 组件,并将 open-type 指定为 getUserInfo 类型,获取用户基本信息。文档

3、实现思路:写一个微信授权登录按钮让用户实现点击的功能,也就是实现了通过 button 组件去触发 getUserInof 接口。在用户进入微信小程序的时候,判断用户是否授权了,如果没有授权的话就显示授权按钮,让用户去执行授权的操作。如果已经授权了,则隐藏这个按钮,进入首页。
企业微信截图_20190708161827.png
4、小程序源码说明

<!-- index.wxml -->
<button  
wx:if="{{is_auth == 0}}" 
class='auth-btn' 
open-type="getUserInfo" 
lang="zh_CN" 
bindgetuserinfo="onGotUserInfo"></button>
/**index.wxss**/
.auth-btn{
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
z-index: 99;
background-color: rgba(255, 255, 255, 0)
}
.auth-btn::after{
border: none;
}
//index.js
var app = getApp();
Page({
  data: {
    is_auth: app.globalData.is_auth, //判断是否登录
  },
  onLoad: function (options) {
    var that = this;
    setTimeout(function () {
      if (app.globalData.userInfo['NickName'] != 'undefined' || app.globalData.userInfo['HeadUrl'] != 'undefined') {
        that.setData({
          is_auth: 1,//判断是否登录
          nickName: app.globalData.userInfo['NickName'],
          HeadUrl: app.globalData.userInfo.HeadUrl,
        });
      }
    }, 1000);
  },

  //授权用户信息
  onGotUserInfo: function (e) {
    //console.log(app.globalData.userInfo)
    //console.log(app.globalData.is_auth)
    var that = this;
    if (e.detail.userInfo !== undefined) {
      let info = e.detail.userInfo;
      wx.request({
        url: app.d.hostUrl + '/Api/Login/authlogin',
        data: {
          gender: info.gender,
          NickName: info.nickName,
          HeadUrl: info.avatarUrl,
          openid: app.globalData.userInfo.openid,
          save_user: 'save_user' //保存用户信息
        },
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        method: 'post',
        success: function (res) {
          var datas = res.data
          if (datas.status == 1) {
            app.globalData.userInfo['id'] = datas.arr.ID;
            app.globalData.userInfo['NickName'] = datas.arr.NickName;
            app.globalData.userInfo['HeadUrl'] = datas.arr.HeadUrl;
            app.globalData.is_auth = 1;
            that.setData({
              userInfos: app.globalData.userInfo,
              nickName: app.globalData.userInfo.NickName,
              HeadUrl: app.globalData.userInfo.HeadUrl,
              is_auth: 1
            });
          }
        },
        fail: function (res) {
          console.error("get case list error!");
        },
        complete: function () {
          wx.hideLoading();
        }
      });
    }
  },
});
// app.js
App({
  d: {
    hostUrl: 'https://xxx',
    userId: 1,
  },
  onLaunch: function () {
    //调用API从本地缓存中获取数据
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs);
    //login
    this.getUserInfo();
  },
  getUserInfo:function(cb){
    var that = this
    if(this.globalData.userInfo != 0){
      typeof cb == "function" && cb(this.globalData.userInfo)
    }else{
      //调用登录接口
      wx.login({
        success(res) {
          if (res.code) {
            typeof cb == "function" && cb(that.globalData.userInfo);
            that.getUserSessionKey(res.code);
          } else {
            console.log('登录失败!' + res.errMsg)
          }
        }
	  });
    }
  },

  getUserSessionKey:function(code){
    //用户的订单状态
    var that = this;
    wx.request({
      url: that.d.hostUrl + '/Api/Login/getsessionkey',
      method:'post',
      data: {
        code: code
      },
      header: {
        'Content-Type':  'application/x-www-form-urlencoded'
      },
      success: function (res) {
        //--init data        
        var data = res.data;
        if(data.status==0){
          wx.showToast({
            title: data.err,
            duration: 2000
          });
          return false;
        }
        that.globalData.userInfo['sessionId'] = data.session_key;
        that.globalData.userInfo['openid'] = data.openid;
        that.onLoginUser();
      },
      fail:function(e){
        wx.showToast({
          title: '网络异常!err:getsessionkeys',
          duration: 2000
        });
      },
    });
  },
  onLoginUser:function(){
    var that = this;
    var user = that.globalData.userInfo;
    wx.request({
      url: that.d.hostUrl + '/Api/Login/authlogin',
      method:'post',
      data: {
        SessionId: user.sessionId,
        gender:user.gender,
        NickName: user.nickName,
        HeadUrl: user.avatarUrl,
        openid:user.openid
      },
      header: {
        'Content-Type':  'application/x-www-form-urlencoded'
      },
      success: function (res) {
        //--init data        
        var data = res.data.arr;
        var status = res.data.status;
        if(status!=1){
          wx.showToast({
            title: res.data.err,
            duration: 3000
          });
          return false;
        }
        that.globalData.userInfo['id'] = data.ID;
        that.globalData.userInfo['NickName'] = data.NickName;
        that.globalData.userInfo['HeadUrl'] = data.HeadUrl;
        var userId = data.ID;
        if (!userId){
          wx.showToast({
            title: '登录失败!',
            duration: 3000
          });
          return false;
        }
        that.d.userId = userId;
      },
      fail:function(e){
        wx.showToast({
          title: '网络异常!err:authlogin',
          duration: 2000
        });
      },
    });
  },

 globalData:{
    userInfo:[],
    is_auth: 0,
    info:[]
  },

});

5、PHP端源码

//***************************
//  授权登录接口
//***************************
public function authlogin(){
	$openid = $_POST['openid'];
	if (!$openid) {
	    echo json_encode(array('status'=>0,'err'=>'授权失败!'.__LINE__));
	    exit();
	}
	$con = array();
	$con['openid']=trim($openid);
	$uid = M('user')->where($con)->getField('id');
	if ($uid) {
	    $userinfo = M('user')->where('id='.intval($uid))->find();
	    if (intval($userinfo['del'])==1) {
	        echo json_encode(array('status'=>0,'err'=>'账号状态异常!'));
		exit();
	    }
	    if(isset($_POST['save_user']) && $_POST['save_user'] == 'save_user') {
		$data = array();
		$data['id'] = $uid;
		$data['name'] = $_POST['NickName'];
		$data['uname'] = $_POST['NickName'];
		$data['photo'] = $_POST['HeadUrl'];
		$data['sex'] = $_POST['gender'];
		//print_r($data);
		$res = M('user')->save($data);
		$userinfo = M('user')->where('id='.intval($uid))->find();
	    }
    	    $err = array();
	    $err['ID'] = intval($uid);
	    $err['NickName'] = $userinfo['uname'];
	    $err['HeadUrl'] = $userinfo['photo'];
	    echo json_encode(array('status'=>1,'arr'=>$err));
	    exit();
	}else{
	    $data = array();
	    $data['name'] = $_POST['NickName'];
	    $data['uname'] = $_POST['NickName'];
	    $data['photo'] = $_POST['HeadUrl'];
	    $data['sex'] = $_POST['gender'];
	    $data['openid'] = $openid;
	    $data['source'] = 'wx';
	    $data['addtime'] = time();
	    if (!$data['openid']) {
    		echo json_encode(array('status'=>0,'err'=>'授权失败!'.__LINE__));
		exit();
	    }
	    $res = M('user')->add($data);
		if ($res) {
			$err = array();
			$err['ID'] = intval($res);
			$err['NickName'] = $data['name'];
			$err['HeadUrl'] = $data['photo'];
			echo json_encode(array('status'=>1,'arr'=>$err));
			exit();
		}else{
			echo json_encode(array('status'=>0,'err'=>'授权失败!'.__LINE__));
			exit();
		}
	}
}

//***************************
//  获取sessionkey 接口
//***************************
public function getsessionkey(){
	$wx_config = C('weixin');
	$appid = $wx_config['appid'];
	$secret = $wx_config['secret'];
	$code = trim($_POST['code']);
	if (!$code) {
		echo json_encode(array('status'=>0,'err'=>'非法操作!'));
		exit();
	}

	if (!$appid || !$secret) {
		echo json_encode(array('status'=>0,'err'=>'非法操作!'.__LINE__));
		exit();
	}

	$get_token_url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';
			
			$res = $this->httpGet($get_token_url);
			echo $res;
	exit();
}
	
private function httpGet($url) {
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_TIMEOUT, 500);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt($curl, CURLOPT_URL, $url);

	$res = curl_exec($curl);
	curl_close($curl);
	return $res;
}

6、数据库表自行设计,仅供参考

CREATE TABLE `lr_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '小程序用户表',
  `name` varchar(20) NOT NULL COMMENT '登陆账号',
  `uname` varchar(10) DEFAULT NULL COMMENT '昵称',
  `addtime` int(11) NOT NULL DEFAULT '0' COMMENT '创建日期',
  `jifen` float(11,0) DEFAULT '0' COMMENT '积分',
  `photo` varchar(255) DEFAULT NULL COMMENT '头像',
  `tel` char(15) DEFAULT NULL COMMENT '手机',
  `email` varchar(50) DEFAULT NULL COMMENT '邮箱',
  `sex` tinyint(2) NOT NULL DEFAULT '0' COMMENT '性别',
  `del` tinyint(2) NOT NULL DEFAULT '0' COMMENT '状态',
  `openid` varchar(50) NOT NULL COMMENT '授权openid',
  `pid` int(11) DEFAULT '0' COMMENT '父级ID',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=225 DEFAULT CHARSET=utf8;

看起来代码有点多,大家可以写的简洁一点,有问题大家相互交流
(完)

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议
A-Bin2019-12-06 20:35:33 1楼
这是完整源码吗