在没开始前,要说下,授权和登录,需要先授权才能拿到用户的头像,昵称等信息,当这只是用户信息授权scope具体自己查看,这里主要讲用户信息授权
要拿到用户的具体信息,还需要登录,通过wx.login() 获取code,登录流程图如下:
微信规则改变后,用户授权需要用户主动触发;open-type="getUserInfo"
话不多说上"马",我要飙车了;
通过wx.getSetting()判断用户是否授权;
app.js// 获取用户信息
wx.getSetting({
success: res => {
if (res.authSetting['scope.userInfo']) {
// 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
wx.getUserInfo({
success: res => {
// 可以将 res 发送给后台解码出 unionId
this.globalData.userInfo = res.userInfo
// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
// 所以此处加入 callback 以防止这种情况
if (this.userInfoReadyCallback) {
this.userInfoReadyCallback(res)
}
}
})
} else {
wx.reLaunch({ //未授权跳转到授权页面,我这里用login,不要误解,因为我授权和登录一起做的
url: '/pages/login/login',
})
}
}
})
login.js//index.js
//获取应用实例
const app = getApp()
Page({
data: {
userInfo: {},
canIUse: wx.canIUse('button.open-type.getUserInfo')
},
onLoad: function () {
var that = this;
// 查看是否授权
wx.getSetting({
success: function (res) {
if (res.authSetting['scope.userInfo']) {
// wx.getUserInfo({
// success: function (res) {
//调取登录按钮
that.userLogin();
// }
// });
} else {
// 用户没有授权
// 改变 isHide 的值,显示授权页面
that.setData({
isHide: true
});
}
}
});
},
// 用户登录方法
userLogin: function () {
var that = this
wx.login({
success: res => {
var code = res.code
wx.getUserInfo({ //得到rawData, signatrue, encryptData
success: function (data) {
var rawData = data.rawData;
var signature = data.signature;
var encryptedData = data.encryptedData;
var iv = data.iv
wx.request({
url: 'http://你的路径/wx_login',
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
method: 'POST',
data: {
"code": code,
"rawData": rawData,
"signature": signature,
'iv': iv,
'encryptedData': encryptedData
},
success: res => {
if (res.data.code == '101') {
wx.showToast({
title: res.data.msg,
icon: 'none',
duration: 2000
})
} else {
wx.setStorageSync('skey', res.data.data) //存入缓存用户业务请求验证登录态
wx.switchTab({ //成功跳转页面
url: '/pages/home/home',
})
}
},
})
},
})
}
})
},
// 用户授权方法
bindGetUserInfo: function (e) {
if (e.detail.userInfo) {
//用户按了允许授权按钮
var that = this;
//授权成功后执行登录方法;
this.userLogin();
//授权成功后,通过改变 isHide 的值,让实现页面显示出来,把授权页面隐藏起来
// that.setData({
// isHide: false,
// userInfo: e.detail,
// });
} else {
//用户按了拒绝按钮
wx.showModal({
title: '警告',
content: '您点击了拒绝授权,将无法进入小程序,请授权之后再进入!!!',
showCancel: false,
confirmText: '返回授权',
success: function (res) {
// 用户没有授权成功,不需要改变 isHide 的值
if (res.confirm) {
console.log('用户点击了“返回授权”');
}
}
});
}
}
})
login.wxml
申请获取以下权限
获得你的公开信息(昵称,头像等)
授权登录
请升级微信版本login.wxss
.header {
margin: 90rpx 0 90rpx 50rpx;
border-bottom: 1px solid #ccc;
text-align: center;
width: 650rpx;
height: 300rpx;
line-height: 450rpx;
}
.header image {
width: 200rpx;
height: 200rpx;
}
.content {
margin-left: 50rpx;
margin-bottom: 90rpx;
}
.content text {
display: block;
color: #9d9d9d;
margin-top: 40rpx;
}
.bottom {
border-radius: 80rpx;
margin: 70rpx 50rpx;
font-size: 35rpx;
}
wx_login.php CI框架 wxBizDataCrypt下载地址public function wx_login()
{
$APPID = '你的appid’;
$AppSecret = '你的secret';
if(empty($this->input->post('code')) || empty($this->input->post('signature')) || empty($this->input->post('rawData')) || empty($this->input->post('encryptedData')) || empty($this->input->post('iv'))){
Response::error('参数缺失!'); //自己封装的json_encode,
}
$code = $this->input->post('code');
$url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $APPID . "&secret=" . $AppSecret . "&js_code=" . $code . "&grant_type=authorization_code";
$arr = $this->httpGet($url);
$arr = json_decode($arr, true);
if(empty($arr)||empty($arr['openid'])||empty($arr['session_key'])){
Response::error('请求微信接口失败,appid或私钥不匹配!');
}
// 数据签名校验
$session_key = $arr['session_key'];
$signature = $this->input->post('signature');
$rawData = $this->input->post('rawData');
$signature2 = sha1($rawData . $session_key);
if ($signature != $signature2) {
Response::error('数据签名验证失败!');
}
require_once dirname(dirname(__DIR__)) . '/libraries/wx_aes/wxBizDataCrypt.php'; //信息解密下载地址
$encryptedData = $this->input->post('encryptedData');
$iv = $this->input->post('iv');
$pc = new \WXBizDataCrypt($APPID, $session_key);
$errCode = $pc->decryptData($encryptedData, $iv, $data); //解密后的用户信息
$data = json_decode($data,true);//获得用户信息
if ($errCode == 0) {
$data['session_key']=$session_key;
unset($data['watermark']);
$this->wxUser_model->wx_user($data);
$time = 2*60*60;
$data['skey'] = md5($session_key); //用作登录态验证
$key = 'ses_'.$data['skey'];
$user_json = json_encode($data);
$this->cache->save($key,$user_json,$time);//我这用的是redis缓存的
//不是放此处,$this->load->driver('cache', array('adapter' => 'redis', 'backup' => 'file'));
Response::returnData($data['skey']);
} else {
Response::error($errCode);
}
}
public function httpGet($url){
$info=curl_init();
curl_setopt($info,CURLOPT_RETURNTRANSFER,true);
curl_setopt($info,CURLOPT_HEADER,0);
curl_setopt($info,CURLOPT_NOBODY,0);
curl_setopt($info,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($info,CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($info,CURLOPT_URL,$url);
$output= curl_exec($info);
curl_close($info);
return $output;
}
}