123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251 |
- <?php
- namespace App\Traits;
- use App\Services\LoginService;
- use EasyWeChat\Factory;
- use Txj\Elastic\Facades\ES;
- use Illuminate\Support\Facades\Cache;
- use Illuminate\Support\Facades\Request;
- /**
- * 微信小程序 登录及绑定
- *
- * Trait WeappLoginTrait2
- * @package App\Traits
- */
- trait WeappLoginTrait2
- {
- public string $wechatConfigName = 'default';
- /**
- * 是否开启登录日志记录
- *
- * @var bool
- */
- private bool $is_open_login_log = false;
- /**
- * 微信小程序登录操作,如果已经绑定则直接登录,没有绑定,则需要绑定手机号
- *
- * @return String
- * @throws \EasyWeChat\Kernel\Exceptions\DecryptException
- * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
- * @throws \Exception
- */
- public function wxBind()
- {
- $requestData = Request::all();
- $code = $requestData['code'] ?? '';
- $wxInfo = $requestData['userInfo'] ?? '';
- $iv = $requestData['iv'] ?? '';
- $encryptedData = $requestData['encryptedData'] ?? '';
- if (empty($iv) || empty($code) || empty($wxInfo) || empty($encryptedData)) {
- return responseMessage(2001, '参数错误');
- }
- $config = config('wechat.mini_program.' . $this->wechatConfigName);
- $miniProgram = Factory::miniProgram($config);
- $info = $miniProgram->auth->session($code);
- $decryptedData = $miniProgram->encryptor->decryptData($info['session_key'], $iv, $encryptedData);
- if (empty($decryptedData)) {
- return responseMessage(2003, '登录失败,请重试!');
- }
- $wxInfo['openid'] = $wx_openid = $decryptedData['openId'] ?? '';
- $wxInfo['unionid'] = $wx_unionid = $decryptedData['unionId'] ?? '';
- if (empty($wx_openid)) {
- return responseMessage(2004, '授权登录失败');
- }
- //根据unionid,openid判断该用户是否已经存在,如果存在则登录跳转
- $flag = false;
- $memberInfo = ES::table($this->memberSetAlias)->where(['wx_openid' => $wx_openid])->first();
- if ($memberInfo) {
- $flag = true;
- } else {
- if ($wx_unionid) {
- $memberInfo = ES::table($this->memberSetAlias)->where(['wx_unionid' => $wx_unionid])->first();
- if ($memberInfo) {
- $flag = true;
- }
- }
- }
- if ($flag) {
- //更新用户登录的openid
- $avatar = $wxInfo['avatar'] ?? $wxInfo['avatarUrl'];
- ES::table($this->memberSetAlias)->updateEntityById($memberInfo['id'], ['wx_unionid' => $wx_unionid, 'wx_openid' => $wx_openid, 'avatar' => $avatar]);
- $loginService = new LoginService($this->siteAliasName);
- $encryptArr = $loginService->setLoginCookie($memberInfo);
- //微信登录的时候,保存的微信接口返回的微信用户信息
- $key = 'weapp:userInfo:' . $encryptArr['token'];
- Cache::put($key, $wxInfo, 7200);
- //微信登录的时候,保存的微信接口返回的微信用户信息
- $key2 = 'weapp:session_key:' . $encryptArr['token'];
- Cache::put($key2, $info, 7200);
- return responseMessage(1001, 'success', $encryptArr);
- } else {
- //微信登录的时候,保存的微信接口返回的微信用户信息
- $key = 'weapp:userInfo:' . $code;
- Cache::put($key, $wxInfo, 7200);
- //微信登录的时候,保存的微信接口返回的微信用户信息
- $key2 = 'weapp:session_key:' . $code;
- Cache::put($key2, $info, 7200);
- return responseMessage(1002, 'success', $code);
- }
- }
- /**
- * 微信小程序绑定手机号
- */
- public function wxBindIn()
- {
- $requestData = Request::all();
- $key = $requestData['key'] ?? '';
- $code = $requestData['code'] ?? '';
- $iv = $requestData['iv'] ?? '';
- $encryptedData = $requestData['encryptedData'] ?? '';
- if (empty($key) || empty($code) || empty($iv) || empty($encryptedData)) {
- return responseMessage(2001, '参数错误');
- }
- //获取微信的信息
- $key2 = 'weapp:userInfo:' . $key;
- $weInfo = Cache::get($key2);
- if (empty($weInfo)) {
- return responseMessage(2003, '微信登录失败,请重试!');
- }
- $key2 = 'weapp:session_key:' . $key;
- $sessionInfo = Cache::get($key2);
- if (empty($sessionInfo)) {
- return responseMessage(2004, '微信登录失败,请重试!');
- }
- $miniProgram = app('wechat.mini_program');
- $decryptedData = $miniProgram->encryptor->decryptData($sessionInfo['session_key'], $iv, $encryptedData);
- if (empty($decryptedData)) {
- return responseMessage(2002, '登录失败,请重试!');
- }
- $mobile = $decryptedData['purePhoneNumber'];
- $openid = $weInfo['openid'] ?? '';
- $token = $this->saveBindAppMember($weInfo, $mobile, $openid);
- if ($token) {
- return responseMessage(1001, 'success', $token);
- } else {
- return responseMessage(2003, '操作失败,请重试!');
- }
- }
- private function saveBindAppMember($weInfo, $mobile, $openid)
- {
- if (isset($weInfo['raw']['unionid']) && $weInfo['raw']['unionid']) {
- $wx_unionid = $weInfo['raw']['unionid'];
- } else {
- $wx_unionid = $weInfo['unionid'] ?? '';
- }
- $username = $weInfo['nickName'] ?? $weInfo['nickname'];
- //保存到数据库
- $data = [
- 'mobile' => $mobile,
- 'wx_username' => $username,
- 'wx_unionid' => $wx_unionid,
- 'avatar' => $weInfo['avatar'] ?? $weInfo['avatarUrl'],
- 'status' => 1,
- 'is_audit' => 0
- ];
- $data['wx_openid'] = $openid;
- // 判断当前的手机号是否存在,如果存在则更新
- $isExist = ES::table($this->memberSetAlias)->where('mobile', $mobile)->where('is_delete', 0)->first();
- if ($isExist) {
- $id = $isExist['id'];
- $is_success = ES::table($this->memberSetAlias)->toRefresh()->updateEntityById($id, $data);
- } else {
- $is_success = ES::table($this->memberSetAlias)->toRefresh()->insertGetId($data);
- $id = $is_success;
- }
- if ($is_success) {
- $memberInfo = ES::table($this->memberSetAlias)->find($id); //设置登录状态
- $loginService = new LoginService($this->siteAliasName);
- return $loginService->setLoginCookie($memberInfo);
- } else {
- return false;
- }
- }
- public function loginOut(Request $request)
- {
- $tokenValue = $this->getToken();
- $loginServer = new LoginService($this->siteAliasName);
- if (empty($tokenValue)) {
- return responseMessage(2001, '操作失败!');
- } else {
- $loginServer->clearLoginInfo($tokenValue);
- return responseMessage(1001, '操作成功!');
- }
- }
- /**
- * 获取小程序的二维码
- *
- * @return String
- * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
- * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
- */
- public function getQrcode()
- {
- $requestData = Request::all();
- $path = $requestData['path'] ?? '';
- if (empty($path)) {
- return responseMessage(2001, '路径不正确');
- }
- // 分享二维码
- $path .= '?share_key=' . base64_encode(($this->memberSetAlias == 'business' ? 1 : 2) . ':' . $this->userId);
- $root_path = public_path('static/upload/store_qrcode/');
- $filename = md5($path) . '.jpg';
- if (file_exists($root_path . '/' . $filename)) {
- return responseMessage(1001, '', '/upload/store_qrcode/' . $filename);
- } else {
- $config = config('wechat.mini_program.' . $this->wechatConfigName);
- $miniProgram = Factory::miniProgram($config);
- $response = $miniProgram->app_code->get($path, [
- 'width' => 430,
- 'auto_color' => false,
- 'line_color' => [
- 'r' => 0,
- 'g' => 0,
- 'b' => 0,
- ],
- ]);
- // 保存小程序码到文件
- if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
- $filename = $response->saveAs($root_path, $filename);
- return responseMessage(1001, '', '/upload/store_qrcode/' . $filename);
- } else {
- return responseMessage(2002, '未知错误');
- }
- }
- }
- }
|