getReferralDayCollectModel() ->where('referral_id', 'eq', $referral_id) ->where('createdate', 'eq', $createDate) ->find(); if (empty($row)) { return $this->createDayData($referral_id, $data, $createDate); } else { //更新 if ($row['all_recharge_money'] <= 0) { $allMoney = $this->getReferralModel() ->where('id', 'eq', $referral_id)->value('money'); $data['all_recharge_money'] = $allMoney ?: 0; } else { $data['all_recharge_money'] = $data['recharge_money']; } foreach ($data as $key=>$val) { if (in_array($key, $updateDataFields)) { $row->$key = ['exp', "($key+$val)"]; } else { if (in_array($val, $updateDataFields)) { $row->$val = ['exp', "($val+1)"]; } } } return $row->save(); } } /** * 创建日统计数据 * * @param $referral_id * @param array $data * @return false|int */ public function createDayData($referral_id, $data = [], $createDate = null) { $referral = $this->getReferralModel() ->where('id', 'eq', $referral_id) ->find(); $allMoney = $referral['money']; if (empty($allMoney)) { Log::error("支付回调每日数据新增时money字段为null---{$referral_id}"); } $saveData = [ 'referral_id' => $referral_id, 'createdate' => $createDate ?: date("Ymd"), 'createtime' => time(), 'updatetime' => time(), 'all_recharge_money' => $allMoney ?: 0, ]; $saveData = array_merge($saveData, $data); return $this->getReferralDayCollectModel() ->allowField(true) ->save($saveData); } public function getAdminReferralList($admin_id, $push = '0', $where = [], $sort = 'referral.money', $order = 'desc', $offset = 0, $limit = 10) { $condition = [ 'push' => $push, ]; $group = Auth::instance()->getGroups($admin_id); $timeBetween = (time() - 86400 * 7) . ',' . time(); switch ($group[0]['group_id']) { case AdminConstants::ADMIN_GROUP_ID_ADMIN: $total = $this->getReferralModel() ->join('book', 'book.id=referral.book_id', "LEFT") ->join('admin_extend', 'admin_extend.admin_id=referral.admin_id', 'INNER') ->where('admin_extend.create_by', $admin_id) ->where($where) ->where($condition) ->whereBetween('referral.createtime',$timeBetween) ->count(); $list = $this->getReferralModel() ->join('book', 'book.id=referral.book_id', "LEFT") ->join('admin_extend', 'admin_extend.admin_id=referral.admin_id', 'INNER') ->where('admin_extend.create_by', $admin_id) ->where($where) ->where($condition) ->whereBetween('referral.createtime',$timeBetween) // ->order('id', 'desc') ->order($sort, $order) ->limit($offset, $limit) ->field('referral.*,book.name as book_name') ->select(); break; case AdminConstants::ADMIN_GROUP_ID_SUPER_ADMIN: case AdminConstants::ADMIN_GROUP_ID_TECHNICAL_SUPPORT: $total = $this->getReferralModel() ->join('book', 'book.id=referral.book_id', "LEFT") ->join('auth_group_access', 'auth_group_access.uid=referral.admin_id', 'INNER') ->where('auth_group_access.group_id', AdminConstants::ADMIN_GROUP_ID_CHANNEL) ->where($where) ->where($condition) ->whereBetween('referral.createtime',$timeBetween) ->count(); $list = $this->getReferralModel() ->join('book', 'book.id=referral.book_id', "LEFT") ->join('auth_group_access', 'auth_group_access.uid=referral.admin_id', 'INNER') ->where('auth_group_access.group_id', AdminConstants::ADMIN_GROUP_ID_CHANNEL) ->where($where) ->where($condition) ->whereBetween('referral.createtime',$timeBetween) // ->order('id', 'desc') ->order($sort, $order) ->limit($offset, $limit) ->field('referral.*,book.name as book_name') ->select(); break; default: $total = 0; $list = []; } $migrateCollectList = []; $migrate = VisitLimitService::instance()->checkMigratedV2(); if ($migrate) { $referralIds = array_column($list, 'id'); $migrateCollectList = ReferralService::instance()->getReferralCollectFromApi($referralIds)->data; } foreach ($list as $k => $v) { //获取当前书籍的默认关注章节 if (empty($v['guide_chapter_idx']) && !empty($v['book_id'])) { $default_chapter_idx = model('Guide')->getGuideChapter($v['admin_id'], $v['book_id'], 0, $v['admin_id']); $list[$k]['guide_chapter_idx'] = $default_chapter_idx; } $adminConfig = model('adminConfig')->getAdminInfoAll($v['admin_id']); $url_referral = Config::get('site.scheme') . '://' . $adminConfig['appid'] . '.' . $adminConfig['ophost_host']; $list[$k]['url_referral'] = $url_referral . '/t/' . $v['id']; $list[$k]['skin_url'] = $this->getSkinUrl($v['id'], $v['source_url']); if ($migrate) { if (array_key_exists($v['id'], $migrateCollectList)) { $list[$k] = array_merge($list[$k]->getData(), $migrateCollectList[$v['id']]); } } else { $dayMTkey = "M-T:".$v['id'].":".date("d"); //今日充值金额key $list[$k]['dayuv'] = (int)Redis::instance()->get(CacheConstants::getReadOfReferralIdKey($v['id'])); $list[$k]['dayut'] = (int)Redis::instance()->get(CacheConstants::getSubscribeOfReferralIdKey($v['id'])); //今日关注人数 $list[$k]['daymt'] = (int)Redis::instance()->get($dayMTkey)? round(Redis::instance()->get($dayMTkey) / 100, 2) :0; //今日充值金额 $list[$k]['dayjt'] = (int)Redis::instance()->get(CacheConstants::getSubscribeOfPureReferralIdKey($v['id'])); //今日净关注人数 $list[$k]['dayqt'] = (int)Redis::instance()->get(CacheConstants::getUnsubscribeOfReferralIdKey($v['id'])); //今日取消关注人数 $list[$k]['net_follow_num'] = (int)$list[$k]['net_follow_num']; $dayMTNkey = "M-T-N:".$v['id'].":".date("d"); //今日充值笔数key $list[$k]['order_nums'] = (int)$list[$k]['orders_num']; $list[$k]['day_order_nums'] = (int)Redis::instance()->get($dayMTNkey); } $list[$k]['book'] = [ 'name' => isset($v['book_name'])?$v['book_name']:'', ]; if (!empty($v['book_id'])) { $isLimited = model('BookLimit')->backendHasLimit(0, $v['admin_id'], $v['book_id']); if ($isLimited) { $list[$k]['limited'] = 1; } else { $list[$k]['limited'] = 0; } } else { $list[$k]['limited'] = 0; } $list[$k]['short_url'] = replaceShortDomain($list[$k]['url_referral'], $v['short_id']); } return $this->setData(["total" => $total, "rows" => $list])->getReturn(); } public function getSkinUrl($referral_id, $default_url, $channel_id='') { //$channel_id = $this->getChannelIdByReferralId($referral_id); $domain = AppConstants::getRandomFrontDomain(); Log::info('skinUrl:domain:'.$domain); $base_url = ""; if(!$domain){ $default_url = str_replace(["https://", "http://"], ["", ""], $default_url); $url = $base_url . $default_url; }else{ //$url = $base_url . $domain . "/referral.html?t=" . $referral_id . "&type=code&channel_id=".$channel_id; $url = $base_url . $domain . "/referral.html?t=" . $referral_id . "&type=code"; } Log::info('skinUrl:'.$url); return $url; } /** * 是否回源链接 * @param $referral_id * @param bool $admin_id * @return int * @throws \think\exception\DbException */ public function isAdReferral($referral_id, $admin_id = false) { $is = 0; $redisKey = 'CADH:'.$referral_id; $relationId = Redis::instance()->get($redisKey); if ($relationId !== false) { //延长时间 Redis::instance()->expire($redisKey, 600); $is = $relationId; } else { //查库 $id = 0; if (!$admin_id) { $referralRow = $this->getReferralModel()->get($referral_id); $admin_id = $referralRow['admin_id']; } $row = model("WechatAb")->field("id")->where('admin_id', 'eq', $admin_id)->where("find_in_set({$referral_id},referral_id)")->find(); if ($row) { $id = $row['id']; $is = $id; } Redis::instance()->set($redisKey, $id, 600); } return (int)$is; } /** * 编辑缓存 * @param $referral_id * @param $id * @param string $op * @return bool */ public function modifyAdReferralCache($referral_id, $id, $op='add') { if (empty($referral_id)) return false; $redisKey = 'CADH:'.$referral_id; if ($op == 'add') { Redis::instance()->set($redisKey, $id, 600); } else { Redis::instance()->del($redisKey); } return true; } public function sendReferralAdData($referral_id, $data) { //是否需要回传 if ($id = $this->isAdReferral($referral_id, $data['admin_id'])) { $row = model("WechatAb")->getInfo($id); if (empty($row)) { Log::error("WechatAb 记录不存在 referral_id: {$referral_id} id:{$id}"); return false; } $adminInfo = AdminService::instance()->getAdminConfigModel()->getAdminInfoAll($data['admin_id']); if (isset($data['orders'])) { $postData['actions'][0] = [ 'user_action_set_id' => $row['wx_ad_source_id'], 'action_type' => $data['action_type'], 'action_time' => time(), 'url' => $data['url'], 'user_id' => [ 'wechat_app_id' => $adminInfo['appid'], 'wechat_openid' => $data['openid'], ], 'action_param' => [ "product_name" => $data['orders']['productName'], "product_id" => $data['product_id'], "value" => intval($data['orders']['money'] * 100), "source" => "Biz", "wechat_app_id" => $adminInfo['appid'], 'claim_type' => 0 ] ]; } if (isset($data['sub'])) { $postData['actions'][0] = [ 'user_action_set_id' => $row['wx_ad_source_id'], 'action_type' => 'REGISTER', 'action_time' => time(), 'url' => $data['url'], 'user_id' => [ 'wechat_app_id' => $adminInfo['appid'], 'wechat_openid' => $data['openid'], ], 'action_param' => [ "product_name" => $data['sub']['productName'], "source" => "Biz", "wechat_app_id" => $adminInfo['appid'], 'claim_type' => 0 ] ]; } try { $access_token = current((new WeChatObject(null))->getOfficialAccountByPlatform($row['platform_id'], $row['appid'], $row['refresh_token'])->access_token->getToken()); $httpConfig = [ 'base_uri' => 'https://api.weixin.qq.com/marketing/', 'connect_timeout' => 10, 'timeout' => 30, 'http_errors' => true, //抛出异常 true是 false否 'verify' => false, //不验证ssl证书 ]; $proxy = OpenPlatformService::instance()->getProxyconfigById($row['platform_id']); if ($proxy) { $httpConfig = array_merge($httpConfig, ['proxy' => $proxy]); } WeChatAdService::instance()->send($httpConfig,$access_token,$postData); } catch (\Exception $e) { Log::error("AbWeChatAd回源异常: data: ".json_encode($postData)." Error:".$e->getMessage()); } } return true; } /** * 推广链接添加 * @param $params * @param $admin_id * @param $group * @param $channel_id * @return ReturnObject */ public function updateReferral($params, $admin_id, $group, $channel_id) { $params['type'] = 1; $params['wx_type'] = 1; $mReferral = $this->getReferralModel(); $oReferral = (new ReferralObject())->bind($params); $oReferral->admin_id = $admin_id; $oReferral->createtime = time(); //获取当前书籍的默认关注章节 $default_chapter_idx = $oReferral->guide_chapter_idx ?? 0; if($oReferral->book_id){ $bookInfo = BookService::instance()->getBookModel()->BookInfo($oReferral->book_id); if ($bookInfo['state'] == 0 || $bookInfo['cansee'] == 0) { return $this->setCode(ErrorCodeConstants::PARAMS_ERROR_INVALID)->setMsg('抱歉,本书已下架,无法生成推广链接~')->getReturn(); } if (!$oReferral->guide_chapter_idx) { if (in_array($group, [AdminConstants::ADMIN_GROUP_ID_VIP, AdminConstants::ADMIN_GROUP_ID_VIP_OPERATOR])) { //vip和vip运营者 return $this->setCode(ErrorCodeConstants::PARAMS_ERROR_INVALID)->setMsg('导粉章节数必填')->getReturn(); } else { $default_chapter_idx = model('Guide')->getGuideChapter($admin_id,$params['book_id'],0,$channel_id); } } if($default_chapter_idx > $this->bookPayChapterIdex($oReferral->book_id)){ return $this->setCode(ErrorCodeConstants::PARAMS_ERROR_INVALID)->setMsg('导粉章节数必须小于收费章节数')->getReturn(); } } if(!$oReferral->push){ $oReferral->push = 0; } $oReferral->share_image = ResourceService::instance()->getRandomImage()->data; $oReferral->share_title = ResourceService::instance()->getRandomTitle()->data; $return = []; if ($oReferral->id) { $update = $mReferral->mkParamsForUpdate($oReferral); $return['id'] = $oReferral->id; $mReferral->update($update, ['id'=>$oReferral->id]); } else { $insert = $mReferral->mkParamsForInsert($oReferral); $insertId = $mReferral->allowField(true)->insertGetId($insert); if($insertId === false){ return $this->setData(ErrorCodeConstants::DB_ERROR_UPDATE)->setMsg($mReferral->getError())->getReturn(); } $return['id'] = $insertId; $source_url = ''; //首页 if ($oReferral->type == 2) { $source_url .= '?referral_id='.$insertId; } else { $source_url .= '/index/book/chapter?book_id=' . $params['book_id'] . '&sid=' . $params['chapter_id'] . '&referral_id=' . $insertId; } if ($group == AdminConstants::ADMIN_GROUP_ID_AGENT) { $source_url .= '&agent_id='.$admin_id; } $update = []; $update['source_url'] =getCurrentDomain($channel_id,$source_url); //绑定域名短链ID及重置生成短链接的源地址,代理商使用渠道的短链域名池 $short = model('ShortRelation')->getRandShort($channel_id); if($short){ $update['short_id'] = $short->id; $short_source_url = replaceShortDomain($params['jmp_url'], $short->id); }else{ $short_source_url = $update['source_url']; } $shoturl = new ShortUrl(); //生成腾讯短链 $update['short_url_qq'] = $shoturl->tencent($channel_id, $short_source_url); //生成sina短链 $update['short_url_weibo'] = $shoturl->sina($short_source_url); $mReferral->update($update, ['id' => $insertId]); } $return['url'] = getCurrentDomain($channel_id,'/t/'.$return['id']); //删除Redis缓存 Redis::instance()->del('RI:N:'.$return['id']); return $this->setData($return)->getReturn(); } /** * 书收费章节 * @param $book_id * @return ReturnObject */ private function bookPayChapterIdex($book_id){ //获取书籍信息 $book = model('Book')->BookInfo($book_id); //全局免费章节数 $free_chapter_idx = config('site.book_free_chapter_num'); //如果本书籍设置了免费章节数,以本书籍的免费章节数为准 if(intval($book['free_chapter_num'])>0){ $free_chapter_idx = $book['free_chapter_num']; } return $this->setData($free_chapter_idx)->getReturn(); } /** * 获取分流链接对应的渠道链接 * @param $vid * @param $channel * @return ReturnObject */ public function getChannelReferralFromVip($vid, $channel) { $referral_id = model('referral_slave')->where('library_id', $vid) ->where('channel_id', $channel) ->value('referral_id'); return $this->setData($referral_id)->getReturn(); } public function getReferralCollectFromApi($ids) { $return = []; $data = ApiService::instance()->getCollectFromApi(ApiConstants::API_REFERRAL, ['ids' => $ids])->data; foreach ($ids as $id) { $return[$id] = [ 'uv' => 0, 'dayuv' => 0, 'follow' => 0, 'dayut' => 0, 'money' => 0, 'daymt' => 0, 'net_follow_num' => 0, 'dayjt' => 0, 'unfollow_num' => 0, 'dayqt' => 0, 'order_nums' => 0, 'day_order_nums' => 0, ]; } foreach ($data as $index => $item) { $return[$item['referralId']] = [ 'uv' => $item['uv'], 'dayuv' => $item['uvDay'], 'follow' => $item['follow'], 'dayut' => $item['followDay'], 'money' => $item['money'], 'daymt' => $item['moneyDay'], 'net_follow_num' => $item['netFollowNum'], 'dayjt' => $item['netFollowNumDay'], 'unfollow_num' => $item['unfollowNum'], 'dayqt' => $item['unfollowNumDay'], 'order_nums' => $item['ordersNum'], 'day_order_nums' => $item['ordersNumDay'], ]; } return $this->setData($return)->getReturn(); } public function getMigrateReferralDayCollect($id) { $list = []; $data = ApiService::instance()->getCollectFromApi(ApiConstants::API_REFERRAL_DAY, ['referralId'=>$id])->data; if ($data) { foreach ($data as $item) { $list[] = [ 'follow' => $item['follow'], 'referral_id' => $item['referralId'], 'createdate' => $item['createdate'], 'recharge_money' => $item['rechargeMoney'], 'orders_num' => $item['ordersNum'], 'all_recharge_money' => $item['allRechargeMoney'], 'uv' => $item['uv'], ]; } } return $this->setData($list)->getReturn(); } }