Auth.php 38 KB

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