Auth.php 31 KB

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