Auth.php 36 KB

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