From 2033c3c46c667a311644632b459ae9713c20f52f Mon Sep 17 00:00:00 2001
From: hgc <yellowrna@gmail.com>
Date: Wed, 25 Dec 2024 15:44:29 +0800
Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E6=9C=8D=E5=8A=A1?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 app/service/GoogleAdsAdService.php       | 61 +++++++------------
 app/service/GoogleAdsCampaignService.php | 75 ++++++++++--------------
 app/service/GoogleAdsClientService.php   | 48 +++++++++++++++
 app/service/GoogleAdsGroupService.php    | 50 +++++-----------
 4 files changed, 115 insertions(+), 119 deletions(-)
 create mode 100644 app/service/GoogleAdsClientService.php

diff --git a/app/service/GoogleAdsAdService.php b/app/service/GoogleAdsAdService.php
index 1453f62..c2baebe 100644
--- a/app/service/GoogleAdsAdService.php
+++ b/app/service/GoogleAdsAdService.php
@@ -2,16 +2,13 @@
 
 namespace app\service;
 
-
+use app\service\GoogleAdsClientService;
 use app\model\ThirdUserAdvertiser;
 use app\util\Helper;
 use app\util\ArgumentNames;
 use app\util\ArgumentParser;
 
 use Google\Ads\GoogleAds\Lib\V18\GoogleAdsClient;
-use Google\Ads\GoogleAds\Lib\V18\GoogleAdsClientBuilder;
-use Google\Ads\GoogleAds\Lib\V18\GoogleAdsException;
-use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
 use Google\Ads\GoogleAds\Util\FieldMasks;
 use Google\Ads\GoogleAds\Util\V18\ResourceNames;
 use Google\Ads\GoogleAds\V18\Common\ResponsiveSearchAdInfo;
