Auth.php 38 KB

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