Auth.php 31 KB

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