效果图
授权.png
wxml页面
给button绑定冒泡事件,也就是我们说的点击事件
<button bindtap="getUserProfile" >授权登录</button>
js页面
这里wx.getUserProfile方法可以从底部弹框提示用户授权,success是用户确认授权回调方法,
可以console.log(result)查看以下数据,可以在userInfo中获取用户的一些基本信息,例如头像,昵称。通过wx.login()获取微信平台提供给我们的code(5分钟内有效,每次请求code都不一样),有了code我们就可以通过wx.request()向后端发起请求了;
getUserProfile(e){
let that = this;
wx.getUserProfile({
desc: '展示用户信息',
success: (result) => {
// 接收名称和头像
let nickName = result.userInfo.nickName;
let avatarUrl = result.userInfo.avatarUrl;
wx.login({
timeout:10000,
success(res){
let code = res.code//获取code
wx.request({
url: 'http://www.day12.com/login',
method:'post',
data:{
code:code,
nickName:nickName,
avatarUrl:avatarUrl
},success: ret=>{
console.log(ret)
}
})
}
})
},
fail: (res) => {
console.log(res)
},
complete: (res) => {},
})
},
php后端
通过code和自己开发平台的appid和appSecret调用微信平台提供给我们的url获取openid和session_key,这里我们可以用file_get_contents()或者curl都可。
function login()
{
$code = request()->param('code');
$nickName = request()->param('nickName');
$avatarUrl = request()->param('avatarUrl');
$appId = "";//appid
$appSecret = "";//填写你微信公众开发平台的appSecret
$url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appId}&secret={$appSecret}&js_code={$code}&grant_type=authorization_code";
//获取openid和session_key
$userInfo = json_decode(file_get_contents($url),true);
$userData = [
'nick_name'=>$nickName,
'avatar_url'=>$avatarUrl,
'open_id'=>$userInfo['openid'],
'session_key'=>$userInfo['session_key']
];
$user = new User();
//根据openid查询用户数据判断用户数是否首次登陆
$res = User::get(['open_id'=>$userInfo['openid']]);
if($res)
{
//返回查询数据的id //更新用户昵称头像
$id = $res->id;
$user->save(['nick_name'=>$nickName,'avatar_url'=>$avatarUrl],['id'=>$id]);
}else{
$res = $user->save($userData);//新增
$id = $user->id;
}
return json(['code'=>200,'msg'=>'success','data'=>$id]);
}
sql user表
CREATE TABLE `user` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`user_name` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL COMMENT '姓名',
`phone` varchar(15) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL COMMENT '手机号',
`nick_name` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL COMMENT '昵称',
`avatar_url` varchar(150) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL COMMENT '头像',
`open_id` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL,
`session_key` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL,
`create_time` datetime(0) NULL DEFAULT NULL,
`last_time` datetime(0) NULL DEFAULT NULL,
`update_time` datetime(0) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 12 CHARACTER SET = utf8 COLLATE = utf8_unicode_ci ROW_FORMAT = Dynamic;
jwt
composer require lcobucci/jwt 3.3
2.在extend/tools/jwt目录下创建Token.php文件
<?php
namespace tools\jwt;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\ValidationData;
class Token
{
// createToken为生成token令牌的方法
public static function createToken($uid = null)
{
$signer = new Sha256();//加密规则
$time = time();//当前时间
$token = (new Builder())
->issuedBy('teacher')//签发人
->canOnlyBeUsedBy('student')//接收人
->identifiedBy('MarsLei', true) //标题id
->issuedAt($time)//发出令牌的时间
->canOnlyBeUsedAfter($time) //生效时间(即时生效)
->expiresAt($time + 3600) //过期时间
->with('uid', $uid) //用户id
->sign($signer, 'my') //签名
->getToken(); //得到token
return (string)$token;
}
//verifyToken 为验证token令牌的方法
public static function verifyToken($token=null){
//检测是否接收到了token
if(empty($token)){
return 0;
}
//转化为可以验证的token
$token = (new Parser())->parse((string) $token);
//验证基本设置
$data = new ValidationData();
$data->setIssuer('teacher');
$data->setAudience('student');
$data->setId('MarsLei');
if(!$token->validate($data)){
return 0;
}
//验证签名
$signer = new Sha256();
if(!$token->verify($signer, 'my')){
return 0;
}
//验证通过,返回用户id
return $token->getClaim('uid');
}
}
3.生成token 验证token的方法
一般我们在登录成功后将用户数据的id生成token令牌
//生成token
$token = Token::createToken($userInfo['id']); //生成token
//验证Token
$res = Token::verifyToken($token);
if (!$res) {
//验证失败
$this->error('token令牌失效', 'home/Login/login');
}