Auth.php 37 KB

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