Auth.php 37 KB

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