Auth.php 30 KB

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