Auth.php 39 KB

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