Auth.php 39 KB

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