setWebsite(__NAMESPACE__); $config = config('easywechat.mini_app.default'); try { $this->app = new Application($config); } catch (InvalidArgumentException $e) { } } public function loginIn(): JsonResponse { $sceneStr = Request::post('sceneStr'); // 场景值 $code = Request::post('code'); $wxInfo = Request::post('userInfo'); if (empty($productMid)) { return responseMessage(3000, '参数错误,请重试!'); } if (empty($code) || empty($wxInfo)) { return responseMessage(3001, '参数错误,请重试!'); } $response = $this->app->getClient()->get('/sns/jscode2session', [ 'js_code' => $code, 'grant_type' => 'authorization_code', ]); try { $result = $response->toArray(); if ($result) { // 判断用户是否已经存在 $openid = $result['openid']; $unionid = $result['unionid']; $userInfo = DB::table('user_wechat_mini_program')->where(['openid' => $openid, 'unionid' => $unionid])->first(); if ($userInfo) { // 更新头像和昵称 $data = [ 'nick' => $wxInfo['nickname'], 'wx_avatar' => $wxInfo['avatar'], 'wx_info' => json_encode($wxInfo), ]; $userId = $userInfo->id; $isSuccess = DB::table('user_wechat_mini_program')->where('user_id', $userId)->update($data); } else { // 插入数据 $isSuccess = DB::transaction(function () use ($result, $wxInfo) { $userData = [ 'mid' => Str::random(12), 'username' => $wxInfo['nickname'], 'real_username' => '', 'avatar' => $wxInfo['avatar'], 'roles' => json_encode([]), 'remember_token' => '', 'status' => 1, 'created_at' => time(), 'updated_at' => time(), ]; $userId = DB::table('user')->insertGetId($userData); $data = [ 'mid' => Str::random(12), 'user_id' => $userId, 'openid' => $result['openid'], 'session_key' => $result['session_key'], 'unionid' => $result['unionid'], 'nick' => $wxInfo['nickname'], 'wx_avatar' => $wxInfo['avatar'], 'wx_info' => json_encode($wxInfo), ]; DB::table('user_wechat_mini_program')->insertGetId($data); }); } if ($isSuccess) { // 设置登录的token $loginToken = new LoginTokenService('user_access_token'); if (!in_array($sceneStr, ['web', 'mobile', 'officialAccount', 'miniProgram'])) { $token = $loginToken->createToken($userId, $sceneStr); } else { // 该场景值,可以为软件的mid $isExist = DB::table('product')->where('mid', $sceneStr)->count(); if ($isExist) { $token = $loginToken->createOnlyOneToken($userId, $sceneStr); } else { return responseMessage(3003, '参数错误,请重试!'); } } return responseMessage(1001, '操作成功!', ['token' => $token]); } else { return responseMessage(3002, '操作失败!'); } } } catch (ClientExceptionInterface $e) { } catch (DecodingExceptionInterface $e) { } catch (RedirectionExceptionInterface $e) { } catch (ServerExceptionInterface $e) { } catch (TransportExceptionInterface $e) { } return responseMessage(3004, '操作失败,请重试!'); } }