123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492 |
- <?php
- namespace App\Http\Controllers\V1;
- use App\Http\Controllers\Controller;
- use App\Http\Requests\MobileLoginRequest;
- use App\Http\Requests\WeappAuthorizationRequest;
- use App\Http\Requests\WeappUserinfoRequest;
- use App\Maps\CacheMap;
- use App\Models\Area;
- use App\Models\Auth;
- use App\Models\User;
- use App\Models\UserPhoneDetail;
- use App\Repositories\ConfigRepository;
- use App\Repositories\InviteNewUserRepository;
- use App\Repositories\UserRepository;
- use App\Transformers\UserTransformer;
- use Carbon\Carbon;
- use EasyWeChat\Factory;
- use Illuminate\Support\Facades\Cache;
- use Illuminate\Support\Facades\Log;
- use Tymon\JWTAuth\Facades\JWTAuth;
- use Alipay\EasySDK\Kernel\Factory as AliFactory;
- use Alipay\EasySDK\Kernel\Config;
- use Alipay\EasySDK\Kernel\Util\ResponseChecker;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\DB;
- /**
- * 小程序权限认证模块
- * Class AuthController
- * @package App\Http\Controllers\V1
- */
- class AuthController extends Controller
- {
- protected $jwt;
- protected $userRepository;
- /**
- * Create a new controller instance.
- *
- * @return void
- */
- public function __construct(JWTAuth $jwt, UserRepository $userRepository)
- {
- parent::__construct();
- $this->jwt = $jwt;
- $this->userRepository = $userRepository;
- }
- /**
- * 小程序认证
- * @param WeappAuthorizationRequest $request
- * User: Mead
- */
- public function xiaoLogin(WeappAuthorizationRequest $request, ConfigRepository $configRepository, InviteNewUserRepository $inviteNewUserRepository)
- {
- try {
- $code = $request->code;
- $appid = $request->appid;
- $type = (int)$request->get('type', 0); //0微信 1支付宝
- $response = [];
- $invite_user_id = $request->get('invite_user_id') ?? 0;
- switch ($type) {
- case Auth::TYPE_WEAPP: //微信
- if ($appid !== self::$MERCHANT['wxapp_app_id']) {
- return $this->errorBadRequest('app_id is error');
- }
- $miniProgram = Factory::miniProgram(wechat_mini_config(self::$MERCHANT));
- $data = $miniProgram->auth->session($code);
- if (isset($data['errcode'])) {
- $this->response->errorUnauthorized('code 不正确');
- return '';
- }
- $auth = Auth::where([
- ['identifier', '=', $appid],
- ['type', '=', Auth::TYPE_WEAPP]
- ])->where('credential', $data['openid'])->first();
- //注册认证信息
- $attributes['type'] = Auth::TYPE_WEAPP;
- $attributes['credential'] = $data['openid'];
- //授权方式
- $source = 1;
- //response参数
- $response['session_key'] = $data['session_key'];
- //来源
- $laiyuan = User::REGISTER_SOURCE_WEAPP;
- break;
- case Auth::TYPE_ALIPAY://支付宝
- if ($appid !== self::$MERCHANT['alipaymini_appId']) {
- return $this->errorBadRequest('app_id is error');
- }
- try {
- $result = alipay_mini_config(self::$MERCHANT)->base()->oauth()->getToken($code);
- } catch (\Throwable $e) {
- return $this->errorBadRequest('服务异常');
- }
- $responseChecker = new ResponseChecker();
- if (!($responseChecker->success($result))) {
- $this->response->errorBadRequest("调用失败,原因:" . $result->msg . "," . $result->subMsg);
- return '';
- }
- $data = json_decode($result->httpBody, true)['alipay_system_oauth_token_response'];
- $auth = Auth::where([
- ['identifier', '=', $appid],
- ['type', '=', Auth::TYPE_ALIPAY]
- ])->where('credential', $data['user_id'])->first();
- //注册认证信息
- $attributes['type'] = Auth::TYPE_ALIPAY;
- $attributes['credential'] = $data['user_id'];
- //授权方式
- $source = 2;
- //来源
- $laiyuan = User::REGISTER_SOURCE_ALIPAYMINI;
- break;
- default:
- $this->errorBadRequest('登录类型不存在');
- return '';
- }
- $is_auth = true;
- if (!$auth) {
- //注册用户
- $userInfo = $this->userRepository->getRandomUserInfo();
- $userInfo['register_source'] = $laiyuan;
- $userInfo['merchant_id'] = self::$MERCHANT_ID;
- $userInfo['is_new_user_coupons'] = User::IS_NEW_USER_COUPONS_OK;
- $user = User::create($userInfo);
- //添加邀请注册活动
- if ((int)$invite_user_id != 0) {
- $inviteNewUserRepository->create($invite_user_id, $user->id, $source);
- }
- $attributes['identifier'] = $appid;
- $attributes['user_id'] = $user->id;
- $attributes['merchant_id'] = self::$MERCHANT_ID;
- $attributes['is_verified'] = Auth::VERIFIED_OK;
- $auth = Auth::create($attributes);
- $is_auth = false;
- } else {
- $user = $this->userRepository->byIdGetModel($auth->user_id);
- }
- $phone_detail = $request->get('phone_detail') ?? '';
- if (!empty($phone_detail)) {
- $detail = json_decode($phone_detail);
- if (!empty($detail)) {
- UserPhoneDetail::Log($detail, $user->id);
- }
- }
- $token = JWTAuth::fromUser($user);
- // 单机登录限制
- // app()->redis->hset(CacheMap::SINGLE_LOGIN_API, $user->id, $token);
- $response['is_auth'] = $is_auth;
- $response['token'] = 'Bearer ' . $token;
- $response['exp'] = Carbon::now()->addMinute(JWTAuth::factory()->getTTL())->getTimestamp();
- $response['auth_id'] = $auth->id;
- $response['user'] = $is_auth ? $user : [];
- $response['android_mini_version'] = $configRepository->getMiniAndroidVersion();
- $response['ios_mini_version'] = $configRepository->getMiniIosVersion();
- return $this->response->array($response);
- } catch (\Exception $exception) {
- return $this->exception($exception);
- }
- }
- /**
- * mobileLogin 手机号登录
- *
- * @param MobileLoginRequest $request
- * @param ConfigRepository $configRepository
- * @return
- * @author Fx
- *
- */
- public function mobileLogin(MobileLoginRequest $request, ConfigRepository $configRepository)
- {
- try {
- $mobile = $request->get('mobile', null);
- $code = $request->get('code', false);
- $type = (int)$request->get('type', 1);
- $auth_id = (int)$request->get('auth_id', false);
- if (!$auth_id) {
- $auth_id = $this->user->id;
- }
- switch ($type) {
- case 1:
- //微信解析手机号
- $session = $request->get('session_key');
- $iv = $request->get('iv');
- $encryptedData = $request->get('encryptedData');
- $miniProgram = Factory::miniProgram(wechat_mini_config(self::$MERCHANT));
- $decryptedData = $miniProgram->encryptor->decryptData($session, $iv, $encryptedData);
- $mobile = $decryptedData['purePhoneNumber'];
- break;
- case 2:
- //短信验证
- $v_code = Cache::get("verification_code_{$mobile}", '');
- // if (empty($v_code)) {
- // return $this->errorNoValidation('短信验证码已过期');
- // }
- //
- // if ((string)$v_code !== (string)$code) {
- // return $this->errorNoValidation('短信验证码错误');
- // }
- break;
- case 3:
- //支付宝解析手机号
- $shouji = AlipayMiniOpenSign(self::$MERCHANT, $request->get('session_key'));
- if ($shouji['code'] != 10000) {
- $this->errorBadRequest('手机号解析失败');
- };
- $mobile = $shouji['mobile'];
- break;
- default:
- $this->errorBadRequest('获取手机号类型不存在');
- return '';
- }
- if (!$mobile) {
- return $this->errorNoValidation('手机号有误');
- }
- $user = User::query()->where('merchant_id', self::$MERCHANT_ID)->where('mobile', $mobile)->first();
- if (!$user) {
- $user_id = $this->user->id;
- if (!$user_id) {
- return $this->errorNoValidation('找不到该用户');
- }
- //注册手机号
- $this->user->fill([
- 'mobile' => $mobile,
- 'is_bind_mobile' => User::BIND_MOBILE_OK,
- 'nickname' => '闪现-' . rand(100000, 999999),
- 'avatar' => "http://resource.bike.hanyiyun.com/logo.png",
- 'register_area_id' => $request->get('area_id', 0),
- 'register_area' => $request->get('area_id', 0) ? Area::where('id', $request->get('area_id', 0))->value('name') : null
- ]);
- $re = $this->user->save();
- if (!$re) {
- return $this->errorNoValidation('用户保存失败');
- }
- $user = User::query()->where('merchant_id', self::$MERCHANT_ID)->where('id', $user_id)->first();
- }
- // 新用户1-》没找到手机号-》注册-》信息相等 新用户2-》找到新用户1手机号-》已注册-》信息不相等
- $auth = Auth::where('merchant_id', self::$MERCHANT_ID)->where('id', $auth_id)->first();
- if (!$auth) {
- return $this->errorBadRequest('授权有误请重新授权');
- }
- if ($auth->user_id != $user->id) {
- DB::beginTransaction();
- //已经注册过得 更新同一个用户
- $upauth = Auth::where('merchant_id', self::$MERCHANT_ID)->where('id', $auth_id)->update(['user_id' => $user->id]);
- //删除多的user记录
- $userde = User::where('merchant_id', self::$MERCHANT_ID)->where('id', $auth->user_id)->delete();
- if (!$upauth && !$userde) {
- DB::rollBack();
- } else {
- DB::commit();
- }
- }
- $phone_detail = $request->get('phone_detail', false);
- if ($phone_detail) {
- $detail = json_decode($phone_detail);
- if (!empty($detail)) {
- UserPhoneDetail::Log($detail, $user->id);
- }
- }
- $token = JWTAuth::fromUser($user);
- // 单机登录限制
- app()->redis->hset(CacheMap::SINGLE_LOGIN_API, $user->id, $token);
- return $this->response->array([
- 'token' => 'Bearer ' . $token,
- 'exp' => Carbon::now()->addMinute(JWTAuth::factory()->getTTL())->getTimestamp(),
- // 'auth_id' => $auth->id ?? '',
- 'user' => $user,
- 'android_mini_version' => $configRepository->getMiniAndroidVersion(),
- 'ios_mini_version' => $configRepository->getMiniIosVersion(),
- ]);
- } catch (\Exception $exception) {
- return $this->exception($exception);
- }
- }
- /**
- * mobileLogin 手机号登录 正式的时候开启
- *
- * @param MobileLoginRequest $request
- * @param ConfigRepository $configRepository
- * @return
- * @author Fx
- *
- */
- public function mobileLogin_zhengshi(MobileLoginRequest $request, ConfigRepository $configRepository)
- {
- try {
- $mobile = $request->get('mobile', null);
- $code = $request->get('code', false);
- $type = (int)$request->get('type', 1);
- $auth_id = (int)$request->get('auth_id', false);
- if (!$auth_id) {
- $auth_id = $this->user->id;
- }
- switch ($type) {
- case 1:
- //微信解析手机号
- $session = $request->get('session_key');
- $iv = $request->get('iv');
- $encryptedData = $request->get('encryptedData');
- $miniProgram = Factory::miniProgram(wechat_mini_config(self::$MERCHANT));
- $decryptedData = $miniProgram->encryptor->decryptData($session, $iv, $encryptedData);
- $mobile = $decryptedData['purePhoneNumber'];
- break;
- case 2:
- //短信验证
- $v_code = Cache::get("verification_code_{$mobile}", '');
- if (empty($v_code)) {
- return $this->errorNoValidation('短信验证码已过期');
- }
- if ((string)$v_code !== (string)$code) {
- return $this->errorNoValidation('短信验证码错误');
- }
- break;
- case 3:
- //支付宝解析手机号
- $shouji = AlipayMiniOpenSign(self::$MERCHANT, $request->get('session_key'));
- if ($shouji['code'] != 10000) {
- $this->errorBadRequest('手机号解析失败');
- };
- $mobile = $shouji['mobile'];
- break;
- default:
- $this->errorBadRequest('获取手机号类型不存在');
- return '';
- }
- if (!$mobile) {
- return $this->errorNoValidation('手机号有误');
- }
- $user = User::query()->where('merchant_id', self::$MERCHANT_ID)->where('mobile', $mobile)->first();
- if (!$user) {
- $user_id = $this->user()->id;
- if (!$user_id) {
- return $this->errorNoValidation('找不到该用户');
- }
- //注册手机号
- $this->user->fill([
- 'mobile' => $mobile,
- 'is_bind_mobile' => User::BIND_MOBILE_OK,
- 'nickname' => '闪现-' . rand(100000, 999999),
- 'avatar' => "http://resource.bike.hanyiyun.com/logo.png",
- 'register_area_id' => $request->get('area_id', 0),
- 'register_area' => $request->get('area_id', 0) ? Area::where('id', $request->get('area_id', 0))->value('name') : null
- ]);
- $re = $this->user->save();
- if (!$re) {
- return $this->errorNoValidation('用户保存失败');
- }
- $user = User::query()->where('merchant_id', self::$MERCHANT_ID)->where('id', $user_id)->first();
- }
- // 新用户1-》没找到手机号-》注册-》信息相等 新用户2-》找到新用户1手机号-》已注册-》信息不相等
- $auth = Auth::where('merchant_id', self::$MERCHANT_ID)->where('id', $auth_id)->first();
- if (!$auth) {
- return $this->errorBadRequest('授权有误请重新授权');
- }
- if ($auth->user_id != $user->id) {
- DB::beginTransaction();
- //已经注册过得 更新同一个用户
- $upauth = Auth::where('merchant_id', self::$MERCHANT_ID)->where('id', $auth_id)->update(['user_id' => $user->id]);
- //删除多的user记录
- $userde = User::where('merchant_id', self::$MERCHANT_ID)->where('id', $auth->user_id)->delete();
- if (!$upauth && !$userde) {
- DB::rollBack();
- } else {
- DB::commit();
- }
- }
- $phone_detail = $request->get('phone_detail', false);
- if ($phone_detail) {
- $detail = json_decode($phone_detail);
- if (!empty($detail)) {
- UserPhoneDetail::Log($detail, $user->id);
- }
- }
- $token = JWTAuth::fromUser($user);
- // 单机登录限制
- app()->redis->hset(CacheMap::SINGLE_LOGIN_API, $user->id, $token);
- return $this->response->array([
- 'token' => 'Bearer ' . $token,
- 'exp' => Carbon::now()->addMinute(JWTAuth::factory()->getTTL())->getTimestamp(),
- // 'auth_id' => $auth->id ?? '',
- 'user' => $user,
- 'android_mini_version' => $configRepository->getMiniAndroidVersion(),
- 'ios_mini_version' => $configRepository->getMiniIosVersion(),
- ]);
- } catch (\Exception $exception) {
- return $this->exception($exception);
- }
- }
- /**
- * 更新用户基本信息
- * User: Mead
- */
- public function weappUserInfoSync(WeappUserinfoRequest $request)
- {
- try {
- $this->user->fill([
- 'nickname' => $request->get('nickName'),
- 'gender' => $request->get('gender', 0),
- 'country' => $request->get('country', 'China'),
- 'province' => $request->get('province', 'Henan'),
- 'city' => $request->get('city', 'Zhengzhou'),
- 'avatar' => $request->get('avatarUrl', 'http://resource.bike.hanyiyun.com/logo.png') ?? "http://resource.bike.hanyiyun.com/logo.png",
- 'language' => $request->get('language', 'zh_CN'),
- 'register_area_id' => $request->get('area_id', 0),
- 'register_area' => $request->get('area_id', 0) ? Area::where('id', $request->get('area_id', 0))->value('name') : '',
- 'is_register' => User::REGISTER_OK
- ]);
- $this->user->save();
- return $this->response->item($this->user, UserTransformer::class);
- } catch (\Exception $exception) {
- return $this->exception($exception);
- }
- }
- /**
- * 获取当前登录用户
- * @return
- * User: Mead
- */
- public function loginUser()
- {
- try {
- return $this->response->item($this->user, UserTransformer::class);
- } catch (\Exception $exception) {
- return $this->exception($exception);
- }
- }
- }
|