Auth.php 34 KB

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