赞
踩
详情请查看EasyWeChat手册
首先下载SDK(这里是使用composer下载的4.0)
composer require overtrue/wechat:~4.0 -vvv
你还可以去文档中查看在框架中使用这一章节,就是一些拓展,其实就是下载一个配置文件,这一步不是必要的,但这样显得规范一点。
一般的操作是前端传code,后台拿code去请求用户信息
微信公众号登录
/** * @param $code * @return \think\response\Json * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException * 微信用户授权登录 */ public function userAuth($code) { $config = [ //用户授权配置 'app_id' => 'appID', 'secret' => '秘钥', // 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名 'response_type' => 'array', ];//如果下载了拓展包这里就不用配置了 $app = Factory::officialAccount($config); $token = $app->oauth->getAccessToken($code);//获取token $user = $app->user->get($token['openid']);//获取用户信息 //这里就已经获取到用户信息了,以下是个人操作,可根据自己的业务进行操作。 $data['username'] = $user['openid']; if (!(empty($user['nickname']))) { $data['nickname'] = $user['nickname']; } else { $data['nickname'] = '忆念'.str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT); } // if (!empty($user['sex'])) { $data['sex'] = $user['sex']; } else { $data['sex'] = 1; } // if (!empty($user['headingurl'])) { $data['avatar'] = $user['headingurl']; } else { $data['avatar'] = 'uploads/images/20210325\9cc6af08604995ca6cc193267a2bca1.jpg'; } //查看是否为新用户 if (!(AuthModel::where('username', '=', $user['openid'])->find())) { AuthModel::create($data); } //生成token $key = "token"; $token = [ "iat" => time(),//签发时间 "exp" => time()+3600*24*7,//token过期时间 "username" => $data['username'] ]; $jwt =JWT::encode($token, $key, 'HS256');//生成参数 return success([ 'token' => $jwt, ]); }
小程序登录
/** * @param $code * @return \think\response\Json * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException * 微信用户授权登录 */ public function userAuth() { //下面的参数都是前端传过来的 $code = $this->request->param('code');//前端传过来的code $nickname = $this->request->param('nickname'); $avatar = $this->request->param('avatar'); $iv = $this->request->param('iv'); $encryptedData = $this->request->param('encryptedData'); $config = [ //用户授权配置 'app_id' => 'appID', 'secret' => '秘钥', // 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名 'response_type' => 'array', ]; $app = Factory::miniProgram($config); $user = $app->auth->session($code);//获取openID $decryptedData = $app->encryptor->decryptData($user['session_key'], $iv, $encryptedData);//解密电话 //以下是个人操作,可根据自己的业务逻辑进行操作 $data = [ 'openid' => $user['openid'], 'nickname' => $nickname, 'avatar' => $avatar, 'phone' => $decryptedData['phoneNumber'] ]; //查看是否为新用户 if (!(UserModel::where('openid', '=', $user['openid'])->find())) { UserModel::create($data); } //生成token $key = "token"; $token = [ "iat" => time(),//签发时间 "exp" => time()+3600*24*7,//token过期时间 "openid" => $data['openid'] ]; $jwt =JWT::encode($token, $key, 'HS256');//生成参数 return success([ 'token' => $jwt, ]); }
(做的笔记,自己看的)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。