Auth.php 39 KB

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