Auth.php 31 KB

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