Auth.php 36 KB

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