Auth.php 36 KB

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