Auth.php 32 KB

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