// +---------------------------------------------------------------------- namespace app\controller\api; use app\common\repositories\store\order\StoreOrderRepository; use app\common\repositories\store\order\StoreRefundOrderRepository; use app\common\repositories\system\HuitongRepository; use app\common\repositories\system\notice\SystemNoticeConfigRepository; use app\common\repositories\system\notice\SystemNoticeRepository; use app\common\repositories\user\UserAssetsLogRepository; use app\common\repositories\user\UserAssetsRepository; use app\common\repositories\user\UserGroupRepository; use app\common\repositories\user\UserRepository; use app\common\repositories\user\UserSignRepository; use app\common\repositories\wechat\RoutineQrcodeRepository; use app\common\repositories\wechat\WechatUserRepository; use app\validate\api\ChangePasswordValidate; use app\validate\api\UserAuthValidate; use crmeb\basic\BaseController; use crmeb\services\MiniProgramService; use crmeb\services\SmsService; use crmeb\services\WechatService; use crmeb\services\WechatTemplateMessageService; use Exception; use Firebase\JWT\JWT; use Gregwar\Captcha\CaptchaBuilder; use Gregwar\Captcha\PhraseBuilder; use Overtrue\Socialite\AccessToken; use Symfony\Component\HttpFoundation\Request; use think\db\exception\DataNotFoundException; use think\db\exception\DbException; use think\db\exception\ModelNotFoundException; use think\exception\ValidateException; use think\facade\Cache; use think\facade\Log; use think\facade\Queue; use crmeb\jobs\SendSmsJob; /** * Class Auth * @package app\controller\api * @author xaboy * @day 2020-05-06 */ class Auth extends BaseController { public function test() { // $json = '{"groupOrder":{"uid":3,"group_order_sn":"wxo1710768193328392661","total_postage":"0.00","total_price":"100.00","total_num":1,"real_name":"\u5f20\u51ef\u7fd4","user_phone":"18362705640","user_address":"\u6c5f\u82cf\u5357\u4eac\u5e02\u6816\u971e\u533a\u5c27\u5316\u8857\u9053\u4e1c\u57ce\u4e16\u5bb6(\u5357\u4eac\u5e02\u6816\u971e\u533a\u5c27\u8fb0\u8def3\u53f7)24\u680b501","pay_price":"100.00","coupon_price":"0.00","pay_postage":"0.00","cost":"0.00","coupon_id":"","pay_type":0,"give_coupon_ids":[],"integral":"0","integral_price":"0.00","give_integral":"100","create_time":"2024-03-18 21:23:13","group_order_id":"32","paid":1,"pay_time":"2024-03-18 21:23:13","is_combine":0,"orderList":[{"order_id":33,"main_id":0,"group_order_id":32,"order_sn":"wxo1710768193328392661","uid":3,"spread_uid":0,"top_uid":1,"district_id":3378,"real_name":"\u5f20\u51ef\u7fd4","user_phone":"18362705640","user_address":"\u6c5f\u82cf\u5357\u4eac\u5e02\u6816\u971e\u533a\u5c27\u5316\u8857\u9053\u4e1c\u57ce\u4e16\u5bb6(\u5357\u4eac\u5e02\u6816\u971e\u533a\u5c27\u8fb0\u8def3\u53f7)24\u680b501","cart_id":"77","total_num":1,"total_price":"100.00","total_postage":"0.00","pay_price":"100.00","pay_postage":"0.00","is_selfbuy":0,"extension_one":"0.00","extension_two":"1.20","commission_rate":"30.0000","integral":0,"integral_price":"0.00","give_integral":100,"coupon_id":"","coupon_price":"0.00","platform_coupon_price":"0.00","svip_discount":"0.00","order_type":0,"paid":1,"pay_time":"2024-03-18 21:23:13","pay_type":0,"create_time":"2024-03-18 21:23:13","status":0,"delivery_type":null,"is_virtual":0,"delivery_name":null,"delivery_id":null,"mark":"","remark":null,"admin_mark":null,"verify_code":null,"verify_time":null,"verify_service_id":null,"transaction_id":null,"activity_type":0,"order_extend":null,"mer_id":6,"reconciliation_id":0,"cost":"0.00","is_del":0,"is_system_del":0,"verify_status":0,"user":{"uid":3,"wechat_user_id":3,"account":"18362705640","pwd":"$2y$10$wYWu1Xc.pUqVwldOM3C\/EenyUPFg8DGlVbZuT.H9cIh.YtANOFmK6","real_name":"","sex":0,"birthday":null,"card_id":"","mark":"","label_id":[],"group_id":0,"agent_district_id":0,"agent_district":"","mer_id":1,"nickname":"\u5fae\u4fe1\u7528\u6237","avatar":"https:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg\/132","phone":"18362705640","addres":null,"cancel_time":null,"create_time":"2024-03-09 22:48:59","last_time":"2024-03-18 13:24:57","last_ip":"180.98.131.161","now_money":"8020.00","brokerage_price":"0.00","status":1,"spread_uid":2,"spread_time":"2024-03-09 22:48:59","spread_limit":null,"brokerage_level":0,"user_type":"routine","promoter_time":null,"is_promoter":0,"main_uid":0,"pay_count":13,"pay_price":"2060.10","spread_count":0,"spread_pay_count":0,"spread_pay_price":"0.00","integral":2070,"member_level":0,"member_value":0,"count_start":0,"count_fans":0,"is_svip":-1,"svip_endtime":null,"svip_save_money":"0.00"},"orderProduct":[{"order_product_id":33,"order_id":33,"uid":3,"cart_id":77,"product_id":203,"extension_one":"0.00","extension_two":"1.20","integral":0,"integral_price":"0.00","integral_total":0,"coupon_price":"0.00","platform_coupon_price":null,"svip_discount":"0.00","postage_price":"0.00","product_sku":"78c5e599c2a0","is_refund":0,"product_num":1,"product_type":0,"activity_id":203,"refund_num":1,"is_reply":0,"cost":"0.00","product_price":"100.00","total_price":"100.00","cart_info":{"product":{"product_id":203,"cate_id":17,"image":"http:\/\/b2.njrenzhou.com\/uploads\/def\/20240314\/e3c14a605d720c3429b6793abbb74e4b.jpg","store_name":"\u6d4b\u8bd5\u5546\u54c1","is_show":1,"status":1,"is_del":0,"unit_name":"\u7247","price":"100.00","mer_status":1,"temp_id":6,"give_coupon_ids":[],"is_gift_bag":0,"is_used":1,"product_type":0,"old_product_id":0,"integral_rate":-1,"delivery_way":"2","delivery_free":0,"type":0,"extend":"","pay_limit":0,"once_max_count":0,"once_min_count":0,"mer_svip_status":1,"svip_price_type":0,"temp":{"shipping_template_id":6,"name":"\u9ed8\u8ba4\u6a21\u677f","type":1,"appoint":0,"undelivery":0,"mer_id":6,"is_default":0,"sort":0,"create_time":"2022-04-24 15:29:04","info":null,"region":[],"undelives":null,"free":[]}},"productAttr":{"image":"http:\/\/b2.njrenzhou.com\/uploads\/def\/20240314\/e3c14a605d720c3429b6793abbb74e4b.jpg","extension_one":"0.00","extension_two":"0.00","product_id":203,"stock":195,"price":"100.00","unique":"78c5e599c2a0","sku":"","volume":"0.00","weight":"0.00","ot_price":"0.00","cost":"0.00","svip_price":"0.00","show_svip_price":false,"product":{"product_id":203,"mer_id":6,"store_name":"\u6d4b\u8bd5\u5546\u54c1","store_info":"dssssss","keyword":"\u6d4b\u8bd5","bar_code":"","brand_id":120,"is_show":1,"status":1,"is_del":0,"mer_status":1,"cate_id":17,"unit_name":"\u7247","sort":0,"rank":0,"sales":5,"price":"100.00","cost":"0.00","ot_price":"0.00","stock":195,"is_hot":1,"is_benefit":0,"is_best":0,"is_new":0,"is_good":1,"product_type":0,"ficti":0,"browse":0,"code_path":"","video_link":"","temp_id":6,"spec_type":0,"extension_type":0,"refusal":null,"rate":"3.0","reply_count":0,"give_coupon_ids":[],"is_gift_bag":0,"create_time":"2024-03-14 20:48:53","care_count":0,"is_used":1,"old_product_id":0,"image":"http:\/\/b2.njrenzhou.com\/uploads\/def\/20240314\/e3c14a605d720c3429b6793abbb74e4b.jpg","slider_image":["http:\/\/b2.njrenzhou.com\/uploads\/def\/20240314\/e3c14a605d720c3429b6793abbb74e4b.jpg"],"guarantee_template_id":0,"once_max_count":0,"once_min_count":0,"integral_rate":-1,"integral_total":0,"integral_price_total":"0.00","labels":"","delivery_way":"2","delivery_free":0,"type":0,"extend":"","pay_limit":0,"svip_price_type":0,"svip_price":0,"mer_svip_status":1,"param_temp_id":"","cash_rate":100,"base":20},"bc_extension_one":2,"bc_extension_two":1},"product_type":0},"create_time":"2024-03-18 21:23:13"}]}],"user":{"uid":3,"wechat_user_id":3,"account":"18362705640","pwd":"$2y$10$wYWu1Xc.pUqVwldOM3C\/EenyUPFg8DGlVbZuT.H9cIh.YtANOFmK6","real_name":"","sex":0,"birthday":null,"card_id":"","mark":"","label_id":[],"group_id":0,"agent_district_id":0,"agent_district":"","mer_id":1,"nickname":"\u5fae\u4fe1\u7528\u6237","avatar":"https:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg\/132","phone":"18362705640","addres":null,"cancel_time":null,"create_time":"2024-03-09 22:48:59","last_time":"2024-03-18 13:24:57","last_ip":"180.98.131.161","now_money":"8020.00","brokerage_price":"0.00","status":1,"spread_uid":2,"spread_time":"2024-03-09 22:48:59","spread_limit":null,"brokerage_level":0,"user_type":"routine","promoter_time":null,"is_promoter":0,"main_uid":0,"pay_count":13,"pay_price":"2060.10","spread_count":0,"spread_pay_count":0,"spread_pay_price":"0.00","integral":2070,"member_level":0,"member_value":0,"count_start":0,"count_fans":0,"is_svip":-1,"svip_endtime":null,"svip_save_money":"0.00"}}}'; // event("order.paySuccess", json_decode($json, true)); // event('order.statistics'); // $json = '{"order":{"order_id":33,"main_id":0,"group_order_id":27,"order_sn":"wxo1710646722542760291","uid":3,"spread_uid":0,"top_uid":0,"district_id":3378,"real_name":"\u5f20\u51ef\u7fd4","user_phone":"18362705640","user_address":"\u6c5f\u82cf\u5357\u4eac\u5e02\u6816\u971e\u533a\u5c27\u5316\u8857\u9053\u4e1c\u57ce\u4e16\u5bb6(\u5357\u4eac\u5e02\u6816\u971e\u533a\u5c27\u8fb0\u8def3\u53f7)24\u680b501","cart_id":"69","total_num":1,"total_price":"180.00","total_postage":"0.00","pay_price":"180.00","pay_postage":"0.00","is_selfbuy":0,"extension_one":"0.00","extension_two":"0.00","commission_rate":"5.0000","integral":0,"integral_price":"0.00","give_integral":180,"coupon_id":"","coupon_price":"0.00","platform_coupon_price":"0.00","svip_discount":"0.00","order_type":0,"paid":1,"pay_time":"2024-03-17 11:38:42","pay_type":0,"create_time":"2024-03-17 11:38:43","status":-1,"delivery_type":null,"is_virtual":0,"delivery_name":null,"delivery_id":null,"mark":"","remark":null,"admin_mark":null,"verify_code":null,"verify_time":null,"verify_service_id":null,"transaction_id":null,"activity_type":0,"order_extend":null,"mer_id":6,"reconciliation_id":0,"cost":"200.00","is_del":0,"is_system_del":0,"verify_status":0,"orderProduct":[{"order_product_id":28,"order_id":28,"uid":3,"cart_id":69,"product_id":6,"extension_one":"0.00","extension_two":"0.00","integral":0,"integral_price":"0.00","integral_total":0,"coupon_price":"0.00","platform_coupon_price":null,"svip_discount":"0.00","postage_price":"0.00","product_sku":"167ac3990130","is_refund":3,"product_num":1,"product_type":0,"activity_id":6,"refund_num":0,"is_reply":0,"cost":"200.00","product_price":"180.00","total_price":"180.00","cart_info":{"product":{"product_id":6,"cate_id":14,"image":"https:\/\/mer.crmeb.net\/uploads\/attach\/2022\/04\/24\/8113054bdc3753c2f4f479e5b04f11d1.png","store_name":"Prada\/\u666e\u62c9\u8fbe\u5973\u58eb\u53d1\u5939\u5934\u9970","is_show":1,"status":1,"is_del":0,"unit_name":"\u4ef6","price":"180.00","mer_status":1,"temp_id":0,"give_coupon_ids":[],"is_gift_bag":0,"is_used":1,"product_type":0,"old_product_id":0,"integral_rate":0,"delivery_way":"2","delivery_free":1,"type":0,"extend":"","pay_limit":0,"once_max_count":0,"once_min_count":0,"mer_svip_status":1,"svip_price_type":0,"temp":null},"productAttr":{"image":"https:\/\/img.alicdn.com\/imgextra\/i2\/2207289125344\/O1CN010XEeaY1pLbHpe8KwV_!!2-item_pic.png","extension_one":"0.00","extension_two":"0.00","product_id":6,"stock":999,"price":"180.00","unique":"167ac3990130","sku":"\u767e\u5408\u8272","volume":"0.00","weight":"0.00","ot_price":"200.00","cost":"200.00","svip_price":"0.00","show_svip_price":false,"bc_extension_one":3.6,"bc_extension_two":1.8},"product_type":0},"create_time":"2024-03-17 11:38:42"}],"presellOrder":null,"groupOrder":{"group_order_id":27,"group_order_sn":"wxo1710646722542760291","uid":3,"total_postage":"0.00","total_price":"180.00","total_num":1,"integral":0,"integral_price":"0.00","give_integral":180,"coupon_price":"0.00","real_name":"\u5f20\u51ef\u7fd4","user_phone":"18362705640","user_address":"\u6c5f\u82cf\u5357\u4eac\u5e02\u6816\u971e\u533a\u5c27\u5316\u8857\u9053\u4e1c\u57ce\u4e16\u5bb6(\u5357\u4eac\u5e02\u6816\u971e\u533a\u5c27\u8fb0\u8def3\u53f7)24\u680b501","pay_price":"180.00","pay_postage":"0.00","cost":"200.00","coupon_id":"","give_coupon_ids":[],"paid":1,"pay_time":"2024-03-17 11:38:42","pay_type":0,"create_time":"2024-03-17 11:38:43","is_remind":0,"is_del":0,"is_combine":0}}}'; // event("order.refundAll", json_decode($json, true)); return app('json')->success(); // $data = [ // 'tempId' => '', // 'id' => '', // ]; // Queue::push(SendSmsJob::class,$data); // $status = app()->make(SystemNoticeConfigRepository::class)->getNoticeStatusByConstKey($data['tempId']); // if ($status['notice_sms'] == 1) { // SmsService::sendMessage($data); // } // if ($status['notice_wechat'] == 1) { // app()->make(WechatTemplateMessageService::class)->sendTemplate($data); // } // if ($status['notice_routine'] == 1) { // app()->make(WechatTemplateMessageService::class)->subscribeSendTemplate($data); // } } /** * @param UserRepository $repository * @return mixed * @throws DbException * @author xaboy * @day 2020/6/1 */ public function login(UserRepository $repository) { $account = $this->request->param('account'); $auth_token = $this->request->param('auth_token'); if (Cache::get('api_login_freeze_' . $account)) return app('json')->fail('账号或密码错误次数太多,请稍后在尝试'); if (!$account) return app('json')->fail('请输入账号'); $user = $repository->accountByUser($this->request->param('account')); // if($auth_token && $user){ // return app('json')->fail('用户已存在'); // } if (!$user) $this->loginFailure($account); if (!password_verify($pwd = (string)$this->request->param('password'), $user['pwd'])) $this->loginFailure($account); $auth = $this->parseAuthToken($auth_token); if ($auth && !$user['wechat_user_id']) { $repository->syncBaseAuth($auth, $user); } $user = $repository->mainUser($user); $pid = $this->request->param('spread', 0); $repository->bindSpread($user, intval($pid)); $tokenInfo = $repository->createToken($user); $repository->loginAfter($user); return app('json')->success($repository->returnToken($user, $tokenInfo)); } /** * TODO 登录尝试次数限制 * @param $account * @param int $number * @param int $n * @author Qinii * @day 7/6/21 */ public function loginFailure($account, $number = 5, $n = 3) { $key = 'api_login_failuree_' . $account; $numb = Cache::get($key) ?? 0; $numb++; if ($numb >= $number) { $fail_key = 'api_login_freeze_' . $account; Cache::set($fail_key, 1, 15 * 60); throw new ValidateException('账号或密码错误次数太多,请稍后在尝试'); } else { Cache::set($key, $numb, 5 * 60); $msg = '账号或密码错误'; $_n = $number - $numb; if ($_n <= $n) { $msg .= ',还可尝试' . $_n . '次'; } throw new ValidateException($msg); } } public function noticeList() { [$page, $limit] = $this->getPage(); $where = array('type' => 5); return app('json')->success(app(SystemNoticeRepository::class)->getList($where, $page, $limit)); } /** * @return mixed * @author xaboy * @day 2020/6/1 */ public function userInfo() { $user = $this->request->userInfo()->hidden(['label_id', 'pwd', 'addres', 'card_id', 'last_time', 'last_ip', 'create_time', 'mark', 'status', 'spread_uid', 'spread_time', 'real_name', 'birthday', 'brokerage_price']); $user->append(['service', 'topService', 'total_collect_product', 'total_collect_store', 'total_coupon', 'total_visit_product', 'total_unread', 'total_recharge', 'lock_integral', 'total_integral']); $data = $user->toArray(); $data['total_consume'] = $user['pay_price']; $data['extension_status'] = systemConfig('extension_status'); if (systemConfig('member_status')) $data['member_icon'] = $this->request->userInfo()->member->brokerage_icon ?? ''; if ($data['is_svip'] == 3) $data['svip_endtime'] = date('Y-m-d H:i:s',strtotime("+100 year")); $day = date('Y-m-d',time()); $key = 'sign_'.$user['uid'].'_'.$day; $data['sign_status'] = false; if (Cache::get($key)) { $data['sign_status'] = true; } else { $nu = app()->make(UserSignRepository::class)->getSign($user->uid,$day); if ($nu) { $data['sign_status'] = true; Cache::set($key,true, new \DateTime($day.' 23:59:59')); } } $groupRepository = app(UserGroupRepository::class); $groupData = $groupRepository->getList([], 1, 10); $groupList = array_column($groupData['list']->toArray(), 'group_name', 'group_id'); $data['group_name'] = $groupList[$data['group_id']] ?? ''; // 用户资产 $assets = app(UserAssetsRepository::class)->assets($data['uid']); $data['assets'] = $assets; return app('json')->success($data); } public function groupList(){ $groupRepository = app(UserGroupRepository::class); $data = $groupRepository->getList([], 1, 10); return app('json')->success($data['list']); } /** * notes 兑换配置 * @return mixed * @create 2024/3/19 22:20 * @update 2024/3/19 22:20 * @author zhangkxiang * @editor */ public function exchangeConfig(){ $config = app(UserAssetsRepository::class)->getConfig(); $huitong = app(HuitongRepository::class)->getCurrent(); $data = [ 'consumeToShare' => $config['consume_to_share'], 'huitongToConsume' => $huitong ]; return app('json')->success($data); } public function toShare(){ $count = $this->request->param('count', 1); $uid = 3; try { app(UserAssetsRepository::class)->consumeToShare($uid, $count); }catch (\Exception $e){ return app('json')->fail($e->getMessage()); } return app('json')->success(); } public function toHuitong(){ $count = $this->request->param('count', 1); $phone = $this->request->param('phoneTo', "13166665555"); $smsCode = $this->request->param('smsCode', 0156); $type = $this->request->param('type', 'intention'); $uid = 3; Log::info("code: {$smsCode}, type: {$type}"); // $checkSms = app()->make(SmsService::class)->checkSmsCode('18362705640', $smsCode, $type); // if (!$smsCode || !$checkSms) // return app('json')->fail('验证码不正确'); try { app(UserAssetsRepository::class)->sendHuitong($uid, $phone, $count); }catch (\Exception $e){ return app('json')->fail($e->getMessage()); } return app('json')->success(); } /** * @param UserRepository $repository * @return mixed * @author xaboy * @day 2020/6/1 */ public function logout(UserRepository $repository) { $repository->clearToken($this->request->token()); return app('json')->success('退出登录'); } /** * @return mixed * @throws DataNotFoundException * @throws DbException * @throws ModelNotFoundException * @author xaboy * @day 2020-05-11 */ public function auth() { if (systemConfig('is_phone_login') === '1') { return app('json')->fail('请绑定手机号'); } $request = $this->request; $oauth = WechatService::create()->getApplication()->oauth; $oauth->setRequest(new Request($request->get(), $request->post(), [], [], [], $request->server(), $request->getContent())); try { $wechatInfo = $oauth->user()->getOriginal(); } catch (Exception $e) { return app('json')->fail('授权失败[001]', ['message' => $e->getMessage()]); } if (!isset($wechatInfo['nickname'])) { return app('json')->fail('授权失败[002]'); } /** @var WechatUserRepository $make */ $make = app()->make(WechatUserRepository::class); $user = $make->syncUser($wechatInfo['openid'], $wechatInfo); if (!$user) return app('json')->fail('授权失败[003]'); /** @var UserRepository $make */ $userRepository = app()->make(UserRepository::class); $user[1] = $userRepository->mainUser($user[1]); $pid = $this->request->param('spread', 0); $userRepository->bindSpread($user[1], intval($pid)); $tokenInfo = $userRepository->createToken($user[1]); $userRepository->loginAfter($user[1]); return app('json')->success($userRepository->returnToken($user[1], $tokenInfo)); } /** * @return mixed * @throws DataNotFoundException * @throws DbException * @throws ModelNotFoundException * @author xaboy * @day 2020-05-11 */ public function mpAuth() { list($code, $post_cache_key) = $this->request->params([ 'code', 'cache_key', ], true); if (systemConfig('is_phone_login') === '1') { return app('json')->fail('请绑定手机号'); } $userInfoCong = Cache::get('eb_api_code_' . $code); if (!$code && !$userInfoCong) return app('json')->fail('授权失败,参数有误'); $miniProgramService = MiniProgramService::create(); if ($code && !$userInfoCong) { try { $userInfoCong = $miniProgramService->getUserInfo($code); Cache::set('eb_api_code_' . $code, $userInfoCong, 86400); } catch (Exception $e) { return app('json')->fail('获取session_key失败,请检查您的配置!', ['line' => $e->getLine(), 'message' => $e->getMessage()]); } } $data = $this->request->params([ ['spread_spid', 0], ['spread_code', ''], ['iv', ''], ['encryptedData', ''], ]); try { //解密获取用户信息 $userInfo = $miniProgramService->encryptor($userInfoCong['session_key'], $data['iv'], $data['encryptedData']); } catch (Exception $e) { if ($e->getCode() == '-41003') return app('json')->fail('获取会话密匙失败'); throw $e; } if (!$userInfo) return app('json')->fail('openid获取失败'); if (!isset($userInfo['openId'])) $userInfo['openId'] = $userInfoCong['openid'] ?? ''; $userInfo['unionId'] = $userInfoCong['unionid'] ?? $userInfo['unionId'] ?? ''; if (!$userInfo['openId']) return app('json')->fail('openid获取失败'); /** @var WechatUserRepository $make */ $make = app()->make(WechatUserRepository::class); $user = $make->syncRoutineUser($userInfo['openId'], $userInfo); if (!$user) return app('json')->fail('授权失败'); /** @var UserRepository $make */ $userRepository = app()->make(UserRepository::class); $user[1] = $userRepository->mainUser($user[1]); $code = intval($data['spread_code']['id'] ?? $data['spread_code']); //获取是否有扫码进小程序 if ($code && ($info = app()->make(RoutineQrcodeRepository::class)->getRoutineQrcodeFindType($code))) { $data['spread_spid'] = $info['third_id']; } $userRepository->bindSpread($user[1], intval($data['spread_spid'])); $tokenInfo = $userRepository->createToken($user[1]); $userRepository->loginAfter($user[1]); return app('json')->success($userRepository->returnToken($user[1], $tokenInfo)); } public function getCaptcha() { $codeBuilder = new CaptchaBuilder(null, new PhraseBuilder(4)); $key = uniqid(microtime(true), true); Cache::set('api_captche' . $key, $codeBuilder->getPhrase(), 300); $captcha = $codeBuilder->build()->inline(); return app('json')->success(compact('key', 'captcha')); } protected function checkCaptcha($uni, string $code): bool { $cacheName = 'api_captche' . $uni; if (!Cache::has($cacheName)) return false; $key = Cache::get($cacheName); $res = strtolower($key) == strtolower($code); if ($res) Cache::delete($cacheName); return $res; } public function verify(UserAuthValidate $validate) { $data = $this->request->params(['phone', ['type', 'login'],['captchaType', ''], ['captchaVerification', ''],'token']); //二次验证 try { aj_captcha_check_two($data['captchaType'], $data['captchaVerification']); } catch (\Throwable $e) { return app('json')->fail($e->getMessage()); } $validate->sceneVerify()->check($data); $sms_limit_key = 'sms_limit_' . $data['phone']; $limit = Cache::get($sms_limit_key) ? Cache::get($sms_limit_key) : 0; $sms_limit = systemConfig('sms_limit'); if ($sms_limit && $limit > $sms_limit) { return app('json')->fail('请求太频繁请稍后再试'); } // if(!env('APP_DEBUG', false)){ try { $sms_code = str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT); $sms_time = systemConfig('sms_time') ? systemConfig('sms_time') : 30; Log::info("{$data['phone']} send {$sms_code} with {$data['type']} "); SmsService::create()->send($data['phone'], 'VERIFICATION_CODE', ['code' => $sms_code, 'time' => $sms_time]); } catch (Exception $e) { return app('json')->fail($e->getMessage()); } // }else{ // $sms_code = 1234; // $sms_time = 5; // } $sms_key = app()->make(SmsService::class)->sendSmsKey($data['phone'], $data['type']); Cache::set($sms_key, $sms_code, $sms_time * 60); Cache::set($sms_limit_key, $limit + 1, 60); //'短信发送成功' return app('json')->success('短信发送成功'); } public function smsLogin(UserAuthValidate $validate, UserRepository $repository) { $data = $this->request->params(['phone', 'sms_code', 'spread', 'auth_token',['user_type','h5']]); $validate->sceneSmslogin()->check($data); $sms_code = app()->make(SmsService::class)->checkSmsCode($data['phone'], $data['sms_code'], 'login'); if (!$sms_code) return app('json')->fail('验证码不正确'); $user = $repository->accountByUser($data['phone']); $auth = $this->parseAuthToken($data['auth_token']); if (!$user) $user = $repository->registr($data['phone'], null, $data['user_type']); if ($auth && !$user['wechat_user_id']){ $repository->syncBaseAuth($auth, $user); } $user = $repository->mainUser($user); $repository->bindSpread($user, intval($data['spread'])); $tokenInfo = $repository->createToken($user); $repository->loginAfter($user); return app('json')->success($repository->returnToken($user, $tokenInfo)); } public function changePassword(ChangePasswordValidate $validate, UserRepository $repository) { $data = $this->request->params(['phone', 'sms_code', 'pwd']); $validate->check($data); $user = $repository->accountByUser($data['phone']); if (!$user) return app('json')->fail('用户不存在'); $sms_code = app()->make(SmsService::class)->checkSmsCode($data['phone'], $data['sms_code'], 'change_pwd'); if (!$sms_code) return app('json')->fail('验证码不正确'); $user->pwd = $repository->encodePassword($data['pwd']); $user->save(); return app('json')->success('修改成功'); } public function spread(UserRepository $userRepository) { $data = $this->request->params([ ['spread_spid', 0], ['spread_code', null], ]); if (isset($data['spread_code']['id']) && ($info = app()->make(RoutineQrcodeRepository::class)->getRoutineQrcodeFindType($data['spread_code']['id']))) { $data['spread_spid'] = $info['third_id']; } $userRepository->bindSpread($this->request->userInfo(), intval($data['spread_spid'])); return app('json')->success(); } /** * TODO 注册账号 * @param UserAuthValidate $validate * @param UserRepository $repository * @return \think\response\Json * @author Qinii * @day 5/27/21 */ public function register(UserAuthValidate $validate, UserRepository $repository) { $data = $this->request->params(['phone', 'sms_code', 'spread', 'pwd', 'auth_token',['user_type','h5']]); $validate->check($data); $sms_code = app()->make(SmsService::class)->checkSmsCode($data['phone'], $data['sms_code'], 'login'); if (!$sms_code) return app('json')->fail('验证码不正确'); $user = $repository->accountByUser($data['phone']); if ($user) return app('json')->fail('用户已存在'); $auth = $this->parseAuthToken($data['auth_token']); $user = $repository->registr($data['phone'], $data['pwd'], $data['user_type']); if ($auth){ $repository->syncBaseAuth($auth, $user); } $user = $repository->mainUser($user); $repository->bindSpread($user, intval($data['spread'])); $tokenInfo = $repository->createToken($user); $repository->loginAfter($user); return app('json')->success($repository->returnToken($user, $tokenInfo)); } private function parseAuthToken($authToken) { $auth = Cache::get('u_try' . $authToken); $auth && Cache::delete('u_try' . $authToken); return $auth; } private function authInfo($auth, $createUser = false) { if (!in_array($auth['type'] ?? '', ['wechat', 'routine', 'apple', 'app_wechat']) || !isset($auth['auth'])) throw new ValidateException('授权信息类型有误'); $data = $auth['auth']; if ($auth['type'] === 'routine') { $code = $data['code'] ?? ''; $userInfoCong = Cache::get('eb_api_code_' . $code); if (!$code && !$userInfoCong) throw new ValidateException('授权失败,参数有误'); $miniProgramService = MiniProgramService::create(); if ($code && !$userInfoCong) { try { $userInfoCong = $miniProgramService->getUserInfo($code); Cache::set('eb_api_code_' . $code, $userInfoCong, 86400); } catch (Exception $e) { throw new ValidateException('获取session_key失败,请检查您的配置!'); } } try { //解密获取用户信息 $userInfo = $miniProgramService->encryptor($userInfoCong['session_key'], $data['iv'], $data['encryptedData']); } catch (Exception $e) { if ($e->getCode() == '-41003') throw new ValidateException('获取会话密匙失败'); throw $e; } if (!$userInfo) throw new ValidateException('openid获取失败'); if (!isset($userInfo['openId'])) $userInfo['openId'] = $userInfoCong['openid'] ?? ''; $userInfo['unionId'] = $userInfoCong['unionid'] ?? $userInfo['unionId'] ?? ''; if (!$userInfo['openId']) throw new ValidateException('openid获取失败'); /** @var WechatUserRepository $make */ $make = app()->make(WechatUserRepository::class); $user = $make->syncRoutineUser($userInfo['openId'], $userInfo, $createUser); if (!$user) throw new ValidateException('授权失败'); return $user; } else if ($auth['type'] === 'wechat') { $request = $this->request; $oauth = WechatService::create()->getApplication()->oauth; $oauth->setRequest(new Request($data, $data, [], [], [], $request->server(), $request->getContent())); try { $wechatInfo = $oauth->user()->getOriginal(); } catch (Exception $e) { throw new ValidateException('授权失败[001]'); } if (!isset($wechatInfo['nickname'])) { throw new ValidateException('授权失败[002]'); } /** @var WechatUserRepository $make */ $make = app()->make(WechatUserRepository::class); $user = $make->syncUser($wechatInfo['openid'], $wechatInfo, false, $createUser); if (!$user) throw new ValidateException('授权失败[003]'); return $user; } else if ($auth['type'] === 'app_wechat') { $oauth = WechatService::create()->getApplication()->oauth; try { $wechatInfo = $oauth->user(new AccessToken(['access_token'=>$data['code'],'openid'=>$data['openid']]))->getOriginal(); } catch (Exception $e) { throw new ValidateException('授权失败[001]'.$e->getMessage()); } $user = app()->make(WechatUserRepository::class)->syncAppUser($wechatInfo['unionid'], $wechatInfo, 'App', $createUser); if (!$user) throw new ValidateException('授权失败'); return $user; } else if ($auth['type'] === 'apple') { $identityToken = $data['userInfo']['identityToken']; $tks = explode('.', $identityToken); if (count($tks) != 3) { throw new ValidateException('Wrong number of segments'); } list($headb64, $bodyb64, $cryptob64) = $tks; if (null === ($payload = JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64)))) { throw new ValidateException('Invalid header encoding'); } if($payload->sub != $data['openId']){ throw new ValidateException('授权失败'); } $user = app()->make(WechatUserRepository::class)->syncAppUser($data['openId'], [ 'nickName' => (string)$data['nickname'] ?: '用户' . strtoupper(substr(md5(time()), 0, 12)) ], 'App', $createUser); if (!$user) throw new ValidateException('授权失败'); return $user; } } public function authLogin() { $auth = $this->request->param('auth'); $users = $this->authInfo($auth, systemConfig('is_phone_login') !== '1'); if (!$users) return app('json')->fail('授权失败'); $authInfo = $users[0]; $userRepository = app()->make(UserRepository::class); $user = $users[1] ?? $userRepository->wechatUserIdBytUser($authInfo['wechat_user_id']); $code = (int)($auth['auth']['spread_code']['id'] ?? $auth['auth']['spread_code'] ?? ''); //获取是否有扫码进小程序 if ($code && ($info = app()->make(RoutineQrcodeRepository::class)->getRoutineQrcodeFindType($code))) { $auth['auth']['spread'] = $info['third_id']; } if (!$user) { $uni = uniqid(true, false) . random_int(1, 100000000); $key = 'U' . md5(time() . $uni); Cache::set('u_try' . $key, ['id' => $authInfo['wechat_user_id'], 'type' => $authInfo['user_type'], 'spread' => $auth['auth']['spread'] ?? 0], 3600); return app('json')->status(201, compact('key')); } if ($auth['auth']['spread'] ?? 0) { $userRepository->bindSpread($user, (int)($auth['auth']['spread'])); } $tokenInfo = $userRepository->createToken($user); $userRepository->loginAfter($user); return app('json')->status(200, $userRepository->returnToken($user, $tokenInfo)); } /** * App微信登陆 * @param Request $request * @return mixed */ public function appAuth() { $data = $this->request->params(['userInfo']); if (systemConfig('is_phone_login') === '1') { return app('json')->fail('请绑定手机号'); } $user = app()->make(WechatUserRepository::class)->syncAppUser($data['userInfo']['unionId'], $data['userInfo']); if (!$user) return app('json')->fail('授权失败'); /** @var UserRepository $make */ $userRepository = app()->make(UserRepository::class); $user[1] = $userRepository->mainUser($user[1]); $tokenInfo = $userRepository->createToken($user[1]); $userRepository->loginAfter($user[1]); return app('json')->success($userRepository->returnToken($user[1], $tokenInfo)); } public function getMerCertificate($merId) { $merId = (int)$merId; $data = $this->request->params(['key', 'code']); if (!$this->checkCaptcha($data['key'], $data['code'])) return app('json')->fail('验证码输入有误'); $certificate = merchantConfig($merId, 'mer_certificate') ?: []; if (!count($certificate)) return app('json')->fail('该商户未上传证书'); return app('json')->success($certificate); } public function appleAuth() { $data = $this->request->params(['openId', 'nickname']); if (systemConfig('is_phone_login') === '1') { return app('json')->fail('请绑定手机号'); } $user = app()->make(WechatUserRepository::class)->syncAppUser($data['openId'], [ 'nickName' => (string)$data['nickname'] ?: '用户' . strtoupper(substr(md5(time()), 0, 12)) ], 'apple'); if (!$user) return app('json')->fail('授权失败'); /** @var UserRepository $make */ $userRepository = app()->make(UserRepository::class); $user[1] = $userRepository->mainUser($user[1]); $tokenInfo = $userRepository->createToken($user[1]); $userRepository->loginAfter($user[1]); return app('json')->success($userRepository->returnToken($user[1], $tokenInfo)); } /** * 注销账号 */ public function cancel() { $userRepository = app()->make(UserRepository::class); $user = $this->request->userInfo(); $order = app()->make(StoreOrderRepository::class)->search(['uid' => $user['uid'], 'paid' => 1])->where('StoreOrder.status', 0)->count(); $refund = app()->make(StoreRefundOrderRepository::class)->search(['uid' => $user['uid'], 'type' => 1])->count(); $key = $this->request->param('key'); $flag = false; if ($user->now_money > 0 || $user->integral > 0 || $order > 0 || $refund > 0) { $flag = true; if (!$key) { $uni = uniqid(true, false) . random_int(1, 100000000); $key = 'L' . md5(time() . $uni); Cache::set('u_out' . $user['uid'], $key, 600); return app('json')->status(201, '该账号下有未完成业务,注销后不可恢复,您确定继续注销?', compact('key')); } } if ($flag && (!$key || (Cache::get('u_out' . $user['uid']) != $key))) { return app('json')->fail('操作超时'); } $userRepository->cancel($user); $userRepository->clearToken($user); return app('json')->status(200, '注销成功'); } public function mpPhone() { $code = $this->request->param('code'); $auth_token = $this->request->param('auth_token'); $iv = $this->request->param('iv'); $encryptedData = $this->request->param('encryptedData'); $miniProgramService = MiniProgramService::create(); $userInfoCong = Cache::get('eb_api_code_' . $code); if (!$code && !$userInfoCong) throw new ValidateException('授权失败,参数有误'); if ($code && !$userInfoCong) { try { $userInfoCong = $miniProgramService->getUserInfo($code); Cache::set('eb_api_code_' . $code, $userInfoCong, 86400); } catch (Exception $e) { throw new ValidateException('获取session_key失败,请检查您的配置!'); } } $session_key = $userInfoCong['session_key']; $data = $miniProgramService->encryptor($session_key, $iv, $encryptedData); $userRepository = app()->make(UserRepository::class); $phone = $data['purePhoneNumber']; $user = $userRepository->accountByUser($phone); // if($user && $auth_token){ // return app('json')->fail('用户已存在'); // } $auth = $this->parseAuthToken($auth_token); if ($user && $auth) { $userRepository->syncBaseAuth($auth, $user); } else if (!$user) { if (!$auth) { return app('json')->fail('操作超时'); } $wechatUser = app()->make(WechatUserRepository::class)->get($auth['id']); $user = $userRepository->syncWechatUser($wechatUser, 'routine'); $user->phone = $phone; $user->account = $phone; $user->save(); if ($auth['spread']) { $userRepository->bindSpread($user, $auth['spread']); } } $tokenInfo = $userRepository->createToken($user); $userRepository->loginAfter($user); return app('json')->success($userRepository->returnToken($user, $tokenInfo)); } /** * @return mixed */ public function ajcaptcha() { $captchaType = $this->request->get('captchaType'); if (!$captchaType) return app('json')->fail('请输入类型'); return app('json')->success(aj_captcha_create($captchaType)); } /** * 一次验证 * @return mixed */ public function ajcheck() { $token = $this->request->param('token',''); $pointJson = $this->request->param('pointJson',''); $captchaType = $this->request->param('captchaType',''); try { aj_captcha_check_one($captchaType, $token, $pointJson); return app('json')->success(); } catch (\Throwable $e) { return app('json')->fail(400336); } } }