1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081 |
- <?php
- /**
- * Created by PhpStorm.
- * User: Bear
- * Date: 2018/12/3
- * Time: 下午4:13
- */
- namespace app\main\service;
- use app\common\library\Redis;
- use app\common\model\Referral;
- use app\common\utility\WhiteList;
- use app\main\constants\AdminConstants;
- use app\main\constants\ApiConstants;
- use app\main\constants\ErrorCodeConstants;
- use app\main\constants\KafkaDotConstants;
- use app\main\constants\MarkConstants;
- use app\main\constants\MqConstants;
- use app\main\constants\OpenPlatformConstants;
- use app\main\constants\UrlConstants;
- use app\main\constants\UserConstants;
- use app\main\helper\ArrayHelper;
- use app\main\model\object\AnalysisObject;
- use app\main\model\object\DotObject;
- use app\main\model\object\UserObject;
- use think\Config;
- use think\Cookie;
- use think\Env;
- use think\Request;
- /**
- * 处理url信息
- * Class UrlService
- * @package app\main\service
- */
- class UrlService extends BaseService
- {
- /**
- * @var UrlService
- */
- protected static $self = NULL;
- private $domain;
- /**
- * @return UrlService
- */
- public static function instance()
- {
- if (self::$self == NULL) {
- self::$self = new self();
- }
- return self::$self;
- }
- /**
- * @return Referral
- */
- public function getReferralModel()
- {
- return model('Referral');
- }
- public function checkApiDomain()
- {
- try{
- $channel_id = Request::instance()->get('channel_id');
- if(!$channel_id){
- $channel_id = Cookie::get('channel_id');
- }
- UserService::instance()->getRunTimeObject()->channelId = $channel_id;
- $host = $this->getSourceDomain();
- UserService::instance()->getRunTimeObject()->sourceDomain = $host;
- UserService::instance()->getRunTimeObject()->currentPayHost = $host;
- $mWeixin = OfficialAccountsService::instance()->getWxpayModel();
- $mOphost = OfficialAccountsService::instance()->getOphostModel();
- $hosts = $mOphost->getHosts();
- LogService::info('API_LOG Source Domain:'.$host);
- LogService::info('API_LOG Ophost:'.var_export($hosts,true));
- if ($this->checkDomainIsPay()) { //支付域名
- UserService::instance()->getRunTimeObject()->urlType = OpenPlatformConstants::URL_TYPE_PAY;
- /*
- * 动态初始化微信商户服务号参数
- */
- $arr = Config::get('wechat.http'); // 修正充值API
- $arr['base_uri'] = 'https://api.mch.weixin.qq.com/'; // 修正充值API
- Config::set('wechat.http', $arr);
- $pay_hosts = $mWeixin->getInfoByHost($host);
- $payInfo = $mWeixin->getInfo($pay_hosts['platform_id'],$pay_hosts['id']);
- Config::set('wechat.app_id', $payInfo['appid']);
- Config::set('wechat.secret', $payInfo['secret']);
- Config::set('wechat.mch_id', $payInfo['mcid']);
- Config::set('wechat.key', $payInfo['apikey']);
- Config::set('wechat.platform_id', $payInfo['platform_id']);
- LogService::info('API_LOG INIT - PAY Default');
- }elseif($appid = $this->checkDomainIsReferral()){
- $channelData = AdminService::instance()->getAdminConfigModel()->getAdminInfoByAppId($appid); //$matches[0] appid
- if ($channelData) {
- UserService::instance()->getRunTimeObject()->agentId = $this->getUserAgentId()->data;
- UserService::instance()->getRunTimeObject()->channelId = UserService::instance()->getUserInfo()->channel_id;
- UserService::instance()->getRunTimeObject()->adminId = UserService::instance()->getAdminId()->data;
- UserService::instance()->getRunTimeObject()->urlType = OpenPlatformConstants::URL_TYPE_SPREAD;
- //根据域名获取平台信息
- $hostArr = explode(".", $host);
- array_shift($hostArr);
- $topHost = implode(".", $hostArr);
- if($topHost == $channelData['menu_ophost_host']){
- $platform_info = OpenPlatformService::instance()->getPlatformModel()->getInfo($channelData['menu_platform_id']);
- Config::set('wechat.app_id', $platform_info['appid']);
- Config::set('wechat.secret', $platform_info['secret']);
- Config::set('wechat.token', $platform_info['token']);
- Config::set('wechat.aes_key', $platform_info['aes_key']);
- Config::set('wechat.platform_id', $channelData['menu_platform_id']);
- }else{
- Config::set('wechat.app_id', $channelData['platform_appid']);
- Config::set('wechat.secret', $channelData['platform_secret']);
- Config::set('wechat.token', $channelData['platform_token']);
- Config::set('wechat.aes_key',$channelData['platform_aes_key']);
- Config::set('wechat.platform_id', $channelData['platform_id']);
- }
- LogService::info('API_LOG WeChatAPPID Default');
- }
- }elseif(in_array($host,$hosts)){
- if($ophost = $mOphost->getInfoByHost($host)){
- $platformData = OpenPlatformService::instance()->getPlatformModel()->getInfo($ophost['platform_id']);
- Config::set('wechat.app_id', $platformData['appid']);
- Config::set('wechat.secret', $platformData['secret']);
- Config::set('wechat.token', $platformData['token']);
- Config::set('wechat.aes_key',$platformData['aes_key']);
- Config::set('wechat.platform_id', $ophost['platform_id']);
- LogService::info('API_LOG Platform:'.var_export($platformData,true));
- } else {
- LogService::info('API_LOG 未匹配到域名信息:' . $host . ':' . json_encode($hosts));
- }
- }
- return $this->getReturn();
- }catch (\Exception $e){
- return $this->getExceptionReturn($e);
- }
- }
- /**
- * 删除www.及callback前缀
- * @return bool|null|string|string[]
- */
- public function getSourceDomain()
- {
- if (!$this->domain) {
- $host = get_host_no_port();
- $host = preg_replace('/^www\./', '', $host);
- $host = preg_replace('/^open\./', '', $host);
- $this->domain = preg_replace('/^' . ApiConstants::PAY_CALLBACK_PREFIX . '/', '', $host);
- }
- return $this->domain;
- }
- /**
- * 域名检查
- * @return \app\main\model\object\ReturnObject|UrlService
- */
- public function checkFrontDomain()
- {
- if (UrlService::instance()->checkDomainIsPay()) { //支付域名
- $result = UrlService::instance()->checkFrontPayHost();
- } elseif (UrlService::instance()->checkDomainIsEntry()) { //入口域名
- $result = UrlService::instance()->checkFrontEntryHost();
- } elseif (UrlService::instance()->checkDomainIsReferral()) { //判断是否为推广域名
- $result = UrlService::instance()->checkFrontReferralHost();
- }elseif( UrlService::instance()->checkDomainIsShare() ){ //检测是不是分享活动域名
- $result = UrlService::instance()->checkShareHost();
- } else {
- UserService::instance()->getRunTimeObject()->urlType = OpenPlatformConstants::URL_TYPE_ADMIN;
- $result = $this->getReturn();
- }
- return $result;
- }
- /**
- * 检查域名是支付域名
- * @return bool
- */
- public function checkDomainIsPay()
- {
- $host = $this->getSourceDomain();
- $payHosts = OfficialAccountsService::instance()->getWxpayModel()->getHosts();
- return in_array($host, $payHosts);
- }
- /**
- * 检查域名是入口域名
- * @return bool
- */
- public function checkDomainIsEntry()
- {
- $host = get_host_no_port();
- $entryHosts = OfficialAccountsService::instance()->getEntryHostModel()->getHosts();
- return in_array($host, $entryHosts);
- }
- /**
- * 检查域名是入口域名
- * @return bool
- */
- public function checkDomainIsReferral()
- {
- $host = get_host_no_port();
- if(preg_match("/^wx\w+/i", $host, $matches)){
- return $matches[0];
- }
- if(preg_match("/^px-\w{5}-(wx\w+)-/i", $host, $matches)){
- return $matches[1];
- }
- return "";
- }
- /**
- * @return bool
- */
- public function checkDomainIsShare()
- {
- $host = get_host_no_port();
- return (bool)strstr(Config::get('site.share_domain'),$host);
- }
- /**
- * 处理支付域名逻辑
- * @return \app\main\model\object\ReturnObject
- */
- public function checkFrontPayHost()
- {
- UserService::instance()->getRunTimeObject()->urlType = OpenPlatformConstants::URL_TYPE_PAY;
- try {
- $site = Config::get("site");
- $host = get_host_no_port();
- //如果是支付域名并且不是Ajax请求清空Cookie,以防JS获取错误参数
- if (!Request::instance()->isAjax()) {
- foreach ($_COOKIE as $key => $val) {
- if (in_array($key, ['user_id', 'openid', 'open_id', 'app_id'])) {
- continue;
- } else {
- Cookie::set($key, null);
- }
- }
- }
- //todo user缓存的设置
- UserService::instance()->setUserCache(Request::instance()->get('user_id'));
- $urlAdminId = UserService::instance()->getAdminId()->data;
- $urlChannelId = UserService::instance()->getUserInfo()->channel_id;
- if (!$urlAdminId) {
- return $this->setData($site['scheme'] . '://' . $site['url_root'])->setCode(ErrorCodeConstants::REDIRECT)->getReturn();
- }
- $configData = AdminService::instance()->getAdminConfigModel()->getAdminInfoAll($urlChannelId);
- //检测支付域名是否一致,如果支付域名不一致,重新跳转到对的支付域名,如果是自定义菜单支付域名时不用跳转
- if (!FufenService::instance()->checkTestParams()->data && $configData['wxpay_pay_host'] != $host) {
- //为true需要跳转
- $isDiyPayHost = true;
- if ($configData['menuwxpay_host'] == $host) {
- $isDiyPayHost = false;
- } else {
- if (FufenService::instance()->checkWxpayHostIsFufen($host)->data) {
- $isDiyPayHost = false;
- }
- }
- if ($isDiyPayHost) {
- $agent_id = $this->getUserAgentId()->data;
- if ($agent_id) {
- $url = parse_url(get_url_no_port());
- if (isset($url['query'])) {
- $params = $this->getUrlParams($url['query'] ?? '');
- } else {
- $params = [];
- }
- $params['agent_id'] = $agent_id;
- if (isset($params['code'])) {
- unset($params['code']);
- }
- $redirectUrl = $site['scheme'] . '://' . $configData['wxpay_pay_host'] . $url['path'] ?? '/';
- if (!empty($params)) {
- $redirectUrl = $redirectUrl . '?' . http_build_query($params);
- }
- return $this->setData($redirectUrl)->setCode(ErrorCodeConstants::REDIRECT)->getReturn();
- } else {
- $redirectUrl = $site['scheme'] . '://' . $configData['wxpay_pay_host'] . get_url_no_port();
- $redirect = $this->removeUrlParam('code', $redirectUrl);
- return $this->setData($redirect)->setCode(ErrorCodeConstants::REDIRECT)->getReturn();
- }
- }
- }
- Cookie::forever('channel_id', $urlChannelId);
- UserService::instance()->getRunTimeObject()->adminId = $urlAdminId;
- UserService::instance()->getRunTimeObject()->channelId = $urlChannelId;
- return $this->getReturn();
- } catch (\Exception $e) {
- return $this->getExceptionReturn($e);
- }
- }
- /**
- * 处理分享活动域名
- * @return \app\main\model\object\ReturnObject
- */
- public function checkShareHost()
- {
- // UserService::instance()->getRunTimeObject()->urlType = 3;
- try {
- $site = Config::get("site");
- if (!Request::instance()->isAjax()) {
- foreach ($_COOKIE as $key => $val) {
- if (in_array($key, ['user_id', 'openid', 'open_id', 'app_id'])) {
- continue;
- } else {
- Cookie::set($key, null);
- }
- }
- }
- //todo user缓存的设置
- UserService::instance()->setUserCache(Request::instance()->get('user_id'));
- $urlAdminId = UserService::instance()->getAdminId()->data;
- $urlChannelId = UserService::instance()->getUserInfo()->channel_id;
- if (!$urlAdminId) {
- return $this->setData($site['scheme'] . '://' . $site['url_root'])->setCode(ErrorCodeConstants::REDIRECT)->getReturn();
- }
- AdminService::instance()->getAdminConfigModel()->getAdminInfoAll($urlChannelId);
- Cookie::forever('channel_id', $urlChannelId);
- UserService::instance()->getRunTimeObject()->adminId = $urlAdminId;
- UserService::instance()->getRunTimeObject()->channelId = $urlChannelId;
- return $this->getReturn();
- } catch (\Exception $e) {
- return $this->getExceptionReturn($e);
- }
- }
- /**
- * 入口域名处理方法
- * @return \app\main\model\object\ReturnObject
- */
- public function checkFrontEntryHost()
- {
- try {
- $site = Config::get("site");
- $channel_id = Request::instance()->get('channel_id');
- if (!$channel_id) { //如果没带渠道商,归到自己渠道商上
- //先用kl的测试
- $klChannelIds = $site['change_ids'] ?? false;
- if ($klChannelIds) {
- $arrchange = explode(',', $klChannelIds);
- $channel_id = $arrchange[array_rand($arrchange, 1)];
- $configData = AdminService::instance()->getAdminConfigModel()->getAdminInfoAll($channel_id);
- if (!empty($configData)) {
- $redirectUrl = Config::get('site.scheme') . '://' . $configData['appid'] . '.' . $configData['ophost_host'] . get_url_no_port();
- $this->setData($redirectUrl)->setCode(ErrorCodeConstants::REDIRECT);
- } else {
- $this->setData($site['scheme'] . '://' . $site['url_root'])->setCode(ErrorCodeConstants::REDIRECT);
- }
- }
- } else { //如果有channel_id
- //获取该渠道商配置信息
- $configData = AdminService::instance()->getAdminConfigModel()->getAdminInfoAll($channel_id);
- if (!empty($configData)) {
- $redirectUrl = Config::get('site.scheme') . '://' . $configData['appid'] . '.' . $configData['ophost_host'] . get_url_no_port();
- $this->setData($redirectUrl)->setCode(ErrorCodeConstants::REDIRECT);
- } else {
- $this->setData($site['scheme'] . '://' . $site['url_root'])->setCode(ErrorCodeConstants::REDIRECT);
- }
- }
- return $this->getReturn();
- } catch (\Exception $e) {
- return $this->getExceptionReturn($e);
- }
- }
- /**
- * 处理推广链接
- * @return $this|\app\main\model\object\ReturnObject
- */
- public function checkFrontReferralHost()
- {
- UserService::instance()->getRunTimeObject()->urlType = OpenPlatformConstants::URL_TYPE_SPREAD;
- $result = UrlService::instance()->unlimitSecondaryDomain();
- if ($result->code != ErrorCodeConstants::SUCCESS) {
- return $result;
- }
- $host = get_host_no_port();
- $appId = $this->checkDomainIsReferral();
- $site = Config::get("site");
- try{
- if ($appId) {
- UserService::instance()->getRunTimeObject()->appId = $appId;
- $channelData = AdminService::instance()->getAdminConfigModel()->getAdminInfoByAppId($appId); //得到此渠道的配置信息 adminInfoAll
- $admin_id = $channelData['admin_id'];
- $hostArr = explode('.', $host);
- array_shift($hostArr);
- $agent_id = $this->getUserAgentId()->data;
- //跳转默认业务域名,如果推广域名和当前渠道商业务域名不一样,如果是自定义菜单域名时不用跳转
- if (strpos($host,'px-') !== 0 && implode('.', $hostArr) != $channelData['ophost_host']) {
- $isDiyMenu = true;
- if (isset($channelData['menuophost']) && $channelData['menuophost'] == implode('.', $hostArr)) {
- $isDiyMenu = false;
- }
- if ($isDiyMenu) {
- if ($agent_id) {
- $url = parse_url(get_url_no_port());
- if (isset($url['query'])) {
- $params = $this->getUrlParams($url['query'] ?? '');
- } else {
- $params = [];
- }
- $params['agent_id'] = $agent_id;
- if (isset($params['code'])) {
- unset($params['code']);
- }
- $redirectUrl = $site['scheme'] . '://' . $appId . '.' . $channelData['ophost_host'] . $url['path'] ?? '/';
- if (!empty($params)) {
- $redirectUrl = $redirectUrl . '?' . http_build_query($params);
- }
- $this->setData($redirectUrl)->setCode(ErrorCodeConstants::REDIRECT);
- } else {
- $redirectUrl = $site['scheme'] . '://' . $appId . '.' . $channelData['ophost_host'] . get_url_no_port();
- $this->setData($redirectUrl)->setCode(ErrorCodeConstants::REDIRECT);
- }
- return $this->getReturn();
- }
- }
- UserService::instance()->getRunTimeObject()->channelId = $admin_id;
- UserService::instance()->getRunTimeObject()->adminId = $agent_id ?: $admin_id;
- UserService::instance()->getRunTimeObject()->referralId = $this->getUserReferralId()->data;
- //设置推广id和代理商id
- UrlService::instance()->setUserAgentId((int)Request::instance()->get('agent_id'));
- UrlService::instance()->setUserReferralId((int)Request::instance()->get('referral_id'));
- } else {
- $redirectUrl = $site['scheme'] . '://' . $site['url_root'];
- return $this->setData($redirectUrl)->setCode(ErrorCodeConstants::REDIRECT)->getReturn();
- }
- return $this->getReturn();
- }catch (\Exception $e){
- return $this->getExceptionReturn($e);
- }
- }
- /**
- * 删除URL指定参数
- * @param $paramNames
- * @param $url
- * @return string
- */
- public function removeUrlParam($paramNames, $url)
- {
- $paramNames = (array)$paramNames;
- $arr = [];
- if (strpos($url, "?")) {
- $urlInfo = explode("?", $url);
- parse_str($urlInfo[1], $arr);
- foreach ($paramNames as $name) {
- if (array_key_exists($name, $arr)) {
- unset($arr[$name]);
- }
- }
- return $urlInfo[0] . "?" . http_build_query($arr);
- }
- return $url;
- }
- /**
- * 推广链接处理
- * @throws \Exception
- */
- public function processReferral()
- {
- $urlType = UserService::instance()->getRunTimeObject()->urlType;
- $bookId = Request::instance()->get('book_id');
- $urlAgentId = $this->getUserAgentId()->data;
- $urlChannelId = UserService::instance()->getRunTimeObject()->channelId;
- $userId = UserService::instance()->getUserInfo()->id;
- $site = Config::get("site");
- //书籍屏蔽
- if ($bookId && $urlType != OpenPlatformConstants::URL_TYPE_ADMIN) {
- $isLimited = BookService::instance()->getBookLimit()->hasLimit($urlAgentId, $urlChannelId, $bookId, $userId);
- if ($isLimited) {
- return $this->setData(UrlConstants::get_page_404())->setCode(ErrorCodeConstants::REDIRECT)->getReturn();
- }
- }
- /**
- * 处理推广链接UV
- */
- if ($urlType == OpenPlatformConstants::URL_TYPE_SPREAD && ($referral_id = Request::instance()->get('referral_id')) && UserService::instance()->isLogin()) {
- //添加推广链接用户白名单
- WhiteList::addReferralUser($referral_id, UserService::instance()->getUserInfo()->id);
- $dotData = new DotObject();
- $dotData->action_type = MqConstants::ROUTING_KEY_REFERRAL_UV;
- $dotData->referral_id = $referral_id;
- $dotData->user_id = UserService::instance()->getUserInfo()->id;
- $dotData->event_time = UserService::instance()->getRunTimeObject()->requestTime;
- MqService::instance()->sendMessage($dotData);
- $oAna = new AnalysisObject();
- $oAna->type = KafkaDotConstants::TYPE_VISIT;
- $oAna->event_time = $dotData->event_time;
- $oAna->user_from = [
- 'referral_id' => $referral_id
- ];
- KafkaDotService::instance()->sendMsg($userId, $oAna);
- }
- //推广链接禁用时,跳转到首页
- if ($urlType == OpenPlatformConstants::URL_TYPE_SPREAD && Request::instance()->has('referral_id')) {
- if ($referral = UrlService::instance()->getReferralModel()->getone((int)Request::instance()->param('referral_id'), false)) {
- if (is_array($referral) && isset($referral['state']) && !$referral['state']) {
- $redirect = $site['scheme'] . '://' . $_SERVER['HTTP_HOST'] . '/index/index';
- return $this->setData($redirect)->setCode(ErrorCodeConstants::REDIRECT)->getReturn();
- }
- }
- }
- //如果是302短链,跳转对应域名
- if ($urlType == OpenPlatformConstants::URL_TYPE_SPREAD && Request::instance()->has('referral_id') && Request::instance()->has('short_id') && Request::instance()->has('re')) {
- if ($referral = UrlService::instance()->getReferralModel()->getone((int)Request::instance()->param('referral_id'), false)) {
- if (in_array($referral['type'], [UrlConstants::REFERRAL_READING_PAGE_SPREAD, UrlConstants::REFERRAL_GROUND_PAGE_SPREAD]) && !intval($referral['push'])) { //阅读页与落地页推广时跳,并且是外派
- $re_params = Request::instance()->param();
- if (isset($re_params['short_id'])) {
- unset($re_params['short_id']);
- }
- if (isset($re_params['re'])) {
- unset($re_params['re']);
- }
- $re_params['user_id'] = UserService::instance()->getUserInfo()->id;
- $re_params['open_id'] = UserService::instance()->getUserInfo()->openid;
- $redirect = Request::instance()->param('re') . '/index/book/chapter?' . http_build_query($re_params);
- return $this->setData($redirect)->setCode(ErrorCodeConstants::REDIRECT)->getReturn();
- }
- }
- }
- return $this->getReturn();
- }
- /**
- * 获取URL参数
- * @param $query
- * @return array
- */
- function getUrlParams($query)
- {
- $queryParts = explode('&', $query);
- $params = [];
- if ($queryParts) {
- foreach ($queryParts as $param) {
- $item = explode('=', $param);
- $params[$item[0]] = $item[1];
- }
- }
- return $params;
- }
- public function getActionUrl()
- {
- $moduleName = Request::instance()->module();
- $controllerName = strtolower(Request::instance()->controller());
- $actionName = strtolower(Request::instance()->action());
- $urlAction = $moduleName . '/' . $controllerName . '/' . $actionName; //当前访问模块链接
- return UserService::instance()->getRunTimeObject()->urlAction = $urlAction;
- }
- /**
- * 检测action
- * @param $list
- * @return bool
- */
- public function checkActionMatch($list)
- {
- $list = (array)$list;
- $action = Request::instance()->action();
- return ArrayHelper::match($action, $list);
- }
- /**
- * @param $bookId
- * @param $chapterId
- * @param string $referralId
- * @return bool
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- */
- public function checkIfDaoFen($bookId, $chapterId, $referralId = '')
- {
- $dofenChapter = Config::get('site.book_guide_chapter_idx');
- if($referralId){
- $dofenChapter = $this->getReferralModel()->getDaoFenChapterId($referralId);
- }
- $book = BookService::instance()->getBookModel()->where('id', '=', $bookId)->find();
- if($book && $book['attent_chapter_order']){
- $dofenChapter = $book['attent_chapter_order'];
- }
- return $dofenChapter <= $chapterId;
- }
- public function getPayUrl($redirect, $book_id, $chapter_id){
- $admin_info = UserService::instance()->getRunTimeObject()->adminConfig;
- $runtime = UserService::instance()->getRunTimeObject();
- $params['redirect'] = $redirect;
- $params['admin_id'] = $runtime->adminId;
- $params['channel_id'] = $runtime->channelId;
- if ($user_id = UserService::instance()->getUserInfo()->id) {
- $params['user_id'] = $user_id;
- } elseif (Cookie::has('visitor')) {
- $params['visitor'] = Cookie::get('visitor');
- }
- if (Cookie::has('referral_id')) {
- $params['referral_id'] = Cookie::get('referral_id');
- }
- $params['book_id'] = $book_id;
- $params['chapter_id'] = $chapter_id;
- //有菜单支付域名时,跳转菜单支付域名
- $menuophost = $admin_info['menuophost'] ?? null;
- $menuwxpay_host = $admin_info['menuwxpay_host'] ?? null;
- if ($menuophost && $menuwxpay_host && $menuophost == getCurrentOphost()) {
- return $this->setData(Config::get('site.scheme') . '://' . $admin_info['menuwxpay_host'] . '/index/recharge/pay?' . http_build_query($params))->getReturn();
- } else {
- return $this->setData(Config::get('site.scheme') . '://' . $admin_info['wxpay_pay_host'] . '/index/recharge/pay?' . http_build_query($params))->getReturn();
- }
- }
- /**
- * 设置代理商ID
- * @param $requestAgentId
- * @return \app\main\model\object\ReturnObject
- */
- public function setUserAgentId($requestAgentId)
- {
- if (!$requestAgentId || !UserService::instance()->isLogin()) {
- return $this->getReturn();
- }
- try {
- //登录状态
- $channel_id = UserService::instance()->getUserInfo()->channel_id;
- $user = UserService::instance()->getUserInfo(true);
- $checkBelongs = AdminService::instance()->checkAgentIdBelongsToChannelId($requestAgentId, $channel_id)->data;
- if($checkBelongs && $user->agent_id != $requestAgentId){
- $update = ['agent_id' => $requestAgentId];
- UserService::instance()->update($update, ['id' => $user->id]);
- // UserService::instance()->getUserModel()->setConnect($user->id)->update($update, ['id' => $user->id]);
- // UserService::instance()->updateRedisUserCache($user->id, $update);
- }
- } catch (\Exception $e) {
- LogService::exception($e);
- }
- return $this->getReturn();
- }
- /**
- * 设置推广ID
- * @param $requestReferralId
- * @return \app\main\model\object\ReturnObject
- */
- public function setUserReferralId($requestReferralId)
- {
- $user = UserService::instance()->getUserInfo();
- if (!$requestReferralId || !UserService::instance()->isLogin() || $requestReferralId == $user->referral_id) {
- return $this->getReturn();
- }
- try {
- $update = $this->getUserReferralIdUpdate($requestReferralId)->data;
- if ($update) {
- UserService::instance()->update($update, ['id' => $user->id]);
- // UserService::instance()->getUserModel()->setConnect($user->id)->update($update, ['id' => $user->id]);
- // UserService::instance()->updateRedisUserCache($user->id, $update);
- }
- } catch (\Exception $e) {
- return $this->getExceptionReturn($e);
- }
- return $this->getReturn();
- }
- /**
- * @param $requestReferralId
- * @return \app\main\model\object\ReturnObject
- */
- public function getUserReferralIdUpdate($requestReferralId)
- {
- $checkBelongs = AdminService::instance()->checkReferralIdBelongsToChannelId($requestReferralId)->data;
- $update = [];
- if($checkBelongs){
- $referral_id_permanent = UserService::instance()->getUserInfo()->referral_id_permanent;
- $referral_id = UserService::instance()->getUserInfo()->referral_id;
- $update = [];
- if ($requestReferralId != $referral_id) {
- $update = [
- 'referral_id' => $requestReferralId,
- ];
- }
- if ($this->checkCustomExtReferralMatch()->data && !$this->checkCustomExtReferralMatch('', $requestReferralId)->data) {
- $update['ext'] = '';
- }
- $referral_info_request = UrlService::instance()->getReferralModel()->getone($requestReferralId, false);
- if ($referral_id_permanent) {
- $referral_info_permanent = UrlService::instance()->getReferralModel()->getone($referral_id_permanent, false);
- } else {
- $referral_info_permanent = false;
- }
- $referral_info = UrlService::instance()->getReferralModel()->getone($referral_id, false);
- //没有推广信息的情况
- if(!$referral_info_permanent && !$referral_info){
- $update['referral_id_permanent'] = $requestReferralId;
- //没有推广信息时处理关注打点
- $user = UserService::instance()->getUserInfo();
- if ($ext = Request::instance()->param('ext')) {
- $ext_data = json_decode($ext, true);
- $referral = UrlService::instance()->getReferralModel()->getone($requestReferralId, false);
- if ($ext_data['mark'] == MarkConstants::MARK_RESOURCE && ($user->is_subscribe || $user->subscription_extend) && $referral['push'] == UrlConstants::REFERRAL_PUSH_OUT && time() - $user->createtime < 1200) {
- $dotData = new DotObject();
- //打点信息初始化
- $dotData->channel_id = $user->channel_id;
- $dotData->user_id = $user->id;
- $dotData->event_time = $user->subscribe_time;
- if ($user->is_first_unfollow != UserConstants::USER_IS_FIRST_UNFOLLOW_NEVER) {
- $dotData->is_first_follow = UserConstants::USER_IS_FIRST_FOLLOW_NO;
- } else {
- $dotData->is_first_follow = UserConstants::USER_IS_FIRST_FOLLOW_YES;
- }
- $dotData->action_type = MqConstants::ROUTING_KEY_SUBSCRIBE_REFERER;
- $dotData->type = MqConstants::MSG_TYPE_FOLLOW;
- $dotData->referral_id = $requestReferralId;
- MqService::instance()->sendMessage($dotData);
- $oAna = new AnalysisObject();
- $oAna->type = KafkaDotConstants::TYPE_SUBSCRIBE;
- $oAna->user_from = [
- 'referral_id' => $requestReferralId
- ];
- $oAna->event_time = $user->subscribe_time;
- KafkaDotService::instance()->sendMsg($user->id, $oAna);
- }
- }
- }else{
- //$checkBelongs判断通过,则推广链接一定存在
- $requestGroupId = AdminService::instance()->getAuthGroupAccessModel()->getGroupId($referral_info_request['admin_id']);
- $permanentGroupId = false;
- if ($referral_info_permanent) {
- $permanentGroupId = AdminService::instance()->getAuthGroupAccessModel()->getGroupId($referral_info_permanent['admin_id']);
- }
- //都是代理商,且代理商不同
- if ($referral_info_permanent['admin_id'] != $referral_info_request['admin_id'] && $requestGroupId == AdminConstants::ADMIN_GROUP_ID_AGENT && $permanentGroupId == AdminConstants::ADMIN_GROUP_ID_AGENT) {
- $update['referral_id_permanent'] = $requestReferralId;
- }
- }
- }
- return $this->setData($update)->getReturn();
- }
- /**
- * 获取推广链接id
- * @return \app\main\model\object\ReturnObject
- */
- public function getUserReferralId()
- {
- try{
- $referralId = 0;
- //从用户表获取
- if (UserService::instance()->getUserInfo()->referral_id) {
- $referralId = UserService::instance()->getUserInfo()->referral_id;
- }elseif(Request::instance()->get('referral_id')){
- $referralId = Request::instance()->get('referral_id');
- }
- if ($referralId && UserService::instance()->isLogin()) {
- $this->setUserReferralId($referralId);
- }
- return $this->setData($referralId)->getReturn();
- }catch (\Exception $e){
- LogService::exception($e);
- return $this->setData(0)->getReturn();
- }
- }
- /**
- * 获取代理商id
- * @return \app\main\model\object\ReturnObject
- */
- public function getUserAgentId()
- {
- try {
- $agentId = 0;
- //从用户表获取
- if (UserService::instance()->getUserInfo()->agent_id) {
- $agentId = UserService::instance()->getUserInfo()->agent_id;
- }elseif(Request::instance()->get('agent_id')){
- $agentId = Request::instance()->get('agent_id');
- }
- if ($agentId && UserService::instance()->isLogin()) {
- $channel_id = UserService::instance()->getUserInfo()->channel_id;
- if (!AdminService::instance()->checkAgentIdBelongsToChannelId($agentId, $channel_id)->data) {
- $agentId = 0;
- if (UserService::instance()->isLogin()) {
- UserService::instance()->update(['agent_id' => 0]);
- // UserService::instance()->getUserModel()->setConnect($user_id)
- // ->where('id', $user_id)
- // ->update(['agent_id' => 0]);
- // UserService::instance()->updateRedisUserCache($user_id, ['agent_id' => 0]);
- }
- } else {
- if (UserService::instance()->getUserInfo()->agent_id != $agentId) {
- UserService::instance()->update(['agent_id' => $agentId]);
- // $user_id = UserService::instance()->getUserInfo()->id;
- // UserService::instance()->getUserModel()->setConnect($user_id)
- // ->where('id', $user_id)
- // ->update(['agent_id' => $agentId]);
- // UserService::instance()->updateRedisUserCache($user_id, ['agent_id' => $agentId]);
- }
- }
- }
- return $this->setData($agentId)->getReturn();
- } catch (\Exception $e) {
- LogService::exception($e);
- return $this->setData(0)->getReturn();
- }
- }
- public function delUrlParams($url, $params)
- {
- $arr = parse_url($url);
- $old_params = [];
- if (isset($arr['query']) && !empty($arr['query'])) {
- $queryParts = explode('&', $arr['query']);
- if ($queryParts) {
- foreach ($queryParts as $param) {
- $item = explode('=', $param);
- if (count($item) == 2) {
- $old_params[$item[0]] = $item[1];
- }
- }
- }
- }
- if (is_string($params)) {
- if (isset($old_params[$params])) {
- unset($old_params[$params]);
- }
- } elseif (is_array($params)) {
- foreach ($params as $item) {
- if (isset($old_params[$item])) {
- unset($old_params[$item]);
- }
- }
- }
- $tmp_url = empty($arr['scheme']) ? 'http' : $arr['scheme'] . '://' . $arr['host'] . $arr['path'];
- if (!empty($old_params)) {
- $i = 0;
- foreach ($old_params as $k => $v) {
- $tmp_url = $tmp_url . ($i == 0 ? '?' : '&') . $k . '=' . $v;
- $i++;
- }
- }
- return $tmp_url;
- }
- public function getUrlNoPort($domain = null)
- {
- $url = Request::instance()->url($domain);
- $url = strtolower(preg_replace('/:\d+$/', '', trim($url))); //去除 :端口 结束的
- return preg_replace('/:\d+\//', '/', trim($url)); //去除 :端口/
- }
- /**
- * 推广链接域名替换
- * @param $channel_id
- * @param $url
- * @param bool $replaceHost
- * @return \app\main\model\object\ReturnObject
- */
- public function replaceReferralHost($channel_id, $url, $replaceHost = true)
- {
- $host = AdminService::instance()->getAdminReferralDomain($channel_id)->data;
- if ($replaceHost) {
- $this->setData(str_replace([$host['menu_ophost_host'], $host['ophost_host']], ['{$ophost}', '{$ophost}'], $url));
- } else {
- $this->setData(str_replace('{$ophost}', $host['menu_ophost_host'], $url));
- }
- return $this->getReturn();
- }
- /**
- * 无限二级域名设置
- * @return \app\main\model\object\ReturnObject
- **/
- public function unlimitSecondaryDomain(){
- if (!Redis::instance()->get("unlimit_domain")) {
- return $this->getReturn();
- }
- $host=get_host_no_port();
- preg_match("/^px-(\w+)-(wx\w+)-(\d+)-(.*?)\.(.*?)$/i", $host, $matches);
- $appId = $this->checkDomainIsReferral();
- $path=get_url_no_port();
- if ($matches) {
- $sign = Request::instance()->get('sign');
- $cacheSign = Redis::instance()->get("cache:" . $matches[3]);
- if ($cacheSign && $cacheSign == $sign) {
- Redis::instance()->del("cache:" . $matches[3]);
- Cookie::set('user_id', $matches[3]);
- }
- $userId=UserService::instance()->getUserInfo()->id;
- if ($userId) {
- $cacheCode = $matches[1];
- $openId=UserService::instance()->getUserInfo()->openid;
- if (substr(md5($openId), 0, 5) != $matches[4]) {
- $url = $this->getUnlimitDomainOriginWxUrl()->data;
- return $this->setCode(ErrorCodeConstants::REDIRECT)->setData($url)->getReturn();
- }
- $redisCacheCode = Redis::instance()->get("DOMAIN:".$userId);
- if($redisCacheCode){
- if($redisCacheCode == $cacheCode){
- Redis::instance()->expire("DOMAIN:".$userId, $this->getUnlimitDomainExpire());
- return $this->getReturn();
- }else{
- $url = $this->getUnlimitDomainOriginWxUrl()->data;
- return $this->setCode(ErrorCodeConstants::REDIRECT)->setData($url)->getReturn();
- }
- }else{
- $code = substr(md5(uniqid()), 0, 5);
- Redis::instance()->setex("DOMAIN:" . $userId, $this->getUnlimitDomainExpire(), $code);
- $preHost = $appId.'.'.$matches[5];
- $newUrl = $this->getUnlimitDomain($code, $appId, $userId, $openId,$preHost . $path);
- return $this->setData($newUrl)->setCode(ErrorCodeConstants::REDIRECT)->getReturn();
- }
- } else {
- $url = $this->getUnlimitDomainOriginWxUrl()->data;
- return $this->setCode(ErrorCodeConstants::REDIRECT)->setData($url)->getReturn();
- }
- }else {
- $userId = UserService::instance()->getUserInfo()->id;
- if ($userId) {
- if ($userId == UserService::instance()->getUserInfo()->openid) {
- Cookie::delete('user_id');
- UserService::instance()->getRunTimeObject()->user = new UserObject();
- } else {
- $cacheCode = Redis::instance()->get("DOMAIN:" . $userId);
- if (!$cacheCode) {
- $cacheCode = substr(md5(uniqid()), 0, 5);
- Redis::instance()->setex("DOMAIN:" . $userId, $this->getUnlimitDomainExpire(), $cacheCode);
- }
- $openId = UserService::instance()->getUserInfo()->openid;
- $sign = md5(time());
- Redis::instance()->set("cache:" . $userId, $sign);
- if (stripos($path, '?') === false) {
- $path .= '?sign=' . $sign;
- } else {
- $path .= '&sign=' . $sign;
- }
- $newUrl = $this->getUnlimitDomain($cacheCode, $appId, $userId, $openId, $host . $path);
- return $this->setData($newUrl)->setCode(ErrorCodeConstants::REDIRECT)->getReturn();
- }
- }
- }
- return $this->getReturn();
- }
- /**
- * 获取无限二级的原始推广链接
- * @return \app\main\model\object\ReturnObject
- */
- public function getUnlimitDomainOriginWxUrl()
- {
- $url = get_url_no_port(true);
- $data = preg_replace("/px-(\w+)-(wx\w+)-(\d+)-(.*?)\.(.*?)$/i", '\2.\5', $url);
- return $this->setData($data)->getReturn();
- }
- /**
- * @return mixed 获取无限二级过期时间
- */
- public function getUnlimitDomainExpire()
- {
- return Env::get('app.unlimit_domain_expire', 3600);
- }
- /**
- * 获取无限二级链接
- * @param $cacheCode
- * @param $appId
- * @param $userId
- * @param $openId
- * @param $url
- * @return mixed
- */
- public function getUnlimitDomain($cacheCode, $appId, $userId, $openId, $url)
- {
- $url = str_replace($appId, 'px-' . $cacheCode . '-' . $appId . '-' . $userId . '-' . substr(md5($openId), 0, 5), $url);
- $url = $this->replace2fakeFirstDomain($appId, $url)->data;
- return $url;
- }
- /**
- * 虚假顶级域名替换
- * @param $appId
- * @param $url
- * @return \app\main\model\object\ReturnObject
- **/
- public function replace2fakeFirstDomain($appId, $url)
- {
- $channelData = AdminService::instance()->getAdminConfigModel()->getAdminInfoByAppId($appId); //得到此渠道的配置信息 adminInfoAll
- $host = AdminService::instance()->getAdminReferralDomain($channelData['admin_id'])->data;
- if(!$host['fakemenuophost_host'] && !$host['fakeophost_host']){
- //默认取Config
- $url = Config::get("site.scheme") . '://' . $url;
- }else{
- if($host['fakemenuophost_host'])
- {
- //菜单域名
- if(false !== strpos($url,$host['menu_ophost_host'])) $url = $host['fakemenuophost_scheme'] . "://" . str_replace($host['menu_ophost_host'],$host['fakemenuophost_host'],$url);
- }
- if($host['fakeophost_host']) {
- //业务域名
- if(false !== strpos($url,$host['ophost_host'])) $url = $host['fakeophost_scheme'] . "://" .str_replace($host['ophost_host'],$host['fakeophost_host'],$url);
- }
- }
- return $this->setData($url)->getReturn();
- }
- /**
- * @param $referralId
- * @param $ext
- * @return \app\main\model\object\ReturnObject
- */
- public function checkCustomExtReferralMatch($ext = '', $referralId = false)
- {
- $user = UserService::instance()->getUserInfo();
- if (!$referralId) {
- $referralId = $user->referral_id;
- }
- if (!$ext) {
- $ext = $user->ext;
- }
- if ($referralId && CustomService::instance()->checkExtIsCustom($ext)->data) {
- $cacheExt = 'RefExt:' . md5($ext);
- if ($cache = Redis::instance()->get($cacheExt)) {
- return $this->setData($cache == $referralId)->getReturn();
- }
- }
- return $this->setData(false)->getReturn();
- }
- }
|