@@ -42,35 +39,12 @@ use Google\ApiCore\ApiException;
 
 class GoogleAdsAdService extends BaseService
 {
-    private $googleAdsClient;
+//    private $googleAdsClient;
     private $customerId;
 
     public function __construct($customerId = null)
     {
-        if ($customerId) {
-            $this->customerId = $customerId;
-        } else {
-            $this->customerId = getenv('GOOGLE_ADS_CUSTOMER_ID');
-        }
-//
-//        // 从数据库获取 access_token
-        $refreshToken = $this->getRefreshTokenFromDatabase($this->customerId);
-//
-//        if (!$refreshToken) {
-//            throw new \Exception("Access token not found for advertiserId: " . $advertiserId);
-//        }
 
-        // OAuth2 Token Authentication
-        $oAuth2Credential = (new OAuth2TokenBuilder())
-            ->fromFile() // 如果需要从文件获取其他配置,可以继续使用 fromFile()
-            ->withRefreshToken($refreshToken) // 使用动态获取的 access_token
-            ->build();
-
-        // Google Ads Client initialization
-        $this->googleAdsClient = (new GoogleAdsClientBuilder())
-            ->fromFile()
-            ->withOAuth2Credential($oAuth2Credential)
-            ->build();
     }
 
     // 从数据库动态获取 google RefreshToken
@@ -99,9 +73,11 @@ class GoogleAdsAdService extends BaseService
     public function runListAds(int $customerId): mixed
     {
 
-        $googleAdsClient = $this->googleAdsClient;
+//        $googleAdsClient = $this->googleAdsClient;
+        $googleAdsClient = new GoogleAdsClientService($customerId);
+
         // Creates a single shared budget to be used by the campaigns added below.
-        $groupAdsResourceName = self::getAds($googleAdsClient, $customerId);
+        $groupAdsResourceName = self::getAds($googleAdsClient->getGoogleAdsClient(), $customerId);
 //        dump(json_encode($groupadsResourceName));
         if (is_array($groupAdsResourceName)) {
             self::saveAds($groupAdsResourceName);
@@ -204,10 +180,11 @@ class GoogleAdsAdService extends BaseService
      */
     public function runUpdateAd($options): mixed
     {
-        $googleAdsClient = $this->googleAdsClient;
+//        $googleAdsClient = $this->googleAdsClient;
+        $googleAdsClient = new GoogleAdsClientService($options['customer_id']);
         // Creates a single shared budget to be used by the campaigns added below.
 
-        $resourceNames = self::updateAd($googleAdsClient, $options['customer_id'], $options['group_id'], $options['ad_id'], $options['status']);
+        $resourceNames = self::updateAd($googleAdsClient->getGoogleAdsClient(), $options['customer_id'], $options['group_id'], $options['ad_id'], $options['status']);
 
         return $resourceNames;
     }
@@ -278,8 +255,9 @@ class GoogleAdsAdService extends BaseService
 //        $ad->updateStatus($status);
         if ($this->modifyDbAdStatus($adId, $status)) {
             // 更新 Google Ads 上的状态
-            $googleAdsClient = $this->googleAdsClient;
-            $resourceName    = self::updateAd($googleAdsClient, $customerId, $adGroupId, $adId, $status);
+//            $googleAdsClient = $this->googleAdsClient;
+            $googleAdsClient = new GoogleAdsClientService($customerId);
+            $resourceName    = self::updateAd($googleAdsClient->getGoogleAdsClient(), $customerId, $adGroupId, $adId, $status);
             return true;
         }
 
@@ -354,12 +332,13 @@ class GoogleAdsAdService extends BaseService
      */
     public function runGetResponsiveSearchAds($options): mixed
     {
-        $googleAdsClient = $this->googleAdsClient;
+//        $googleAdsClient = $this->googleAdsClient;
+        $googleAdsClient = new GoogleAdsClientService($options['customer_id']);
         // Creates a single shared budget to be used by the campaigns added below.
         if (!isset($options['group_id'])) {
             $options['group_id'] = null;
         }
-        $resourceNames = self::getResponsiveSearchAds($googleAdsClient, $options['customer_id'], $options['group_id']);
+        $resourceNames = self::getResponsiveSearchAds($googleAdsClient->getGoogleAdsClient(), $options['customer_id'], $options['group_id']);
 
         return $resourceNames;
     }
@@ -468,9 +447,10 @@ class GoogleAdsAdService extends BaseService
      */
     public function runUpdateResponsiveSearchAd($options): mixed
     {
-        $googleAdsClient = $this->googleAdsClient;
+//        $googleAdsClient = $this->googleAdsClient;
+        $googleAdsClient = new GoogleAdsClientService($options['customer_id']);
         // Creates a single shared budget to be used by the campaigns added below.
-        $resourceName = self::updateResponsiveSearchAd($googleAdsClient, $options['customer_id'], $options['ad_id']);
+        $resourceName = self::updateResponsiveSearchAd($googleAdsClient->getGoogleAdsClient(), $options['customer_id'], $options['ad_id']);
 
         return $resourceName;
     }
@@ -547,9 +527,10 @@ class GoogleAdsAdService extends BaseService
      */
     public function runSearchForGoogleAdsFields($options): mixed
     {
-        $googleAdsClient = $this->googleAdsClient;
+//        $googleAdsClient = $this->googleAdsClient;
+        $googleAdsClient = new GoogleAdsClientService($options['customer_id']);
         // Creates a single shared budget to be used by the campaigns added below.
-        $googleAdsFieldData = self::searchForGoogleAdsFields($googleAdsClient, $options['name_prefix']);
+        $googleAdsFieldData = self::searchForGoogleAdsFields($googleAdsClient->getGoogleAdsClient(), $options['name_prefix']);
 
         return $googleAdsFieldData;
     }
diff --git a/app/service/GoogleAdsCampaignService.php b/app/service/GoogleAdsCampaignService.php
index b9040cd..dae2a8d 100644
--- a/app/service/GoogleAdsCampaignService.php
+++ b/app/service/GoogleAdsCampaignService.php
@@ -2,15 +2,12 @@
 
 namespace app\service;
 
-
+use app\service\GoogleAdsClientService;
 use app\model\ThirdUserAdvertiser;
 use app\util\Helper;
 use app\util\ArgumentNames;
 use app\util\ArgumentParser;
 use Google\Ads\GoogleAds\Lib\V18\GoogleAdsClient;
-use Google\Ads\GoogleAds\Lib\V18\GoogleAdsClientBuilder;
-use Google\Ads\GoogleAds\Lib\V18\GoogleAdsException;
-use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
 use Google\Ads\GoogleAds\Lib\V18\GoogleAdsServerStreamDecorator;
 use Google\Ads\GoogleAds\Util\FieldMasks;
 use Google\Ads\GoogleAds\Util\V18\ResourceNames;
@@ -32,6 +29,7 @@ use Google\Ads\GoogleAds\V18\Services\SearchGoogleAdsRequest;
 use Google\Ads\GoogleAds\V18\Services\SearchGoogleAdsResponse;
 use app\model\Campaign as CampaignModel;
 use app\model\DayData as DayDataModel;
+use Monolog\Handler\NewRelicHandler;
 use think\facade\Db as ThinkDb;
 
 use Google\ApiCore\ApiException;
@@ -42,31 +40,11 @@ class GoogleAdsCampaignService extends BaseService
     private $customerId;
     private const NUMBER_OF_CAMPAIGNS_TO_ADD = 1;
 
-    public function __construct($customerId = null)
+    public function __construct($customerId = null,GoogleAdsClientService $googleAdsClientService = null)
     {
-        if ($customerId) {
-            $this->customerId = $customerId;
-        } else {
-            $this->customerId = getenv('GOOGLE_ADS_CUSTOMER_ID');
-        }
-        // 从数据库获取 access_token
-        $refreshToken = $this->getRefreshTokenFromDatabase($this->customerId);
-//
-//        if (!$refreshToken) {
-//            throw new \Exception("Access token not found for advertiserId: " . $advertiserId);
-//        }
-
-        // OAuth2 Token Authentication
-        $oAuth2Credential = (new OAuth2TokenBuilder())
-            ->fromFile() // 如果需要从文件获取其他配置,可以继续使用 fromFile()
-            ->withRefreshToken($refreshToken) // 使用动态获取的 access_token
-            ->build();
-
-        // Google Ads Client initialization
-        $this->googleAdsClient = (new GoogleAdsClientBuilder())
-            ->fromFile()
-            ->withOAuth2Credential($oAuth2Credential)
-            ->build();
+        // 使用 GoogleAdsClientService 来初始化 googleAdsClient
+//        $googleAdsClient = new GoogleAdsClientService($customerId);
+//         $this->googleAdsClient = $googleAdsClient->getGoogleAdsClient();
     }
 
     // 从数据库动态获取 google RefreshToken
@@ -97,9 +75,10 @@ class GoogleAdsCampaignService extends BaseService
      */
     public function runAddCampaign(int $customerId, $options): mixed
     {
-        $googleAdsClient = $this->googleAdsClient;
+        $googleAdsClient = new GoogleAdsClientService($customerId);
+
         // Creates a single shared budget to be used by the campaigns added below.
-        $budgetResourceName = self::addCampaignBudget($googleAdsClient, $customerId, $options);
+        $budgetResourceName = self::addCampaignBudget($googleAdsClient->getGoogleAdsClient(), $customerId, $options);
 
         // Configures the campaign network options.
         $networkSettings = new NetworkSettings([
@@ -168,9 +147,10 @@ class GoogleAdsCampaignService extends BaseService
 //        if(!$customerId){
 //            $customerId = $this->customerId;
 //        }
-        $googleAdsClient = $this->googleAdsClient;
+//        $googleAdsClient = $this->googleAdsClient;
+        $googleAdsClient = new GoogleAdsClientService($customerId);
         // Creates a single shared budget to be used by the campaigns added below.
-        $budgetResourceName = self::addCampaignBudget($googleAdsClient, $customerId, $options);
+        $budgetResourceName = self::addCampaignBudget($googleAdsClient->getGoogleAdsClient(), $customerId, $options);
 
         return $budgetResourceName;
     }
@@ -222,9 +202,10 @@ class GoogleAdsCampaignService extends BaseService
     public function runListCampaigns(int $customerId): mixed
     {
 
-        $googleAdsClient = $this->googleAdsClient;
+//        $googleAdsClient = $this->googleAdsClient;
+         $googleAdsClient = new GoogleAdsClientService($customerId);
         // Creates a single shared budget to be used by the campaigns added below.
-        $campaignsResourceName = self::getCampaigns($googleAdsClient, $customerId);
+        $campaignsResourceName = self::getCampaigns($googleAdsClient->getGoogleAdsClient(), $customerId);
 //        dump(json_encode($campaignsResourceName));
         if (is_array($campaignsResourceName)) {
             self::saveCampaigns($campaignsResourceName);
@@ -241,9 +222,10 @@ class GoogleAdsCampaignService extends BaseService
     public function runListDateDatas(int $customerId, $date): mixed
     {
 
-        $googleAdsClient = $this->googleAdsClient;
+//        $googleAdsClient = $this->googleAdsClient;
+        $googleAdsClient = new GoogleAdsClientService($customerId);
         // Creates a single shared budget to be used by the campaigns added below.
-        $dayResourceName = self::getDateDatas($googleAdsClient, $customerId, $date);
+        $dayResourceName = self::getDateDatas($googleAdsClient->getGoogleAdsClient(), $customerId, $date);
 //        dump(json_encode($dayResourceName));
         if (is_array($dayResourceName)) {
             self::saveDateDatas($dayResourceName);
@@ -441,9 +423,10 @@ class GoogleAdsCampaignService extends BaseService
      */
     public function runListCampaignsNext($options): mixed
     {
-        $googleAdsClient = $this->googleAdsClient;
+//        $googleAdsClient = $this->googleAdsClient;
+        $googleAdsClient = new GoogleAdsClientService($options['customer_id']);
         // Creates a single shared budget to be used by the campaigns added below.
-        $campaigns = self::getCampaignsNext($googleAdsClient, $options['customer_id'], $options['page_token']);
+        $campaigns = self::getCampaignsNext($googleAdsClient->getGoogleAdsClient(), $options['customer_id'], $options['page_token']);
 
         return $campaigns;
     }
@@ -551,9 +534,11 @@ class GoogleAdsCampaignService extends BaseService
      */
     public function runRemoveCampaign($options): mixed
     {
-        $googleAdsClient = $this->googleAdsClient;
+//        $googleAdsClient = $this->googleAdsClient;
+        $googleAdsClient = new GoogleAdsClientService($options['customer_id']);
+
         // Creates a single shared budget to be used by the campaigns added below.
-        $resourceName = self::removeCampaign($googleAdsClient, $options['customer_id'], $options['campaign_id']);
+        $resourceName = self::removeCampaign($googleAdsClient->getGoogleAdsClient(), $options['customer_id'], $options['campaign_id']);
 
         return $resourceName;
     }
@@ -605,9 +590,10 @@ class GoogleAdsCampaignService extends BaseService
      */
     public function runUpdateCampaign($options): mixed
     {
-        $googleAdsClient = $this->googleAdsClient;
+
+        $googleAdsClient = new GoogleAdsClientService($options['customer_id']);
         // Creates a single shared budget to be used by the campaigns added below.
-        $resourceName = self::updateCampaign($googleAdsClient, $options['customer_id'], $options['campaign_id'], $options['status']);
+        $resourceName = self::updateCampaign($googleAdsClient->getGoogleAdsClient(), $options['customer_id'], $options['campaign_id'], $options['status']);
 
         return $resourceName;
     }
@@ -676,8 +662,9 @@ class GoogleAdsCampaignService extends BaseService
         // 更新本地数据库的状态
         if ($this->modifyDbCampaignStatus($campaignId, $status)) {
             // 更新 Google Ads 上的状态
-            $googleAdsClient = $this->googleAdsClient;
-            $resourceName    = self::updateCampaign($googleAdsClient, $customerId, $campaignId, $status);
+//            $googleAdsClient = $this->googleAdsClient;
+            $googleAdsClient = new GoogleAdsClientService($customerId);
+            $resourceName    = self::updateCampaign($googleAdsClient->getGoogleAdsClient(), $customerId, $campaignId, $status);
             return true;
         }
         return false;
diff --git a/app/service/GoogleAdsClientService.php b/app/service/GoogleAdsClientService.php
new file mode 100644
index 0000000..629a6c1
--- /dev/null
+++ b/app/service/GoogleAdsClientService.php
@@ -0,0 +1,48 @@
+<?php
+
+namespace app\service;
+
+use Google\Ads\GoogleAds\Lib\V18\GoogleAdsClientBuilder;
+use Google\Ads\GoogleAds\Lib\V18\GoogleAdsException;
+use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
+// GoogleAdsClientService.php
+class GoogleAdsClientService extends BaseService
+{
+    private $googleAdsClient;
+
+    public function __construct($customerId = null)
+    {
+        // 如果没有传入 customerId,则从环境变量中获取
+        if ($customerId) {
+            $this->customerId = $customerId;
+        } else {
+            $this->customerId = getenv('GOOGLE_ADS_CUSTOMER_ID');
+        }
+
+        // 从数据库获取 refreshToken
+        $refreshToken = $this->getRefreshTokenFromDatabase($this->customerId);
+
+        if (!$refreshToken) {
+            throw new \Exception("Access token not found for customerId: " . $this->customerId);
+        }
+
+        // OAuth2 Token Authentication
+        $oAuth2Credential = (new OAuth2TokenBuilder())
+            ->fromFile() // 如果需要从文件获取其他配置
+            ->withRefreshToken($refreshToken) // 使用动态获取的 access_token
+            ->build();
+
+        // 初始化 Google Ads Client
+        $this->googleAdsClient = (new GoogleAdsClientBuilder())
+            ->fromFile()
+            ->withOAuth2Credential($oAuth2Credential)
+            ->build();
+
+    }
+
+    public function getGoogleAdsClient()
+    {
+        return $this->googleAdsClient;
+    }
+
+}
diff --git a/app/service/GoogleAdsGroupService.php b/app/service/GoogleAdsGroupService.php
index 12c9511..e074b6c 100644
--- a/app/service/GoogleAdsGroupService.php
+++ b/app/service/GoogleAdsGroupService.php
@@ -2,16 +2,14 @@
 
 namespace app\service;
 
-
+use app\service\GoogleAdsClientService;
 use app\model\ThirdUserAdvertiser;
 use app\util\Helper;
 use app\util\ArgumentNames;
 use app\util\ArgumentParser;
 
 use Google\Ads\GoogleAds\Lib\V18\GoogleAdsClient;
-use Google\Ads\GoogleAds\Lib\V18\GoogleAdsClientBuilder;
-use Google\Ads\GoogleAds\Lib\V18\GoogleAdsException;
-use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
+
 use Google\Ads\GoogleAds\Util\FieldMasks;
 use Google\Ads\GoogleAds\Util\V18\ResourceNames;
 use Google\Ads\GoogleAds\V18\Enums\AdGroupStatusEnum\AdGroupStatus;
@@ -33,30 +31,7 @@ class GoogleAdsGroupService extends BaseService
 
     public function __construct($customerId = null)
     {
-        if ($customerId) {
-            $this->customerId = $customerId;
-        } else {
-            $this->customerId = getenv('GOOGLE_ADS_CUSTOMER_ID');
-        }
 
-        // 从数据库获取 access_token
-        $refreshToken = $this->getRefreshTokenFromDatabase($this->customerId);
-//
-//        if (!$refreshToken) {
-//            throw new \Exception("Access token not found for advertiserId: " . $advertiserId);
-//        }
-
-        // OAuth2 Token Authentication
-        $oAuth2Credential = (new OAuth2TokenBuilder())
-            ->fromFile() // 如果需要从文件获取其他配置,可以继续使用 fromFile()
-            ->withRefreshToken($refreshToken) // 使用动态获取的 access_token
-            ->build();
-
-        // Google Ads Client initialization
-        $this->googleAdsClient = (new GoogleAdsClientBuilder())
-            ->fromFile()
-            ->withOAuth2Credential($oAuth2Credential)
-            ->build();
     }
 
 
@@ -86,9 +61,10 @@ class GoogleAdsGroupService extends BaseService
     public function runListGroups(int $customerId): mixed
     {
 
-        $googleAdsClient = $this->googleAdsClient;
+//        $googleAdsClient = $this->googleAdsClient;
+        $googleAdsClient = new GoogleAdsClientService($customerId);
         // Creates a single shared budget to be used by the campaigns added below.
-        $groupsResourceName = self::getGroups($googleAdsClient, $customerId);
+        $groupsResourceName = self::getGroups($googleAdsClient->getGoogleAdsClient(), $customerId);
 //        dump(json_encode($groupsResourceName));
         if (is_array($groupsResourceName)) {
             self::saveGroups($groupsResourceName);
@@ -192,9 +168,10 @@ class GoogleAdsGroupService extends BaseService
      */
     public function runAddGroup($options): mixed
     {
-        $googleAdsClient = $this->googleAdsClient;
+//        $googleAdsClient = $this->googleAdsClient;
+        $googleAdsClient = new GoogleAdsClientService($customerId);
         // Creates a single shared budget to be used by the campaigns added below.
-        $resourceNames = self::addGroup($googleAdsClient, $options['customer_id'], $options['campaign_id']);
+        $resourceNames = self::addGroup($googleAdsClient->getGoogleAdsClient(), $options['customer_id'], $options['campaign_id']);
 
         return $resourceNames;
     }
@@ -274,11 +251,12 @@ class GoogleAdsGroupService extends BaseService
      */
     public function runUpdateGroup($options): mixed
     {
-        $googleAdsClient = $this->googleAdsClient;
+//        $googleAdsClient = $this->googleAdsClient;
+        $googleAdsClient = new GoogleAdsClientService($options['customer_id']);
         // Creates a single shared budget to be used by the campaigns added below.
 
 //        $resourceNames = self::updateGroup($googleAdsClient, $options['customer_id'], $options['group_id'],  $options['status'], $options['bid_micro_amount'],);
-        $resourceNames = self::updateGroup($googleAdsClient, $options['customer_id'], $options['group_id'], $options['status']);
+        $resourceNames = self::updateGroup($googleAdsClient->getGoogleAdsClient(), $options['customer_id'], $options['group_id'], $options['status']);
 
         return $resourceNames;
     }
@@ -352,8 +330,10 @@ class GoogleAdsGroupService extends BaseService
 //        $adGroup->updateStatus($status);
         if ($this->modifyDbGroupStatus($adGroupId, $status)) {
             // 更新 Google Ads 上的状态
-            $googleAdsClient = $this->googleAdsClient;
-            $resourceName    = self::updateGroup($googleAdsClient, $customerId, $adGroupId, $status);
+//            $googleAdsClient = $this->googleAdsClient;
+             $googleAdsClient = new GoogleAdsClientService($customerId);
+
+            $resourceName    = self::updateGroup($googleAdsClient->getGoogleAdsClient(), $customerId, $adGroupId, $status);
             return true;
         }