Auth.php 37 KB

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