Auth.php 37 KB

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