Auth.php 32 KB

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