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