Auth.php 34 KB

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