/*
* 登陆 发放token
* */
public function login()
{
$openid = $this->getUserOpenId();
if (!$openid){
return error('openid获取失败');
}
$nickname = $this->request->param('nickName',''); // 昵称
$avatar = $this->request->param('avatarUrl',''); // 头像
$mobile = $this->request->param('mobile',''); // 电话
$user_model = new User();
$insert_data['nickname'] = $nickname;
$insert_data['avatar'] = $avatar;
$insert_data['mobile'] = $mobile;
$user_info = $user_model->where(['openid'=>$openid])->field('id,avatar,nickname,mobile,openid,')->find();
if(!$user_info){
$insert_data['openid'] = $openid;
$res = $user_model->save($insert_data);
$user_info = Db::name('user')->where(['openid'=>$openid])->field('id,avatar,nickname,mobile,openid')->find();
}else{
$res = $user_model->save($insert_data,['id'=>$user_info['id']]);
}
$uid = $user_info['id'];
// 修改token
$token = $this->getToken($uid);
$user_info['token'] = $token;
if ($res){
return success($user_info,'登陆成功'); // 登陆成功返回给前端
}else{
return error('登陆失败');
}
}
/*
* 获取用户的openid
* */
public function getUserOpenId()
{
$code = $this->request->param('code');
if ($code){
$config = config('wechat.');
$appid=$config['app_id']; // 这里是小程序的appid 替换成自己的
$appsecret = $config['secret'];// 这里是小程序的secret 替换成自己的
$token = json_decode($this->getCurl("https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$appsecret}&js_code={$code}&grant_type=authorization_code"), true);
$openid = $token['openid'];
if ($openid) {
return $openid;
}else{
return error('openid获取失败');
}
}else{
return error('code为空');
}
}
public function getCurl($url)
{
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$result = curl_exec($ch);
return $result;
}
php 微信授权登陆
最新推荐文章于 2023-08-15 21:15:10 发布