Auth.php 37 KB

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