Auth.php 40 KB

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