Auth.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2022 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\controller\api;
  12. use app\common\repositories\store\order\StoreOrderRepository;
  13. use app\common\repositories\store\order\StoreRefundOrderRepository;
  14. use app\common\repositories\system\notice\SystemNoticeConfigRepository;
  15. use app\common\repositories\user\UserRepository;
  16. use app\common\repositories\user\UserSignRepository;
  17. use app\common\repositories\wechat\RoutineQrcodeRepository;
  18. use app\common\repositories\wechat\WechatUserRepository;
  19. use app\validate\api\ChangePasswordValidate;
  20. use app\validate\api\UserAuthValidate;
  21. use crmeb\basic\BaseController;
  22. use crmeb\services\MiniProgramService;
  23. use crmeb\services\SmsService;
  24. use crmeb\services\WechatService;
  25. use crmeb\services\WechatTemplateMessageService;
  26. use Exception;
  27. use Firebase\JWT\JWT;
  28. use Gregwar\Captcha\CaptchaBuilder;
  29. use Gregwar\Captcha\PhraseBuilder;
  30. use Overtrue\Socialite\AccessToken;
  31. use Symfony\Component\HttpFoundation\Request;
  32. use think\db\exception\DataNotFoundException;
  33. use think\db\exception\DbException;
  34. use think\db\exception\ModelNotFoundException;
  35. use think\exception\ValidateException;
  36. use think\facade\Cache;
  37. use think\facade\Log;
  38. use think\facade\Queue;
  39. use crmeb\jobs\SendSmsJob;
  40. /**
  41. * Class Auth
  42. * @package app\controller\api
  43. * @author xaboy
  44. * @day 2020-05-06
  45. */
  46. class Auth extends BaseController
  47. {
  48. public function test()
  49. {
  50. // $data = [
  51. // 'tempId' => '',
  52. // 'id' => '',
  53. // ];
  54. // Queue::push(SendSmsJob::class,$data);
  55. // $status = app()->make(SystemNoticeConfigRepository::class)->getNoticeStatusByConstKey($data['tempId']);
  56. // if ($status['notice_sms'] == 1) {
  57. // SmsService::sendMessage($data);
  58. // }
  59. // if ($status['notice_wechat'] == 1) {
  60. // app()->make(WechatTemplateMessageService::class)->sendTemplate($data);
  61. // }
  62. // if ($status['notice_routine'] == 1) {
  63. // app()->make(WechatTemplateMessageService::class)->subscribeSendTemplate($data);
  64. // }
  65. }
  66. /**
  67. * @param UserRepository $repository
  68. * @return mixed
  69. * @throws DbException
  70. * @author xaboy
  71. * @day 2020/6/1
  72. */
  73. public function login(UserRepository $repository)
  74. {
  75. $account = $this->request->param('account');
  76. $auth_token = $this->request->param('auth_token');
  77. if (Cache::get('api_login_freeze_' . $account))
  78. return app('json')->fail('账号或密码错误次数太多,请稍后在尝试');
  79. if (!$account)
  80. return app('json')->fail('请输入账号');
  81. $user = $repository->accountByUser($this->request->param('account'));
  82. // if($auth_token && $user){
  83. // return app('json')->fail('用户已存在');
  84. // }
  85. if (!$user) $this->loginFailure($account);
  86. if (!password_verify($pwd = (string)$this->request->param('password'), $user['pwd'])) $this->loginFailure($account);
  87. $auth = $this->parseAuthToken($auth_token);
  88. if ($auth && !$user['wechat_user_id']) {
  89. $repository->syncBaseAuth($auth, $user);
  90. }
  91. $user = $repository->mainUser($user);
  92. $pid = $this->request->param('spread', 0);
  93. $repository->bindSpread($user, intval($pid));
  94. $tokenInfo = $repository->createToken($user);
  95. $repository->loginAfter($user);
  96. return app('json')->success($repository->returnToken($user, $tokenInfo));
  97. }
  98. /**
  99. * TODO 登录尝试次数限制
  100. * @param $account
  101. * @param int $number
  102. * @param int $n
  103. * @author Qinii
  104. * @day 7/6/21
  105. */
  106. public function loginFailure($account, $number = 5, $n = 3)
  107. {
  108. $key = 'api_login_failuree_' . $account;
  109. $numb = Cache::get($key) ?? 0;
  110. $numb++;
  111. if ($numb >= $number) {
  112. $fail_key = 'api_login_freeze_' . $account;
  113. Cache::set($fail_key, 1, 15 * 60);
  114. throw new ValidateException('账号或密码错误次数太多,请稍后在尝试');
  115. } else {
  116. Cache::set($key, $numb, 5 * 60);
  117. $msg = '账号或密码错误';
  118. $_n = $number - $numb;
  119. if ($_n <= $n) {
  120. $msg .= ',还可尝试' . $_n . '次';
  121. }
  122. throw new ValidateException($msg);
  123. }
  124. }
  125. /**
  126. * @return mixed
  127. * @author xaboy
  128. * @day 2020/6/1
  129. */
  130. public function userInfo()
  131. {
  132. $user = $this->request->userInfo()->hidden(['label_id', 'group_id', 'pwd', 'addres', 'card_id', 'last_time', 'last_ip', 'create_time', 'mark', 'status', 'spread_uid', 'spread_time', 'real_name', 'birthday', 'brokerage_price']);
  133. $user->append(['service', 'topService', 'total_collect_product', 'total_collect_store', 'total_coupon', 'total_visit_product', 'total_unread', 'total_recharge', 'lock_integral', 'total_integral']);
  134. $data = $user->toArray();
  135. $data['total_consume'] = $user['pay_price'];
  136. $data['extension_status'] = systemConfig('extension_status');
  137. if (systemConfig('member_status'))
  138. $data['member_icon'] = $this->request->userInfo()->member->brokerage_icon ?? '';
  139. if ($data['is_svip'] == 3)
  140. $data['svip_endtime'] = date('Y-m-d H:i:s',strtotime("+100 year"));
  141. $day = date('Y-m-d',time());
  142. $key = 'sign_'.$user['uid'].'_'.$day;
  143. $data['sign_status'] = false;
  144. if (Cache::get($key)) {
  145. $data['sign_status'] = true;
  146. } else {
  147. $nu = app()->make(UserSignRepository::class)->getSign($user->uid,$day);
  148. if ($nu) {
  149. $data['sign_status'] = true;
  150. Cache::set($key,true, new \DateTime($day.' 23:59:59'));
  151. }
  152. }
  153. return app('json')->success($data);
  154. }
  155. /**
  156. * @param UserRepository $repository
  157. * @return mixed
  158. * @author xaboy
  159. * @day 2020/6/1
  160. */
  161. public function logout(UserRepository $repository)
  162. {
  163. $repository->clearToken($this->request->token());
  164. return app('json')->success('退出登录');
  165. }
  166. /**
  167. * @return mixed
  168. * @throws DataNotFoundException
  169. * @throws DbException
  170. * @throws ModelNotFoundException
  171. * @author xaboy
  172. * @day 2020-05-11
  173. */
  174. public function auth()
  175. {
  176. if (systemConfig('is_phone_login') === '1') {
  177. return app('json')->fail('请绑定手机号');
  178. }
  179. $request = $this->request;
  180. $oauth = WechatService::create()->getApplication()->oauth;
  181. $oauth->setRequest(new Request($request->get(), $request->post(), [], [], [], $request->server(), $request->getContent()));
  182. try {
  183. $wechatInfo = $oauth->user()->getOriginal();
  184. } catch (Exception $e) {
  185. return app('json')->fail('授权失败[001]', ['message' => $e->getMessage()]);
  186. }
  187. if (!isset($wechatInfo['nickname'])) {
  188. return app('json')->fail('授权失败[002]');
  189. }
  190. /** @var WechatUserRepository $make */
  191. $make = app()->make(WechatUserRepository::class);
  192. $user = $make->syncUser($wechatInfo['openid'], $wechatInfo);
  193. if (!$user)
  194. return app('json')->fail('授权失败[003]');
  195. /** @var UserRepository $make */
  196. $userRepository = app()->make(UserRepository::class);
  197. $user[1] = $userRepository->mainUser($user[1]);
  198. $pid = $this->request->param('spread', 0);
  199. $userRepository->bindSpread($user[1], intval($pid));
  200. $tokenInfo = $userRepository->createToken($user[1]);
  201. $userRepository->loginAfter($user[1]);
  202. return app('json')->success($userRepository->returnToken($user[1], $tokenInfo));
  203. }
  204. /**
  205. * @return mixed
  206. * @throws DataNotFoundException
  207. * @throws DbException
  208. * @throws ModelNotFoundException
  209. * @author xaboy
  210. * @day 2020-05-11
  211. */
  212. public function mpAuth()
  213. {
  214. list($code, $post_cache_key) = $this->request->params([
  215. 'code',
  216. 'cache_key',
  217. ], true);
  218. if (systemConfig('is_phone_login') === '1') {
  219. return app('json')->fail('请绑定手机号');
  220. }
  221. $userInfoCong = Cache::get('eb_api_code_' . $code);
  222. if (!$code && !$userInfoCong)
  223. return app('json')->fail('授权失败,参数有误');
  224. $miniProgramService = MiniProgramService::create();
  225. if ($code && !$userInfoCong) {
  226. try {
  227. $userInfoCong = $miniProgramService->getUserInfo($code);
  228. Cache::set('eb_api_code_' . $code, $userInfoCong, 86400);
  229. } catch (Exception $e) {
  230. return app('json')->fail('获取session_key失败,请检查您的配置!', ['line' => $e->getLine(), 'message' => $e->getMessage()]);
  231. }
  232. }
  233. $data = $this->request->params([
  234. ['spread_spid', 0],
  235. ['spread_code', ''],
  236. ['iv', ''],
  237. ['encryptedData', ''],
  238. ]);
  239. try {
  240. //解密获取用户信息
  241. $userInfo = $miniProgramService->encryptor($userInfoCong['session_key'], $data['iv'], $data['encryptedData']);
  242. } catch (Exception $e) {
  243. if ($e->getCode() == '-41003') return app('json')->fail('获取会话密匙失败');
  244. throw $e;
  245. }
  246. if (!$userInfo) return app('json')->fail('openid获取失败');
  247. if (!isset($userInfo['openId'])) $userInfo['openId'] = $userInfoCong['openid'] ?? '';
  248. $userInfo['unionId'] = $userInfoCong['unionid'] ?? $userInfo['unionId'] ?? '';
  249. if (!$userInfo['openId']) return app('json')->fail('openid获取失败');
  250. /** @var WechatUserRepository $make */
  251. $make = app()->make(WechatUserRepository::class);
  252. $user = $make->syncRoutineUser($userInfo['openId'], $userInfo);
  253. if (!$user)
  254. return app('json')->fail('授权失败');
  255. /** @var UserRepository $make */
  256. $userRepository = app()->make(UserRepository::class);
  257. $user[1] = $userRepository->mainUser($user[1]);
  258. $code = intval($data['spread_code']['id'] ?? $data['spread_code']);
  259. //获取是否有扫码进小程序
  260. if ($code && ($info = app()->make(RoutineQrcodeRepository::class)->getRoutineQrcodeFindType($code))) {
  261. $data['spread_spid'] = $info['third_id'];
  262. }
  263. $userRepository->bindSpread($user[1], intval($data['spread_spid']));
  264. $tokenInfo = $userRepository->createToken($user[1]);
  265. $userRepository->loginAfter($user[1]);
  266. return app('json')->success($userRepository->returnToken($user[1], $tokenInfo));
  267. }
  268. public function getCaptcha()
  269. {
  270. $codeBuilder = new CaptchaBuilder(null, new PhraseBuilder(4));
  271. $key = uniqid(microtime(true), true);
  272. Cache::set('api_captche' . $key, $codeBuilder->getPhrase(), 300);
  273. $captcha = $codeBuilder->build()->inline();
  274. return app('json')->success(compact('key', 'captcha'));
  275. }
  276. protected function checkCaptcha($uni, string $code): bool
  277. {
  278. $cacheName = 'api_captche' . $uni;
  279. if (!Cache::has($cacheName)) return false;
  280. $key = Cache::get($cacheName);
  281. $res = strtolower($key) == strtolower($code);
  282. if ($res) Cache::delete($cacheName);
  283. return $res;
  284. }
  285. public function verify(UserAuthValidate $validate)
  286. {
  287. $data = $this->request->params(['phone', ['type', 'login'],['captchaType', ''], ['captchaVerification', ''],'token']);
  288. //二次验证
  289. try {
  290. aj_captcha_check_two($data['captchaType'], $data['captchaVerification']);
  291. } catch (\Throwable $e) {
  292. return app('json')->fail($e->getMessage());
  293. }
  294. $validate->sceneVerify()->check($data);
  295. $sms_limit_key = 'sms_limit_' . $data['phone'];
  296. $limit = Cache::get($sms_limit_key) ? Cache::get($sms_limit_key) : 0;
  297. $sms_limit = systemConfig('sms_limit');
  298. if ($sms_limit && $limit > $sms_limit) {
  299. return app('json')->fail('请求太频繁请稍后再试');
  300. }
  301. // if(!env('APP_DEBUG', false)){
  302. try {
  303. $sms_code = str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT);
  304. $sms_time = systemConfig('sms_time') ? systemConfig('sms_time') : 30;
  305. SmsService::create()->send($data['phone'], 'VERIFICATION_CODE', ['code' => $sms_code, 'time' => $sms_time]);
  306. } catch (Exception $e) {
  307. return app('json')->fail($e->getMessage());
  308. }
  309. // }else{
  310. // $sms_code = 1234;
  311. // $sms_time = 5;
  312. // }
  313. $sms_key = app()->make(SmsService::class)->sendSmsKey($data['phone'], $data['type']);
  314. Cache::set($sms_key, $sms_code, $sms_time * 60);
  315. Cache::set($sms_limit_key, $limit + 1, 60);
  316. //'短信发送成功'
  317. return app('json')->success('短信发送成功');
  318. }
  319. public function smsLogin(UserAuthValidate $validate, UserRepository $repository)
  320. {
  321. $data = $this->request->params(['phone', 'sms_code', 'spread', 'auth_token',['user_type','h5']]);
  322. $validate->sceneSmslogin()->check($data);
  323. $sms_code = app()->make(SmsService::class)->checkSmsCode($data['phone'], $data['sms_code'], 'login');
  324. if (!$sms_code) return app('json')->fail('验证码不正确');
  325. $user = $repository->accountByUser($data['phone']);
  326. $auth = $this->parseAuthToken($data['auth_token']);
  327. if (!$user) $user = $repository->registr($data['phone'], null, $data['user_type']);
  328. if ($auth && !$user['wechat_user_id']){
  329. $repository->syncBaseAuth($auth, $user);
  330. }
  331. $user = $repository->mainUser($user);
  332. $repository->bindSpread($user, intval($data['spread']));
  333. $tokenInfo = $repository->createToken($user);
  334. $repository->loginAfter($user);
  335. return app('json')->success($repository->returnToken($user, $tokenInfo));
  336. }
  337. public function changePassword(ChangePasswordValidate $validate, UserRepository $repository)
  338. {
  339. $data = $this->request->params(['phone', 'sms_code', 'pwd']);
  340. $validate->check($data);
  341. $user = $repository->accountByUser($data['phone']);
  342. if (!$user) return app('json')->fail('用户不存在');
  343. $sms_code = app()->make(SmsService::class)->checkSmsCode($data['phone'], $data['sms_code'], 'change_pwd');
  344. if (!$sms_code)
  345. return app('json')->fail('验证码不正确');
  346. $user->pwd = $repository->encodePassword($data['pwd']);
  347. $user->save();
  348. return app('json')->success('修改成功');
  349. }
  350. public function spread(UserRepository $userRepository)
  351. {
  352. $data = $this->request->params([
  353. ['spread_spid', 0],
  354. ['spread_code', null],
  355. ]);
  356. if (isset($data['spread_code']['id']) && ($info = app()->make(RoutineQrcodeRepository::class)->getRoutineQrcodeFindType($data['spread_code']['id']))) {
  357. $data['spread_spid'] = $info['third_id'];
  358. }
  359. $userRepository->bindSpread($this->request->userInfo(), intval($data['spread_spid']));
  360. return app('json')->success();
  361. }
  362. /**
  363. * TODO 注册账号
  364. * @param UserAuthValidate $validate
  365. * @param UserRepository $repository
  366. * @return \think\response\Json
  367. * @author Qinii
  368. * @day 5/27/21
  369. */
  370. public function register(UserAuthValidate $validate, UserRepository $repository)
  371. {
  372. $data = $this->request->params(['phone', 'sms_code', 'spread', 'pwd', 'auth_token',['user_type','h5']]);
  373. $validate->check($data);
  374. $sms_code = app()->make(SmsService::class)->checkSmsCode($data['phone'], $data['sms_code'], 'login');
  375. if (!$sms_code)
  376. return app('json')->fail('验证码不正确');
  377. $user = $repository->accountByUser($data['phone']);
  378. if ($user) return app('json')->fail('用户已存在');
  379. $auth = $this->parseAuthToken($data['auth_token']);
  380. $user = $repository->registr($data['phone'], $data['pwd'], $data['user_type']);
  381. if ($auth){
  382. $repository->syncBaseAuth($auth, $user);
  383. }
  384. $user = $repository->mainUser($user);
  385. $repository->bindSpread($user, intval($data['spread']));
  386. $tokenInfo = $repository->createToken($user);
  387. $repository->loginAfter($user);
  388. return app('json')->success($repository->returnToken($user, $tokenInfo));
  389. }
  390. private function parseAuthToken($authToken)
  391. {
  392. $auth = Cache::get('u_try' . $authToken);
  393. $auth && Cache::delete('u_try' . $authToken);
  394. return $auth;
  395. }
  396. private function authInfo($auth, $createUser = false)
  397. {
  398. if (!in_array($auth['type'] ?? '', ['wechat', 'routine', 'apple', 'app_wechat']) || !isset($auth['auth']))
  399. throw new ValidateException('授权信息类型有误');
  400. $data = $auth['auth'];
  401. if ($auth['type'] === 'routine') {
  402. $code = $data['code'] ?? '';
  403. $userInfoCong = Cache::get('eb_api_code_' . $code);
  404. if (!$code && !$userInfoCong)
  405. throw new ValidateException('授权失败,参数有误');
  406. $miniProgramService = MiniProgramService::create();
  407. if ($code && !$userInfoCong) {
  408. try {
  409. $userInfoCong = $miniProgramService->getUserInfo($code);
  410. Cache::set('eb_api_code_' . $code, $userInfoCong, 86400);
  411. } catch (Exception $e) {
  412. throw new ValidateException('获取session_key失败,请检查您的配置!');
  413. }
  414. }
  415. try {
  416. //解密获取用户信息
  417. $userInfo = $miniProgramService->encryptor($userInfoCong['session_key'], $data['iv'], $data['encryptedData']);
  418. } catch (Exception $e) {
  419. if ($e->getCode() == '-41003') throw new ValidateException('获取会话密匙失败');
  420. throw $e;
  421. }
  422. if (!$userInfo) throw new ValidateException('openid获取失败');
  423. if (!isset($userInfo['openId'])) $userInfo['openId'] = $userInfoCong['openid'] ?? '';
  424. $userInfo['unionId'] = $userInfoCong['unionid'] ?? $userInfo['unionId'] ?? '';
  425. if (!$userInfo['openId']) throw new ValidateException('openid获取失败');
  426. /** @var WechatUserRepository $make */
  427. $make = app()->make(WechatUserRepository::class);
  428. $user = $make->syncRoutineUser($userInfo['openId'], $userInfo, $createUser);
  429. if (!$user)
  430. throw new ValidateException('授权失败');
  431. return $user;
  432. } else if ($auth['type'] === 'wechat') {
  433. $request = $this->request;
  434. $oauth = WechatService::create()->getApplication()->oauth;
  435. $oauth->setRequest(new Request($data, $data, [], [], [], $request->server(), $request->getContent()));
  436. try {
  437. $wechatInfo = $oauth->user()->getOriginal();
  438. } catch (Exception $e) {
  439. throw new ValidateException('授权失败[001]');
  440. }
  441. if (!isset($wechatInfo['nickname'])) {
  442. throw new ValidateException('授权失败[002]');
  443. }
  444. /** @var WechatUserRepository $make */
  445. $make = app()->make(WechatUserRepository::class);
  446. $user = $make->syncUser($wechatInfo['openid'], $wechatInfo, false, $createUser);
  447. if (!$user)
  448. throw new ValidateException('授权失败[003]');
  449. return $user;
  450. } else if ($auth['type'] === 'app_wechat') {
  451. $oauth = WechatService::create()->getApplication()->oauth;
  452. try {
  453. $wechatInfo = $oauth->user(new AccessToken(['access_token'=>$data['code'],'openid'=>$data['openid']]))->getOriginal();
  454. } catch (Exception $e) {
  455. throw new ValidateException('授权失败[001]'.$e->getMessage());
  456. }
  457. $user = app()->make(WechatUserRepository::class)->syncAppUser($wechatInfo['unionid'], $wechatInfo, 'App', $createUser);
  458. if (!$user)
  459. throw new ValidateException('授权失败');
  460. return $user;
  461. } else if ($auth['type'] === 'apple') {
  462. $identityToken = $data['userInfo']['identityToken'];
  463. $tks = explode('.', $identityToken);
  464. if (count($tks) != 3) {
  465. throw new ValidateException('Wrong number of segments');
  466. }
  467. list($headb64, $bodyb64, $cryptob64) = $tks;
  468. if (null === ($payload = JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64)))) {
  469. throw new ValidateException('Invalid header encoding');
  470. }
  471. if($payload->sub != $data['openId']){
  472. throw new ValidateException('授权失败');
  473. }
  474. $user = app()->make(WechatUserRepository::class)->syncAppUser($data['openId'], [
  475. 'nickName' => (string)$data['nickname'] ?: '用户' . strtoupper(substr(md5(time()), 0, 12))
  476. ], 'App', $createUser);
  477. if (!$user)
  478. throw new ValidateException('授权失败');
  479. return $user;
  480. }
  481. }
  482. public function authLogin()
  483. {
  484. $auth = $this->request->param('auth');
  485. $users = $this->authInfo($auth, systemConfig('is_phone_login') !== '1');
  486. if (!$users)
  487. return app('json')->fail('授权失败');
  488. $authInfo = $users[0];
  489. $userRepository = app()->make(UserRepository::class);
  490. $user = $users[1] ?? $userRepository->wechatUserIdBytUser($authInfo['wechat_user_id']);
  491. $code = (int)($auth['auth']['spread_code']['id'] ?? $auth['auth']['spread_code'] ?? '');
  492. //获取是否有扫码进小程序
  493. if ($code && ($info = app()->make(RoutineQrcodeRepository::class)->getRoutineQrcodeFindType($code))) {
  494. $auth['auth']['spread'] = $info['third_id'];
  495. }
  496. if (!$user) {
  497. $uni = uniqid(true, false) . random_int(1, 100000000);
  498. $key = 'U' . md5(time() . $uni);
  499. Cache::set('u_try' . $key, ['id' => $authInfo['wechat_user_id'], 'type' => $authInfo['user_type'], 'spread' => $auth['auth']['spread'] ?? 0], 3600);
  500. return app('json')->status(201, compact('key'));
  501. }
  502. if ($auth['auth']['spread'] ?? 0) {
  503. $userRepository->bindSpread($user, (int)($auth['auth']['spread']));
  504. }
  505. $tokenInfo = $userRepository->createToken($user);
  506. $userRepository->loginAfter($user);
  507. return app('json')->status(200, $userRepository->returnToken($user, $tokenInfo));
  508. }
  509. /**
  510. * App微信登陆
  511. * @param Request $request
  512. * @return mixed
  513. */
  514. public function appAuth()
  515. {
  516. $data = $this->request->params(['userInfo']);
  517. if (systemConfig('is_phone_login') === '1') {
  518. return app('json')->fail('请绑定手机号');
  519. }
  520. $user = app()->make(WechatUserRepository::class)->syncAppUser($data['userInfo']['unionId'], $data['userInfo']);
  521. if (!$user)
  522. return app('json')->fail('授权失败');
  523. /** @var UserRepository $make */
  524. $userRepository = app()->make(UserRepository::class);
  525. $user[1] = $userRepository->mainUser($user[1]);
  526. $tokenInfo = $userRepository->createToken($user[1]);
  527. $userRepository->loginAfter($user[1]);
  528. return app('json')->success($userRepository->returnToken($user[1], $tokenInfo));
  529. }
  530. public function getMerCertificate($merId)
  531. {
  532. $merId = (int)$merId;
  533. $data = $this->request->params(['key', 'code']);
  534. if (!$this->checkCaptcha($data['key'], $data['code']))
  535. return app('json')->fail('验证码输入有误');
  536. $certificate = merchantConfig($merId, 'mer_certificate') ?: [];
  537. if (!count($certificate))
  538. return app('json')->fail('该商户未上传证书');
  539. return app('json')->success($certificate);
  540. }
  541. public function appleAuth()
  542. {
  543. $data = $this->request->params(['openId', 'nickname']);
  544. if (systemConfig('is_phone_login') === '1') {
  545. return app('json')->fail('请绑定手机号');
  546. }
  547. $user = app()->make(WechatUserRepository::class)->syncAppUser($data['openId'], [
  548. 'nickName' => (string)$data['nickname'] ?: '用户' . strtoupper(substr(md5(time()), 0, 12))
  549. ], 'apple');
  550. if (!$user)
  551. return app('json')->fail('授权失败');
  552. /** @var UserRepository $make */
  553. $userRepository = app()->make(UserRepository::class);
  554. $user[1] = $userRepository->mainUser($user[1]);
  555. $tokenInfo = $userRepository->createToken($user[1]);
  556. $userRepository->loginAfter($user[1]);
  557. return app('json')->success($userRepository->returnToken($user[1], $tokenInfo));
  558. }
  559. /**
  560. * 注销账号
  561. */
  562. public function cancel()
  563. {
  564. $userRepository = app()->make(UserRepository::class);
  565. $user = $this->request->userInfo();
  566. $order = app()->make(StoreOrderRepository::class)->search(['uid' => $user['uid'], 'paid' => 1])->where('StoreOrder.status', 0)->count();
  567. $refund = app()->make(StoreRefundOrderRepository::class)->search(['uid' => $user['uid'], 'type' => 1])->count();
  568. $key = $this->request->param('key');
  569. $flag = false;
  570. if ($user->now_money > 0 || $user->integral > 0 || $order > 0 || $refund > 0) {
  571. $flag = true;
  572. if (!$key) {
  573. $uni = uniqid(true, false) . random_int(1, 100000000);
  574. $key = 'L' . md5(time() . $uni);
  575. Cache::set('u_out' . $user['uid'], $key, 600);
  576. return app('json')->status(201, '该账号下有未完成业务,注销后不可恢复,您确定继续注销?', compact('key'));
  577. }
  578. }
  579. if ($flag && (!$key || (Cache::get('u_out' . $user['uid']) != $key))) {
  580. return app('json')->fail('操作超时');
  581. }
  582. $userRepository->cancel($user);
  583. $userRepository->clearToken($user);
  584. return app('json')->status(200, '注销成功');
  585. }
  586. public function mpPhone()
  587. {
  588. $code = $this->request->param('code');
  589. $auth_token = $this->request->param('auth_token');
  590. $iv = $this->request->param('iv');
  591. $encryptedData = $this->request->param('encryptedData');
  592. $miniProgramService = MiniProgramService::create();
  593. $userInfoCong = Cache::get('eb_api_code_' . $code);
  594. if (!$code && !$userInfoCong)
  595. throw new ValidateException('授权失败,参数有误');
  596. if ($code && !$userInfoCong) {
  597. try {
  598. $userInfoCong = $miniProgramService->getUserInfo($code);
  599. Cache::set('eb_api_code_' . $code, $userInfoCong, 86400);
  600. } catch (Exception $e) {
  601. throw new ValidateException('获取session_key失败,请检查您的配置!');
  602. }
  603. }
  604. $session_key = $userInfoCong['session_key'];
  605. $data = $miniProgramService->encryptor($session_key, $iv, $encryptedData);
  606. $userRepository = app()->make(UserRepository::class);
  607. $phone = $data['purePhoneNumber'];
  608. $user = $userRepository->accountByUser($phone);
  609. // if($user && $auth_token){
  610. // return app('json')->fail('用户已存在');
  611. // }
  612. $auth = $this->parseAuthToken($auth_token);
  613. if ($user && $auth) {
  614. $userRepository->syncBaseAuth($auth, $user);
  615. } else if (!$user) {
  616. if (!$auth) {
  617. return app('json')->fail('操作超时');
  618. }
  619. $wechatUser = app()->make(WechatUserRepository::class)->get($auth['id']);
  620. $user = $userRepository->syncWechatUser($wechatUser, 'routine');
  621. $user->phone = $phone;
  622. $user->account = $phone;
  623. $user->save();
  624. if ($auth['spread']) {
  625. $userRepository->bindSpread($user, $auth['spread']);
  626. }
  627. }
  628. $tokenInfo = $userRepository->createToken($user);
  629. $userRepository->loginAfter($user);
  630. return app('json')->success($userRepository->returnToken($user, $tokenInfo));
  631. }
  632. /**
  633. * @return mixed
  634. */
  635. public function ajcaptcha()
  636. {
  637. $captchaType = $this->request->get('captchaType');
  638. if (!$captchaType) return app('json')->fail('请输入类型');
  639. return app('json')->success(aj_captcha_create($captchaType));
  640. }
  641. /**
  642. * 一次验证
  643. * @return mixed
  644. */
  645. public function ajcheck()
  646. {
  647. $token = $this->request->param('token','');
  648. $pointJson = $this->request->param('pointJson','');
  649. $captchaType = $this->request->param('captchaType','');
  650. try {
  651. aj_captcha_check_one($captchaType, $token, $pointJson);
  652. return app('json')->success();
  653. } catch (\Throwable $e) {
  654. return app('json')->fail(400336);
  655. }
  656. }
  657. }