From a37d7ae901938cd1648601b00b3dced611b4afe9 Mon Sep 17 00:00:00 2001 From: hgc Date: Tue, 24 Dec 2024 09:51:32 +0800 Subject: [PATCH] =?UTF-8?q?=E9=87=87=E9=9B=86=E4=BA=8B=E4=BB=B6=E6=9B=B4?= =?UTF-8?q?=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/controller/AdController.php | 1 + app/controller/OAuthController.php | 4 + app/event/GoogleAdsAds.php | 18 +- app/event/GoogleAdsCampaigns.php | 18 +- app/event/GoogleAdsDateDatas.php | 15 +- app/event/GoogleAdsGroups.php | 370 ++++++++++++----------- app/process/UpdateGoogleAdsTask.php | 6 +- app/service/BaseService.php | 2 +- app/service/GoogleAdsAdService.php | 19 +- app/service/GoogleAdsCampaignService.php | 11 +- app/service/GoogleAdsGroupService.php | 11 +- app/service/GoogleOAuthService.php | 30 +- 12 files changed, 297 insertions(+), 208 deletions(-) diff --git a/app/controller/AdController.php b/app/controller/AdController.php index 7446120..d40a571 100644 --- a/app/controller/AdController.php +++ b/app/controller/AdController.php @@ -86,6 +86,7 @@ class AdController // 调用 Service 层查询 $result = $this->googleAdsReportService::getCampaignList($page, $pageSize, $keyword, $dateRange, $startDate, $endDate); return $this->successResponse($result); +// return $this->errorResponse(300,'授权失败'); } public function exportAdsToExcel(Request $request) diff --git a/app/controller/OAuthController.php b/app/controller/OAuthController.php index 5217978..6a8c276 100644 --- a/app/controller/OAuthController.php +++ b/app/controller/OAuthController.php @@ -88,6 +88,10 @@ class OAuthController public function testRefreshToken(Request $request) { + $customers = $this->googleOAuthService->getGoogleAdCustomers([]); + return $this->successResponse(['data' => $customers]); + + // $list = ThinkDb::table('bps.bps_third_user')->where('third_type', 'google')->select(); // return $this->successResponse($list); diff --git a/app/event/GoogleAdsAds.php b/app/event/GoogleAdsAds.php index 86067a5..1b98f6c 100644 --- a/app/event/GoogleAdsAds.php +++ b/app/event/GoogleAdsAds.php @@ -3,6 +3,7 @@ namespace app\event; use app\service\GoogleAdsAdService; +use app\service\GoogleOAuthService; use Google\ApiCore\ApiException; use GuzzleHttp\Client; use GuzzleHttp\Exception\GuzzleException; @@ -24,6 +25,12 @@ class GoogleAdsAds private $googleAdsAdService; + /** + * @Inject + * @var GoogleOAuthService + */ + + private $googleOAuthService; //微博热榜地址 @@ -40,8 +47,6 @@ class GoogleAdsAds const countries = ["GB", "BE"]; - - public function listAds(Request $request) { $options = $request->all(); @@ -54,11 +59,14 @@ class GoogleAdsAds * get groups * @throws ApiException */ - public function getAds($options): Response + public function getAds($options) { - $resourceName = $this->googleAdsAdService->runListAds($options['customer_id']); + $customers = $this->googleOAuthService->getGoogleAdCustomers([]); + foreach ($customers as $customerId) { + $resourceName = $this->googleAdsAdService->runListAds($customerId); + } - return $this->successResponse(['ads_list' => $resourceName]); +// return $this->successResponse(['ads_list' => $resourceName]); } /** diff --git a/app/event/GoogleAdsCampaigns.php b/app/event/GoogleAdsCampaigns.php index da9108e..1e86aef 100644 --- a/app/event/GoogleAdsCampaigns.php +++ b/app/event/GoogleAdsCampaigns.php @@ -4,6 +4,7 @@ namespace app\event; use app\model\Campaign; use app\service\GoogleAdsCampaignService; +use app\service\GoogleOAuthService; use Google\ApiCore\ApiException; use GuzzleHttp\Client; use GuzzleHttp\Exception\GuzzleException; @@ -25,6 +26,12 @@ class GoogleAdsCampaigns private $googleAdsCampaignService; + /** + * @Inject + * @var GoogleOAuthService + */ + + private $googleOAuthService; //微博热榜地址 @@ -55,11 +62,14 @@ class GoogleAdsCampaigns * get campaigns * @throws ApiException */ - public function getCampaigns($options): Response + public function getCampaigns($options) { - $resourceName = $this->googleAdsCampaignService->runListCampaigns($options['customer_id']); - - return $this->successResponse(['campaigns_list' => $resourceName]); + $customers = $this->googleOAuthService->getGoogleAdCustomers([]); + foreach ($customers as $customerId) { + $googleAdsCampaignService = new googleAdsCampaignService($customerId); + $resourceName = $googleAdsCampaignService->runListCampaigns($customerId); + } +// return $this->successResponse(['campaigns_list' => $resourceName]); } /** diff --git a/app/event/GoogleAdsDateDatas.php b/app/event/GoogleAdsDateDatas.php index f0e5dce..1ac30fb 100644 --- a/app/event/GoogleAdsDateDatas.php +++ b/app/event/GoogleAdsDateDatas.php @@ -4,6 +4,7 @@ namespace app\event; use app\model\Campaign; use app\service\GoogleAdsCampaignService; +use app\service\GoogleOAuthService; use Google\ApiCore\ApiException; use GuzzleHttp\Client; use GuzzleHttp\Exception\GuzzleException; @@ -25,6 +26,13 @@ class GoogleAdsDateDatas private $googleAdsCampaignService; + /** + * @Inject + * @var GoogleOAuthService + */ + + private $googleOAuthService; + //微博热榜地址 @@ -57,7 +65,12 @@ class GoogleAdsDateDatas */ public function getDateDatas($options) { - $this->googleAdsCampaignService->runListDateDatas($options['customer_id'], $options['date']); + $customers = $this->googleOAuthService->getGoogleAdCustomers([]); + foreach ($customers as $customerId) { + $this->googleAdsCampaignService->runListDateDatas($customerId, $options['date']); + } + +// $this->googleAdsCampaignService->runListDateDatas($options['customer_id'], $options['date']); // return $this->successResponse(['data' => $resourceName]); } diff --git a/app/event/GoogleAdsGroups.php b/app/event/GoogleAdsGroups.php index 291e7c7..6406c78 100644 --- a/app/event/GoogleAdsGroups.php +++ b/app/event/GoogleAdsGroups.php @@ -4,7 +4,9 @@ namespace app\event; use app\model\AdGroup; use app\service\GoogleAdsCampaignService; -use app\service\GoogleAdsGroupService;use Google\ApiCore\ApiException; +use app\service\GoogleAdsGroupService; +use app\service\GoogleOAuthService; +use Google\ApiCore\ApiException; use GuzzleHttp\Client; use GuzzleHttp\Exception\GuzzleException; use support\Db; @@ -25,6 +27,12 @@ class GoogleAdsGroups private $googleAdsGroupService; + /** + * @Inject + * @var GoogleOAuthService + */ + + private $googleOAuthService; //微博热榜地址 @@ -41,8 +49,6 @@ class GoogleAdsGroups const countries = ["GB", "BE"]; - - public function listGroups(Request $request) { $options = $request->all(); @@ -55,195 +61,201 @@ class GoogleAdsGroups * get groups * @throws ApiException */ - public function getGroups($options): Response + public function getGroups($options) { - $resourceName = $this->googleAdsGroupService->runListGroups($options['customer_id']); + $customers = $this->googleOAuthService->getGoogleAdCustomers([]); - return $this->successResponse(['groups_list' => $resourceName]); + foreach ($customers as $customerId) { + $googleAdsGroupService = new GoogleAdsGroupService($customerId); + + $resourceName = $googleAdsGroupService->runListGroups($options['customer_id']); + +// return $this->successResponse(['groups_list' => $resourceName]); + } } + /** + * 每天爬取tiktok广告 + * @return void + */ + public + function update() + { + try { - /** - * 每天爬取tiktok广告 - * @return void - */ - public function update() - { - try { - - $client = new Client([ - //允许重定向 + $client = new Client([ + //允许重定向 // 'allow_redirects' => true, - ]); + ]); - // 获取前两天 0 点的时间戳 - $dayBeforeYesterdayStart = strtotime('-2 days 00:00:00'); + // 获取前两天 0 点的时间戳 + $dayBeforeYesterdayStart = strtotime('-2 days 00:00:00'); - // 获取前一天 0 点的时间戳 - $yesterdayStart = strtotime('-1 day 00:00:00'); - $countryCache = Redis::get(self::type . 'lastCountry'); - //全部跑完跳出 - if ($countryCache == 'All') { - dump($countryCache . '国家更新tiktok Ads 完成'); - return; - } - - if (empty($countryCache)) { - $countryCache = 'GB'; - } - - $searchIdCache = Redis::get(self::type . 'lastSearchId'); - $offsetCache = Redis::get(self::type . 'nextOffset'); - $totalCache = Redis::get(self::type . 'totalCache'); - if (!isset($searchIdCache) || empty($searchIdCache)) { - $searchIdCache = ''; - } - if (!isset($offsetCache) || empty($searchIdCache)) { - $offsetCache = 0; - } - if (!isset($totalCache) || empty($searchIdCache)) { - $totalCache = 0; - } - - //判断国家是否跑完。 - if ($totalCache > 0 && $offsetCache > ceil($totalCache / self::limit)) { - $key = array_search($countryCache, self::countries, true); - if (in_array($countryCache, self::countries) && isset(self::countries[$key + 1])) { - $countryCache = self::countries[$key + 1]; - dump('更新' . $countryCache . '国家的tiktok Ads 完成'); - } else { - $countryCache = 'All'; //赋值非正常国家的code中断定时任务 + // 获取前一天 0 点的时间戳 + $yesterdayStart = strtotime('-1 day 00:00:00'); + $countryCache = Redis::get(self::type . 'lastCountry'); + //全部跑完跳出 + if ($countryCache == 'All') { dump($countryCache . '国家更新tiktok Ads 完成'); + return; + } + + if (empty($countryCache)) { + $countryCache = 'GB'; + } + + $searchIdCache = Redis::get(self::type . 'lastSearchId'); + $offsetCache = Redis::get(self::type . 'nextOffset'); + $totalCache = Redis::get(self::type . 'totalCache'); + if (!isset($searchIdCache) || empty($searchIdCache)) { + $searchIdCache = ''; + } + if (!isset($offsetCache) || empty($searchIdCache)) { + $offsetCache = 0; + } + if (!isset($totalCache) || empty($searchIdCache)) { + $totalCache = 0; + } + + //判断国家是否跑完。 + if ($totalCache > 0 && $offsetCache > ceil($totalCache / self::limit)) { + $key = array_search($countryCache, self::countries, true); + if (in_array($countryCache, self::countries) && isset(self::countries[$key + 1])) { + $countryCache = self::countries[$key + 1]; + dump('更新' . $countryCache . '国家的tiktok Ads 完成'); + } else { + $countryCache = 'All'; //赋值非正常国家的code中断定时任务 + dump($countryCache . '国家更新tiktok Ads 完成'); + } + return; } - return; - } - $start_time = $dayBeforeYesterdayStart; - $end_time = $yesterdayStart; - //当前国家爬取 - $currentParams = null; - $currentParams = ['country' => $countryCache, 'search_id' => $searchIdCache, 'type' => 1, 'start_time' => $start_time, 'end_time' => $end_time]; + $start_time = $dayBeforeYesterdayStart; + $end_time = $yesterdayStart; + //当前国家爬取 + $currentParams = null; + $currentParams = ['country' => $countryCache, 'search_id' => $searchIdCache, 'type' => 1, 'start_time' => $start_time, 'end_time' => $end_time]; - $url = 'https://library.tiktok.com/api/v1/search?region=' . $currentParams['country'] . '&type=' . $currentParams['type'] . '&start_time=' . $currentParams['start_time'] . '&end_time=' . $currentParams['end_time']; + $url = 'https://library.tiktok.com/api/v1/search?region=' . $currentParams['country'] . '&type=' . $currentParams['type'] . '&start_time=' . $currentParams['start_time'] . '&end_time=' . $currentParams['end_time']; - $res = json_decode($client->post($url, [ - 'headers' => [ - 'accept' => 'application/json, text/plain, */*', - 'accept-language' => 'zh-CN,zh;q=0.9', - 'content-type' => 'application/json', - 'cookie' => 'cookie: _ttp=2ov8Fc4C2CaNscHJd90O9fMhlpE; _ga=GA1.1.1025820618.1731926196; FPID=FPID2.2.Bcgkp%2Fk%2Bbn5w5YeSMR9wd9VpNHJwTUpkkaEqSdCEa0w%3D.1731926196; FPAU=1.2.944915349.1731926193; FPLC=mbVyryI5aG6IVpAvhs1JsgWjA7FVA6QsCJ7VbXhM7zWoXNp4rcD0IK7FNTTf%2FuOrqeOgqEhTd4NB3hY7q3aDVTGQa3WGHqxkGte4%2BBZxsrpaHFas9kb7DPRXM12T5Q%3D%3D; _ga_TEQXTT9FE4=GS1.1.1732097542.7.0.1732097542.0.0.857840528', - 'origin' => 'https://library.tiktok.com', - 'priority' => 'u=1, i', - 'referer' => 'https://library.tiktok.com/ads?region=AT&start_time=1731945600000&end_time=1732032000000&adv_name=&adv_biz_ids=&query_type=&sort_type=last_shown_date,desc', - 'sec-ch-ua' => '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"', - 'sec-ch-ua-mobile' => '?0', - 'sec-ch-ua-platform' => '"Windows"', - 'sec-fetch-dest' => 'empty', - 'sec-fetch-mode' => 'cors', - 'sec-fetch-site' => 'same-origin', - 'user-agent' => self::userAgent, + $res = json_decode($client->post($url, [ + 'headers' => [ + 'accept' => 'application/json, text/plain, */*', + 'accept-language' => 'zh-CN,zh;q=0.9', + 'content-type' => 'application/json', + 'cookie' => 'cookie: _ttp=2ov8Fc4C2CaNscHJd90O9fMhlpE; _ga=GA1.1.1025820618.1731926196; FPID=FPID2.2.Bcgkp%2Fk%2Bbn5w5YeSMR9wd9VpNHJwTUpkkaEqSdCEa0w%3D.1731926196; FPAU=1.2.944915349.1731926193; FPLC=mbVyryI5aG6IVpAvhs1JsgWjA7FVA6QsCJ7VbXhM7zWoXNp4rcD0IK7FNTTf%2FuOrqeOgqEhTd4NB3hY7q3aDVTGQa3WGHqxkGte4%2BBZxsrpaHFas9kb7DPRXM12T5Q%3D%3D; _ga_TEQXTT9FE4=GS1.1.1732097542.7.0.1732097542.0.0.857840528', + 'origin' => 'https://library.tiktok.com', + 'priority' => 'u=1, i', + 'referer' => 'https://library.tiktok.com/ads?region=AT&start_time=1731945600000&end_time=1732032000000&adv_name=&adv_biz_ids=&query_type=&sort_type=last_shown_date,desc', + 'sec-ch-ua' => '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"', + 'sec-ch-ua-mobile' => '?0', + 'sec-ch-ua-platform' => '"Windows"', + 'sec-fetch-dest' => 'empty', + 'sec-fetch-mode' => 'cors', + 'sec-fetch-site' => 'same-origin', + 'user-agent' => self::userAgent, // 'user-agent' => 'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36', - ], - 'json' => [ - 'query' => '', - 'query_type' => '', - 'adv_biz_ids' => '', - 'order' => self::sort_order, - 'offset' => (int)$offsetCache, - 'search_id' => $currentParams['search_id'], - 'limit' => self::limit, - ], + ], + 'json' => [ + 'query' => '', + 'query_type' => '', + 'adv_biz_ids' => '', + 'order' => self::sort_order, + 'offset' => (int)$offsetCache, + 'search_id' => $currentParams['search_id'], + 'limit' => self::limit, + ], - ])->getBody()->getContents(), true); + ])->getBody()->getContents(), true); // dump($res);return; //调试点 - if ($res['search_id'] != $searchIdCache) { - $searchIdCache = $res['search_id']; - dump('search_id更新 ' . $searchIdCache . ' 成功'); - } - - - if ($res['total'] == 0 || $res['code'] != 0) { - dump('更新tiktok Ads接口响应异常:' . json_encode($res, JSON_UNESCAPED_UNICODE)); - return; - } - $listAdsIds = []; - foreach ($res['data'] as $ad) { - if ($ad['audit_status'] == 2 || empty($ad['videos'])) { - continue; //审核不过或者没视频不采集 + if ($res['search_id'] != $searchIdCache) { + $searchIdCache = $res['search_id']; + dump('search_id更新 ' . $searchIdCache . ' 成功'); } - $imagesJson = is_array($ad['image_urls']) ? json_encode($ad['image_urls']) : json_encode([]); - $rejection_info = is_array($ad['rejection_info']) ? json_encode($ad['rejection_info']) : null; -// dump($rejection_info); - $insertData[$ad['id']] = [ - 'ad_id' => $ad['id'], - 'name' => $ad['name'], - 'audit_status' => $ad['audit_status'], - 'type' => $ad['type'], - 'first_shown_date' => $ad['first_shown_date'], - 'last_shown_date' => $ad['last_shown_date'], - 'image_urls' => $imagesJson, - 'estimated_audience' => $ad['estimated_audience'], - 'spent' => $ad['spent'], - 'impression' => $ad['impression'], - 'show_mode' => $ad['show_mode'], - 'rejection_info' => $rejection_info, - 'sor_audit_status' => $ad['sor_audit_status'], - 'country_code' => $countryCache, - ]; - if (isset($ad['videos']) && !empty($ad['videos'])) { - // 遍历 "videos" 数组 - foreach ($ad['videos'] as $video) { - $insertData[$ad['id']]['video_url'] = $video['video_url']; - $insertData[$ad['id']]['cover_img'] = $video['cover_img']; + + if ($res['total'] == 0 || $res['code'] != 0) { + dump('更新tiktok Ads接口响应异常:' . json_encode($res, JSON_UNESCAPED_UNICODE)); + return; + } + $listAdsIds = []; + foreach ($res['data'] as $ad) { + if ($ad['audit_status'] == 2 || empty($ad['videos'])) { + continue; //审核不过或者没视频不采集 } - } - $listAdsIds = array_column($insertData, 'ad_id'); - } + $imagesJson = is_array($ad['image_urls']) ? json_encode($ad['image_urls']) : json_encode([]); + $rejection_info = is_array($ad['rejection_info']) ? json_encode($ad['rejection_info']) : null; +// dump($rejection_info); + $insertData[$ad['id']] = [ + 'ad_id' => $ad['id'], + 'name' => $ad['name'], + 'audit_status' => $ad['audit_status'], + 'type' => $ad['type'], + 'first_shown_date' => $ad['first_shown_date'], + 'last_shown_date' => $ad['last_shown_date'], + 'image_urls' => $imagesJson, + 'estimated_audience' => $ad['estimated_audience'], + 'spent' => $ad['spent'], + 'impression' => $ad['impression'], + 'show_mode' => $ad['show_mode'], + 'rejection_info' => $rejection_info, + 'sor_audit_status' => $ad['sor_audit_status'], + 'country_code' => $countryCache, + ]; + if (isset($ad['videos']) && !empty($ad['videos'])) { + // 遍历 "videos" 数组 + foreach ($ad['videos'] as $video) { + $insertData[$ad['id']]['video_url'] = $video['video_url']; + $insertData[$ad['id']]['cover_img'] = $video['cover_img']; + } + } + $listAdsIds = array_column($insertData, 'ad_id'); + + } // dump($insertData);return; - if (empty($insertData)) return; + if (empty($insertData)) return; - //开启事务 - Db::beginTransaction(); + //开启事务 + Db::beginTransaction(); - //删除原来的旧数据 - TiktokAd::query()->whereIn('ad_id', array_keys($insertData))->delete(); - //添加新的数据 - TiktokAd::query()->insert($insertData); + //删除原来的旧数据 + TiktokAd::query()->whereIn('ad_id', array_keys($insertData))->delete(); + //添加新的数据 + TiktokAd::query()->insert($insertData); - //redis缓存 - Redis::set(self::type, json_encode($insertData, JSON_UNESCAPED_UNICODE)); + //redis缓存 + Redis::set(self::type, json_encode($insertData, JSON_UNESCAPED_UNICODE)); - //redis缓存 记录更新时间 - $time = date('Y-m-d H:i:s'); - Redis::set(self::type . 'time', $time); - Redis::set(self::type . 'lastCountry', $countryCache); - Redis::set(self::type . 'nextOffset', ++$offsetCache); //记录下一次的offset - Redis::set(self::type . 'totalCache', $res['total']); - Redis::set(self::type . 'lastSearchId', $searchIdCache); - if (!empty($listAdsIds)) { - Redis::rPush(self::type . 'AdsIds', ...$listAdsIds); + //redis缓存 记录更新时间 + $time = date('Y-m-d H:i:s'); + Redis::set(self::type . 'time', $time); + Redis::set(self::type . 'lastCountry', $countryCache); + Redis::set(self::type . 'nextOffset', ++$offsetCache); //记录下一次的offset + Redis::set(self::type . 'totalCache', $res['total']); + Redis::set(self::type . 'lastSearchId', $searchIdCache); + if (!empty($listAdsIds)) { + Redis::rPush(self::type . 'AdsIds', ...$listAdsIds); + } + + //提交事务 + Db::commit(); + //销毁$res + unset($res); + + dump(date('Y-m-d H:i:s') . '更新' . self::type . '成功'); + } catch (GuzzleException|\Exception $exception) { + //回滚事务 + Db::rollBack(); + dump('更' . self::type . '异常:' . $exception->getMessage()); + dump($exception); } - - //提交事务 - Db::commit(); - //销毁$res - unset($res); - - dump(date('Y-m-d H:i:s') . '更新' . self::type . '成功'); - } catch (GuzzleException|\Exception $exception) { - //回滚事务 - Db::rollBack(); - dump('更' . self::type . '异常:' . $exception->getMessage()); - dump($exception); - } // } catch (ClientExceptionInterface $e) { // // 捕获 4xx 错误 // dump( 'Client error: ' . $e->getMessage() . "\n"); @@ -257,25 +269,27 @@ class GoogleAdsGroups // // 捕获所有其他错误 // dump('General error: ' . $e->getMessage() . "\n") ; // } - } + } - // 可以加入一些公共方法 - protected function successResponse($data): Response - { - return Json([ - 'code' => 0, - 'msg' => 'ok', - 'data' => $data, - ]); - } + // 可以加入一些公共方法 + protected + function successResponse($data): Response + { + return Json([ + 'code' => 0, + 'msg' => 'ok', + 'data' => $data, + ]); + } - protected function errorResponse($code, $message, $data = []): Response - { - return Json([ - 'code' => $code, - 'msg' => $message ?: 'error', - 'data' => $data - ]); + protected + function errorResponse($code, $message, $data = []): Response + { + return Json([ + 'code' => $code, + 'msg' => $message ?: 'error', + 'data' => $data + ]); + } } -} diff --git a/app/process/UpdateGoogleAdsTask.php b/app/process/UpdateGoogleAdsTask.php index 8b61a5a..652bdcd 100644 --- a/app/process/UpdateGoogleAdsTask.php +++ b/app/process/UpdateGoogleAdsTask.php @@ -25,7 +25,7 @@ class UpdateGoogleAdsTask // $dayBeforeYesterdayStart = date('Y-m-d', strtotime('-2 day')); // dump($dayBeforeYesterdayStart . '更新' . GoogleAdsDateDatas::type . '开始'); -// Event::emit(GoogleAdsDateDatas::type, ['customer_id' => 4060397299, 'date' => $dayBeforeYesterdayStart]); +// Event::emit(GoogleAdsDateDatas::type, ['date' => $dayBeforeYesterdayStart]); } ); @@ -34,7 +34,7 @@ class UpdateGoogleAdsTask new Crontab('20 */1 * * * *', function () { // $yesterdayStart = date('Y-m-d', strtotime('-1 day')); // dump($yesterdayStart . '更新' . GoogleAdsDateDatas::type . '开始'); -// Event::emit(GoogleAdsDateDatas::type, ['customer_id' => 4060397299, 'date' => $yesterdayStart]); +// Event::emit(GoogleAdsDateDatas::type, ['date' => $yesterdayStart]); } ); @@ -43,7 +43,7 @@ class UpdateGoogleAdsTask //获取今天的 0 点的YYYY-MM-DD格式 // $todayStart = date('Y-m-d', strtotime('0 day')); // dump($todayStart . '更新' . GoogleAdsDateDatas::type . '开始'); -// Event::emit(GoogleAdsDateDatas::type, ['customer_id' => 4060397299, 'date' => $todayStart]); +// Event::emit(GoogleAdsDateDatas::type, ['date' => $todayStart]); } ); // 每15分钟执行一次 diff --git a/app/service/BaseService.php b/app/service/BaseService.php index a391af9..e3b2794 100644 --- a/app/service/BaseService.php +++ b/app/service/BaseService.php @@ -81,7 +81,7 @@ class BaseService } - /** + /** * 从数据库获取 refreshToken * * @param string $advertiserId 广告主ID diff --git a/app/service/GoogleAdsAdService.php b/app/service/GoogleAdsAdService.php index c444048..3a48e23 100644 --- a/app/service/GoogleAdsAdService.php +++ b/app/service/GoogleAdsAdService.php @@ -43,13 +43,18 @@ use Google\ApiCore\ApiException; class GoogleAdsAdService extends BaseService { private $googleAdsClient; + private $customerId; - public function __construct() + public function __construct($customerId = null) { - $advertiserId = getenv('GOOGLE_ADS_CUSTOMER_ID'); + if ($customerId) { + $this->customerId = $customerId; + } else { + $this->customerId = getenv('GOOGLE_ADS_CUSTOMER_ID'); + } // // // 从数据库获取 access_token - $refreshToken = $this->getRefreshTokenFromDatabase($advertiserId); + $refreshToken = $this->getRefreshTokenFromDatabase($this->customerId); // // if (!$refreshToken) { // throw new \Exception("Access token not found for advertiserId: " . $advertiserId); @@ -264,14 +269,14 @@ class GoogleAdsAdService extends BaseService $ad = AdModel::find($adId); if (!$ad) { // throw new ValidateException('Ad not found'); - return false; + return false; } // 更新数据库中的状态 // $ad->updateStatus($status); - if ($this->modifyDbAdStatus($adId, $status)){ - // 更新 Google Ads 上的状态 + if ($this->modifyDbAdStatus($adId, $status)) { + // 更新 Google Ads 上的状态 $googleAdsClient = $this->googleAdsClient; - $resourceName = self::updateAd($googleAdsClient,$customerId, $adGroupId, $adId, $status); + $resourceName = self::updateAd($googleAdsClient, $customerId, $adGroupId, $adId, $status); return true; } diff --git a/app/service/GoogleAdsCampaignService.php b/app/service/GoogleAdsCampaignService.php index 44f2c22..b9040cd 100644 --- a/app/service/GoogleAdsCampaignService.php +++ b/app/service/GoogleAdsCampaignService.php @@ -42,12 +42,15 @@ class GoogleAdsCampaignService extends BaseService private $customerId; private const NUMBER_OF_CAMPAIGNS_TO_ADD = 1; - public function __construct() + public function __construct($customerId = null) { - $advertiserId = getenv('GOOGLE_ADS_CUSTOMER_ID'); -// + if ($customerId) { + $this->customerId = $customerId; + } else { + $this->customerId = getenv('GOOGLE_ADS_CUSTOMER_ID'); + } // 从数据库获取 access_token - $refreshToken = $this->getRefreshTokenFromDatabase($advertiserId); + $refreshToken = $this->getRefreshTokenFromDatabase($this->customerId); // // if (!$refreshToken) { // throw new \Exception("Access token not found for advertiserId: " . $advertiserId); diff --git a/app/service/GoogleAdsGroupService.php b/app/service/GoogleAdsGroupService.php index ff41b98..12c9511 100644 --- a/app/service/GoogleAdsGroupService.php +++ b/app/service/GoogleAdsGroupService.php @@ -29,13 +29,18 @@ use app\model\AdGroup as AdGroupModel; class GoogleAdsGroupService extends BaseService { private $googleAdsClient; + private $customerId; - public function __construct() + public function __construct($customerId = null) { - $advertiserId = getenv('GOOGLE_ADS_CUSTOMER_ID'); + if ($customerId) { + $this->customerId = $customerId; + } else { + $this->customerId = getenv('GOOGLE_ADS_CUSTOMER_ID'); + } // 从数据库获取 access_token - $refreshToken = $this->getRefreshTokenFromDatabase($advertiserId); + $refreshToken = $this->getRefreshTokenFromDatabase($this->customerId); // // if (!$refreshToken) { // throw new \Exception("Access token not found for advertiserId: " . $advertiserId); diff --git a/app/service/GoogleOAuthService.php b/app/service/GoogleOAuthService.php index 84a0058..14fb547 100644 --- a/app/service/GoogleOAuthService.php +++ b/app/service/GoogleOAuthService.php @@ -4,6 +4,7 @@ namespace app\service; use GuzzleHttp\Client; use think\facade\Db as ThinkDb; +use app\model\ThirdUserAdvertiser; class GoogleOAuthService { @@ -54,11 +55,11 @@ class GoogleOAuthService // $thirdUser->third_type = 'google'; // $thirdUser->user_id = $userId; // $thirdUser->save(); - $data = [ + $data = [ 'access_token' => $refreshToken, 'is_default' => 't', 'third_type' => 'google', - ]; + ]; $tableName = 'bps_third_user'; $tableName = getenv('DB_PG_SCHEMA') ? getenv('DB_PG_SCHEMA') . '.' . $tableName : 'bps' . $tableName; @@ -117,4 +118,29 @@ class GoogleOAuthService } + /** + * 批量获取全部Google广告账号数据 + * + */ + public function getGoogleAdCustomers($options = []) + { + // 获取符合条件的客户ID数组 + $customers = ThirdUserAdvertiser::alias('tua') + ->join('bps.bps_third_user tu', 'tua.doc_ = tu.id') // 连接 bps_third_user 表 + ->where('tu.third_type', 'google') // 筛选 third_type 为 google 的记录 + ->field('tua.advertiser_id') // 获取 advertiser_id 字段 + ->select(); // 执行查询 + + // 如果没有找到符合条件的广告主,抛出异常 + if ($customers->isEmpty()) { + return []; +// throw new ApiException('No customers found for google third type'); + } + + // 转换为简单的数组(提取 advertiser_id) + return $customers->column('advertiser_id'); + + } + + } \ No newline at end of file