Auth.php 37 KB

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