Auth.php 38 KB

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