Auth.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  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. $GiftLevel = app()->make(GiftLevel::class);
  193. $group_users = $GiftLevel->get_group_user($user['uid']);
  194. $achievement1 = StoreOrder::where('uid','in', $group_users)->where('paid', 1)->where('product_type',2)->whereNotIn('status',-1)->sum('pay_price');
  195. $achievement2 = StoreOrder::where('uid', $user['uid'])->where('paid', 1)->where('product_type',2)->whereNotIn('status',-1)->sum('pay_price');
  196. $gift_performance = bcadd($achievement1, $achievement2, 2);
  197. if ($gift_performance>0){
  198. $data['gift_performance'] = $gift_performance;
  199. }
  200. $achievement1 = StoreOrder::where('uid', 'in',$group_users)->where('paid', 1)->where('product_type',1)->whereNotIn('status',-1)->sum('pay_price');
  201. $achievement2 = StoreOrder::where('uid', $user['uid'])->where('paid', 1)->where('product_type',1)->whereNotIn('status',-1)->sum('pay_price');
  202. $oil_performance = bcadd($achievement1, $achievement2, 2);
  203. if ($oil_performance>0){
  204. $data['oil_performance'] = $oil_performance;
  205. }
  206. return app('json')->success($data);
  207. }
  208. /**
  209. * @param UserRepository $repository
  210. * @return mixed
  211. * @author xaboy
  212. * @day 2020/6/1
  213. */
  214. public function logout(UserRepository $repository)
  215. {
  216. $repository->clearToken($this->request->token());
  217. return app('json')->success('退出登录');
  218. }
  219. /**
  220. * @return mixed
  221. * @throws DataNotFoundException
  222. * @throws DbException
  223. * @throws ModelNotFoundException
  224. * @author xaboy
  225. * @day 2020-05-11
  226. */
  227. public function auth()
  228. {
  229. if (systemConfig('is_phone_login') === '1') {
  230. return app('json')->fail('请绑定手机号');
  231. }
  232. $request = $this->request;
  233. $oauth = WechatService::create()->getApplication()->oauth;
  234. $oauth->setRequest(new Request($request->get(), $request->post(), [], [], [], $request->server(), $request->getContent()));
  235. try {
  236. $wechatInfo = $oauth->user()->getOriginal();
  237. } catch (Exception $e) {
  238. return app('json')->fail('授权失败[001]', ['message' => $e->getMessage()]);
  239. }
  240. if (!isset($wechatInfo['nickname'])) {
  241. return app('json')->fail('授权失败[002]');
  242. }
  243. /** @var WechatUserRepository $make */
  244. $make = app()->make(WechatUserRepository::class);
  245. $user = $make->syncUser($wechatInfo['openid'], $wechatInfo);
  246. if (!$user)
  247. return app('json')->fail('授权失败[003]');
  248. /** @var UserRepository $make */
  249. $userRepository = app()->make(UserRepository::class);
  250. $user[1] = $userRepository->mainUser($user[1]);
  251. $pid = $this->request->param('spread', 0);
  252. $userRepository->bindSpread($user[1], intval($pid));
  253. $tokenInfo = $userRepository->createToken($user[1]);
  254. $userRepository->loginAfter($user[1]);
  255. return app('json')->success($userRepository->returnToken($user[1], $tokenInfo));
  256. }
  257. /**
  258. * @return mixed
  259. * @throws DataNotFoundException
  260. * @throws DbException
  261. * @throws ModelNotFoundException
  262. * @author xaboy
  263. * @day 2020-05-11
  264. */
  265. public function mpAuth()
  266. {
  267. list($code, $post_cache_key) = $this->request->params([
  268. 'code',
  269. 'cache_key',
  270. ], true);
  271. if (systemConfig('is_phone_login') === '1') {
  272. return app('json')->fail('请绑定手机号');
  273. }
  274. $userInfoCong = Cache::get('eb_api_code_' . $code);
  275. if (!$code && !$userInfoCong)
  276. return app('json')->fail('授权失败,参数有误');
  277. $miniProgramService = MiniProgramService::create();
  278. if ($code && !$userInfoCong) {
  279. try {
  280. $userInfoCong = $miniProgramService->getUserInfo($code);
  281. Cache::set('eb_api_code_' . $code, $userInfoCong, 86400);
  282. } catch (Exception $e) {
  283. return app('json')->fail('获取session_key失败,请检查您的配置!', ['line' => $e->getLine(), 'message' => $e->getMessage()]);
  284. }
  285. }
  286. $data = $this->request->params([
  287. ['spread_spid', 0],
  288. ['spread_code', ''],
  289. ['iv', ''],
  290. ['encryptedData', ''],
  291. ]);
  292. try {
  293. //解密获取用户信息
  294. $userInfo = $miniProgramService->encryptor($userInfoCong['session_key'], $data['iv'], $data['encryptedData']);
  295. } catch (Exception $e) {
  296. if ($e->getCode() == '-41003') return app('json')->fail('获取会话密匙失败');
  297. throw $e;
  298. }
  299. if (!$userInfo) return app('json')->fail('openid获取失败');
  300. if (!isset($userInfo['openId'])) $userInfo['openId'] = $userInfoCong['openid'] ?? '';
  301. $userInfo['unionId'] = $userInfoCong['unionid'] ?? $userInfo['unionId'] ?? '';
  302. if (!$userInfo['openId']) return app('json')->fail('openid获取失败');
  303. /** @var WechatUserRepository $make */
  304. $make = app()->make(WechatUserRepository::class);
  305. $user = $make->syncRoutineUser($userInfo['openId'], $userInfo);
  306. if (!$user)
  307. return app('json')->fail('授权失败');
  308. /** @var UserRepository $make */
  309. $userRepository = app()->make(UserRepository::class);
  310. $user[1] = $userRepository->mainUser($user[1]);
  311. $code = intval($data['spread_code']['id'] ?? $data['spread_code']);
  312. //获取是否有扫码进小程序
  313. if ($code && ($info = app()->make(RoutineQrcodeRepository::class)->getRoutineQrcodeFindType($code))) {
  314. $data['spread_spid'] = $info['third_id'];
  315. }
  316. $userRepository->bindSpread($user[1], intval($data['spread_spid']));
  317. $tokenInfo = $userRepository->createToken($user[1]);
  318. $userRepository->loginAfter($user[1]);
  319. return app('json')->success($userRepository->returnToken($user[1], $tokenInfo));
  320. }
  321. public function getCaptcha()
  322. {
  323. $codeBuilder = new CaptchaBuilder(null, new PhraseBuilder(4));
  324. $key = uniqid(microtime(true), true);
  325. Cache::set('api_captche' . $key, $codeBuilder->getPhrase(), 300);
  326. $captcha = $codeBuilder->build()->inline();
  327. return app('json')->success(compact('key', 'captcha'));
  328. }
  329. protected function checkCaptcha($uni, string $code): bool
  330. {
  331. $cacheName = 'api_captche' . $uni;
  332. if (!Cache::has($cacheName)) return false;
  333. $key = Cache::get($cacheName);
  334. $res = strtolower($key) == strtolower($code);
  335. if ($res) Cache::delete($cacheName);
  336. return $res;
  337. }
  338. public function verify(UserAuthValidate $validate)
  339. {
  340. $data = $this->request->params(['phone', ['type', 'login'], ['captchaType', 'clickWord'], ['captchaVerification', ''], 'token']);
  341. //二次验证
  342. try {
  343. aj_captcha_check_two($data['captchaType'], $data['captchaVerification']);
  344. } catch (\Throwable $e) {
  345. return app('json')->fail($e->getMessage());
  346. }
  347. $validate->sceneVerify()->check($data);
  348. $sms_limit_key = 'sms_limit_' . $data['phone'];
  349. $limit = Cache::get($sms_limit_key) ? Cache::get($sms_limit_key) : 0;
  350. $sms_limit = systemConfig('sms_limit');
  351. if ($sms_limit && $limit > $sms_limit) {
  352. return app('json')->fail('请求太频繁请稍后再试');
  353. }
  354. //if(!env('APP_DEBUG', false)){
  355. try {
  356. $sms_code = str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT);
  357. $sms_time = systemConfig('sms_time') ? systemConfig('sms_time') : 30;
  358. SmsService::create()->send($data['phone'], 'VERIFICATION_CODE', ['code' => $sms_code, 'time' => $sms_time]);
  359. } catch (Exception $e) {
  360. return app('json')->fail($e->getMessage());
  361. }
  362. //}else{
  363. // $sms_code = 1234;
  364. // $sms_time = 5;
  365. //}
  366. $sms_key = app()->make(SmsService::class)->sendSmsKey($data['phone'], $data['type']);
  367. Cache::set($sms_key, $sms_code, $sms_time * 60);
  368. Cache::set($sms_limit_key, $limit + 1, 60);
  369. //'短信发送成功'
  370. return app('json')->success('短信发送成功');
  371. }
  372. public function smsLogin(UserAuthValidate $validate, UserRepository $repository)
  373. {
  374. $data = $this->request->params(['phone', 'sms_code', 'spread', 'auth_token', ['user_type', 'h5']]);
  375. $validate->sceneSmslogin()->check($data);
  376. $sms_code = app()->make(SmsService::class)->checkSmsCode($data['phone'], $data['sms_code'], 'login');
  377. if (!$sms_code) return app('json')->fail('验证码不正确');
  378. $user = $repository->accountByUser($data['phone']);
  379. if (!$user) $user = $repository->getWhere(['phone' => $data['phone']]);
  380. $auth = $this->parseAuthToken($data['auth_token']);
  381. //有auth说明是绑定手机号
  382. if ($auth && $user && $user['wechat_user_id'] && $user['wechat_user_id'] !== $auth['id'])
  383. return app('json')->fail('该手机号已被绑定');
  384. if (!$user) $user = $repository->registr($data['phone'], null, $data['user_type']);
  385. if ($auth && !$user['wechat_user_id']) {
  386. $repository->syncBaseAuth($auth, $user);
  387. }
  388. $user = $repository->mainUser($user);
  389. $repository->bindSpread($user, intval($data['spread']));
  390. $tokenInfo = $repository->createToken($user);
  391. $repository->loginAfter($user);
  392. return app('json')->success($repository->returnToken($user, $tokenInfo));
  393. }
  394. public function changePassword(ChangePasswordValidate $validate, UserRepository $repository)
  395. {
  396. $data = $this->request->params(['phone', 'sms_code', 'pwd']);
  397. $validate->check($data);
  398. $user = $repository->accountByUser($data['phone']);
  399. if (!$user) return app('json')->fail('用户不存在');
  400. $sms_code = app()->make(SmsService::class)->checkSmsCode($data['phone'], $data['sms_code'], 'change_pwd');
  401. if (!$sms_code)
  402. return app('json')->fail('验证码不正确');
  403. $user->pwd = $repository->encodePassword($data['pwd']);
  404. $user->save();
  405. return app('json')->success('修改成功');
  406. }
  407. public function spread(UserRepository $userRepository)
  408. {
  409. $data = $this->request->params([
  410. ['spread_spid', 0],
  411. ['spread_code', null],
  412. ]);
  413. if (isset($data['spread_code']['id']) && ($info = app()->make(RoutineQrcodeRepository::class)->getRoutineQrcodeFindType($data['spread_code']['id']))) {
  414. $data['spread_spid'] = $info['third_id'];
  415. }
  416. $userRepository->bindSpread($this->request->userInfo(), intval($data['spread_spid']));
  417. return app('json')->success();
  418. }
  419. /**
  420. * 注册账号
  421. * @param UserAuthValidate $validate
  422. * @param UserRepository $repository
  423. * @return \think\response\Json
  424. * @author Qinii
  425. * @day 5/27/21
  426. */
  427. public function register(UserAuthValidate $validate, UserRepository $repository)
  428. {
  429. $data = $this->request->params(['phone', 'sms_code', 'spread', 'pwd', 'auth_token', ['user_type', 'h5']]);
  430. $validate->check($data);
  431. $sms_code = app()->make(SmsService::class)->checkSmsCode($data['phone'], $data['sms_code'], 'login');
  432. // if (!$sms_code)
  433. // return app('json')->fail('验证码不正确');
  434. $user = $repository->accountByUser($data['phone']);
  435. if ($user) return app('json')->fail('用户已存在');
  436. $auth = $this->parseAuthToken($data['auth_token']);
  437. $user = $repository->registr($data['phone'], $data['pwd'], $data['user_type']);
  438. if ($auth) {
  439. $repository->syncBaseAuth($auth, $user);
  440. }
  441. $user = $repository->mainUser($user);
  442. $repository->bindSpread($user, intval($data['spread']));
  443. $tokenInfo = $repository->createToken($user);
  444. $repository->loginAfter($user);
  445. return app('json')->success($repository->returnToken($user, $tokenInfo));
  446. }
  447. private function parseAuthToken($authToken)
  448. {
  449. $auth = Cache::get('u_try' . $authToken);
  450. $auth && Cache::delete('u_try' . $authToken);
  451. return $auth;
  452. }
  453. private function authInfo($auth, $createUser = false)
  454. {
  455. if (!in_array($auth['type'] ?? '', ['wechat', 'routine', 'apple', 'app_wechat']) || !isset($auth['auth']))
  456. throw new ValidateException('授权信息类型有误');
  457. $data = $auth['auth'];
  458. if ($auth['type'] === 'routine') {
  459. $code = $data['code'] ?? '';
  460. $userInfoCong = Cache::get('eb_api_code_' . $code);
  461. if (!$code && !$userInfoCong)
  462. throw new ValidateException('授权失败,参数有误');
  463. $miniProgramService = MiniProgramService::create();
  464. if ($code && !$userInfoCong) {
  465. try {
  466. $userInfoCong = $miniProgramService->getUserInfo($code);
  467. Cache::set('eb_api_code_' . $code, $userInfoCong, 86400);
  468. } catch (Exception $e) {
  469. throw new ValidateException('获取session_key失败,请检查您的配置!' . $e->getMessage());
  470. }
  471. }
  472. // try {
  473. // //解密获取用户信息
  474. // $userInfo = $miniProgramService->encryptor($userInfoCong['session_key'], $data['iv'], $data['encryptedData']);
  475. // } catch (Exception $e) {
  476. // if ($e->getCode() == '-41003') throw new ValidateException('获取会话密匙失败'.$e->getMessage());
  477. // throw $e;
  478. // }
  479. $userInfo = [];
  480. // if (!$userInfo) throw new ValidateException('openid获取失败');
  481. if (!isset($userInfo['openId'])) $userInfo['openId'] = $userInfoCong['openid'] ?? '';
  482. $userInfo['unionId'] = $userInfoCong['unionid'] ?? $userInfo['unionId'] ?? '';
  483. if (!$userInfo['openId']) throw new ValidateException('openid获取失败');
  484. /** @var WechatUserRepository $make */
  485. $make = app()->make(WechatUserRepository::class);
  486. $user = $make->syncRoutineUser($userInfo['openId'], $userInfo, $createUser);
  487. if (!$user)
  488. throw new ValidateException('授权失败');
  489. return $user;
  490. } else if ($auth['type'] === 'wechat') {
  491. $request = $this->request;
  492. $oauth = WechatService::create()->getApplication()->oauth;
  493. $oauth->setRequest(new Request($data, $data, [], [], [], $request->server(), $request->getContent()));
  494. try {
  495. $wechatInfo = $oauth->user()->getOriginal();
  496. } catch (Exception $e) {
  497. throw new ValidateException('授权失败[001]');
  498. }
  499. if (!isset($wechatInfo['nickname'])) {
  500. throw new ValidateException('授权失败[002]');
  501. }
  502. /** @var WechatUserRepository $make */
  503. $make = app()->make(WechatUserRepository::class);
  504. $user = $make->syncUser($wechatInfo['openid'], $wechatInfo, false, $createUser);
  505. if (!$user)
  506. throw new ValidateException('授权失败[003]');
  507. return $user;
  508. } else if ($auth['type'] === 'app_wechat') {
  509. $oauth = WechatService::create()->getApplication()->oauth;
  510. try {
  511. $wechatInfo = $oauth->user(new AccessToken(['access_token' => $data['code'], 'openid' => $data['openid']]))->getOriginal();
  512. } catch (Exception $e) {
  513. throw new ValidateException('授权失败[001]' . $e->getMessage());
  514. }
  515. $user = app()->make(WechatUserRepository::class)->syncAppUser($wechatInfo['unionid'], $wechatInfo, 'App', $createUser);
  516. if (!$user)
  517. throw new ValidateException('授权失败');
  518. return $user;
  519. } else if ($auth['type'] === 'apple') {
  520. $identityToken = $data['userInfo']['identityToken'];
  521. $tks = explode('.', $identityToken);
  522. if (count($tks) != 3) {
  523. throw new ValidateException('Wrong number of segments');
  524. }
  525. list($headb64, $bodyb64, $cryptob64) = $tks;
  526. if (null === ($payload = JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64)))) {
  527. throw new ValidateException('Invalid header encoding');
  528. }
  529. if ($payload->sub != $data['openId']) {
  530. throw new ValidateException('授权失败');
  531. }
  532. $user = app()->make(WechatUserRepository::class)->syncAppUser($data['openId'], [
  533. 'nickName' => (string)$data['nickname'] ?: '用户' . strtoupper(substr(md5(time()), 0, 12))
  534. ], 'App', $createUser);
  535. if (!$user)
  536. throw new ValidateException('授权失败');
  537. return $user;
  538. }
  539. }
  540. /**
  541. * @return \think\response\Json
  542. * @author Qinii
  543. * @day 2023/11/9
  544. */
  545. public function authLogin()
  546. {
  547. $auth = $this->request->param('auth');
  548. $users = $this->authInfo($auth, !systemConfig('is_phone_login'));
  549. if (!$users)
  550. return app('json')->fail('授权失败');
  551. $authInfo = $users[0];
  552. $userRepository = app()->make(UserRepository::class);
  553. $user = $users[1] ?? $userRepository->wechatUserIdBytUser($authInfo['wechat_user_id']);
  554. $code = (int)($auth['auth']['spread_code']['id'] ?? $auth['auth']['spread_code'] ?? '');
  555. //获取是否有扫码进小程序
  556. if ($code && ($info = app()->make(RoutineQrcodeRepository::class)->getRoutineQrcodeFindType($code))) {
  557. $auth['auth']['spread'] = $info['third_id'];
  558. }
  559. if (!$user) {
  560. $uni = uniqid(true, false) . random_int(1, 100000000);
  561. $key = 'U' . md5(time() . $uni);
  562. Cache::set('u_try' . $key, ['id' => $authInfo['wechat_user_id'], 'type' => $authInfo['user_type'], 'spread' => $auth['auth']['spread'] ?? 0], 3600);
  563. $wechat_phone_switch = systemConfig('wechat_phone_switch');
  564. return app('json')->status(201, compact('key','wechat_phone_switch'));
  565. }
  566. if ($auth['auth']['spread'] ?? 0) {
  567. $userRepository->bindSpread($user, (int)($auth['auth']['spread']));
  568. }
  569. $tokenInfo = $userRepository->createToken($user);
  570. $userRepository->loginAfter($user);
  571. return app('json')->status(200, $userRepository->returnToken($user, $tokenInfo));
  572. }
  573. /**
  574. * 查询小程序是否需要绑定手机好 以及绑定手机号的方式
  575. * @return \think\response\Json
  576. * @author Qinii
  577. * @day 2023/11/10'
  578. */
  579. public function mpLoginType()
  580. {
  581. $code = $this->request->param('code');
  582. if (!$code) return app('json')->fail('请获取code参数');
  583. $spread = $this->request->param('spread',0);
  584. $data = app()->make(WechatUserRepository::class)->mpLoginType($code,$spread);
  585. return app('json')->success($data);
  586. }
  587. /**
  588. * App微信登陆
  589. * @param Request $request
  590. * @return mixed
  591. */
  592. public function appAuth()
  593. {
  594. $data = $this->request->params(['userInfo']);
  595. if (systemConfig('is_phone_login') === '1') {
  596. return app('json')->fail('请绑定手机号');
  597. }
  598. $user = app()->make(WechatUserRepository::class)->syncAppUser($data['userInfo']['unionId'], $data['userInfo']);
  599. if (!$user)
  600. return app('json')->fail('授权失败');
  601. /** @var UserRepository $make */
  602. $userRepository = app()->make(UserRepository::class);
  603. $user[1] = $userRepository->mainUser($user[1]);
  604. $tokenInfo = $userRepository->createToken($user[1]);
  605. $userRepository->loginAfter($user[1]);
  606. return app('json')->success($userRepository->returnToken($user[1], $tokenInfo));
  607. }
  608. public function getMerCertificate($merId)
  609. {
  610. $merId = (int)$merId;
  611. $data = $this->request->params(['key', 'code']);
  612. if (!$this->checkCaptcha($data['key'], $data['code']))
  613. return app('json')->fail('验证码输入有误');
  614. $certificate = merchantConfig($merId, 'mer_certificate') ?: [];
  615. if (!count($certificate))
  616. return app('json')->fail('该商户未上传证书');
  617. return app('json')->success($certificate);
  618. }
  619. public function appleAuth()
  620. {
  621. $data = $this->request->params(['openId', 'nickname']);
  622. if (systemConfig('is_phone_login') === '1') {
  623. return app('json')->fail('请绑定手机号');
  624. }
  625. $user = app()->make(WechatUserRepository::class)->syncAppUser($data['openId'], [
  626. 'nickName' => (string)$data['nickname'] ?: '用户' . strtoupper(substr(md5(time()), 0, 12))
  627. ], 'apple');
  628. if (!$user)
  629. return app('json')->fail('授权失败');
  630. /** @var UserRepository $make */
  631. $userRepository = app()->make(UserRepository::class);
  632. $user[1] = $userRepository->mainUser($user[1]);
  633. $tokenInfo = $userRepository->createToken($user[1]);
  634. $userRepository->loginAfter($user[1]);
  635. return app('json')->success($userRepository->returnToken($user[1], $tokenInfo));
  636. }
  637. /**
  638. * 注销账号
  639. */
  640. public function cancel()
  641. {
  642. $userRepository = app()->make(UserRepository::class);
  643. $user = $this->request->userInfo();
  644. $order = app()->make(StoreOrderRepository::class)->search(['uid' => $user['uid'], 'paid' => 1])->where('StoreOrder.status', 0)->count();
  645. $refund = app()->make(StoreRefundOrderRepository::class)->search(['uid' => $user['uid'], 'type' => 1])->count();
  646. $key = $this->request->param('key');
  647. $flag = false;
  648. if ($user->now_money > 0 || $user->integral > 0 || $order > 0 || $refund > 0) {
  649. $flag = true;
  650. if (!$key) {
  651. $uni = uniqid(true, false) . random_int(1, 100000000);
  652. $key = 'L' . md5(time() . $uni);
  653. Cache::set('u_out' . $user['uid'], $key, 600);
  654. return app('json')->status(201, '该账号下有未完成业务,注销后不可恢复,您确定继续注销?', compact('key'));
  655. }
  656. }
  657. if ($flag && (!$key || (Cache::get('u_out' . $user['uid']) != $key))) {
  658. return app('json')->fail('操作超时');
  659. }
  660. $userRepository->cancel($user);
  661. $userRepository->clearToken($user);
  662. return app('json')->status(200, '注销成功');
  663. }
  664. /**
  665. * 通过小程序组件,获取小程序绑定手机号
  666. * @return \think\response\Json
  667. * @author Qinii
  668. * @day 2023/11/9
  669. */
  670. public function mpPhone()
  671. {
  672. $code = $this->request->param('code');
  673. $auth_token = $this->request->param('auth_token');
  674. $iv = $this->request->param('iv');
  675. $encryptedData = $this->request->param('encryptedData');
  676. $miniProgramService = MiniProgramService::create();
  677. $userInfoCong = Cache::get('eb_api_code_' . $code);
  678. if (!$code && !$userInfoCong)
  679. throw new ValidateException('授权失败,参数有误');
  680. if ($code && !$userInfoCong) {
  681. try {
  682. $userInfoCong = $miniProgramService->getUserInfo($code);
  683. Cache::set('eb_api_code_' . $code, $userInfoCong, 86400);
  684. } catch (Exception $e) {
  685. throw new ValidateException('获取session_key失败,请检查您的配置!');
  686. }
  687. }
  688. $session_key = $userInfoCong['session_key'];
  689. $data = $miniProgramService->encryptor($session_key, $iv, $encryptedData);
  690. $userRepository = app()->make(UserRepository::class);
  691. $phone = $data['purePhoneNumber'];
  692. $user = $userRepository->accountByUser($phone);
  693. // if($user && $auth_token){
  694. // return app('json')->fail('用户已存在');
  695. // }
  696. $auth = $this->parseAuthToken($auth_token);
  697. if ($user && $auth) {
  698. $userRepository->syncBaseAuth($auth, $user);
  699. } else if (!$user) {
  700. if (!$auth) {
  701. return app('json')->fail('操作超时');
  702. }
  703. $wechatUser = app()->make(WechatUserRepository::class)->get($auth['id']);
  704. $user = $userRepository->syncWechatUser($wechatUser, 'routine');
  705. $user->phone = $phone;
  706. $user->account = $phone;
  707. $user->save();
  708. if ($auth['spread']) {
  709. $userRepository->bindSpread($user,(int)$auth['spread']);
  710. }
  711. }
  712. $tokenInfo = $userRepository->createToken($user);
  713. $userRepository->loginAfter($user);
  714. return app('json')->success($userRepository->returnToken($user, $tokenInfo));
  715. }
  716. /**
  717. * @return mixed
  718. */
  719. public function ajcaptcha()
  720. {
  721. $captchaType = $this->request->param('captchaType', 'clickWord');
  722. if (!$captchaType) return app('json')->fail('请输入类型');
  723. return app('json')->success(aj_captcha_create($captchaType));
  724. }
  725. /**
  726. * 一次验证
  727. * @return mixed
  728. */
  729. public function ajcheck()
  730. {
  731. $token = $this->request->param('token', '');
  732. $pointJson = $this->request->param('pointJson', '');
  733. $captchaType = $this->request->param('captchaType', 'clickWord');
  734. try {
  735. aj_captcha_check_one($captchaType, $token, $pointJson);
  736. return app('json')->success();
  737. } catch (\Throwable $e) {
  738. return app('json')->fail($e->getMessage());
  739. }
  740. }
  741. }