Auth.php 31 KB

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