Auth.php 32 KB

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