动态获取refreshToken

This commit is contained in:
hgc 2024-12-20 18:36:27 +08:00
parent 9da48235e3
commit 27b97ecc0a
5 changed files with 154 additions and 53 deletions

View File

@ -52,7 +52,7 @@ class GoogleAdsAccountService
// [START list_accessible_customers] // [START list_accessible_customers]
public static function runListAccessibleCustomers() public static function runListAccessibleCustomers()
{ {
// Creates a client with the manager customer ID as login customer ID. // Creates a client with the manager customer ID as login customer ID.
$googleAdsClient = self::createGoogleAdsClient(0); $googleAdsClient = self::createGoogleAdsClient(0);
$customerServiceClient = $googleAdsClient->getCustomerServiceClient(); $customerServiceClient = $googleAdsClient->getCustomerServiceClient();
@ -271,35 +271,61 @@ class GoogleAdsAccountService
*/ */
private static function createGoogleAdsClient(int $loginCustomerId) private static function createGoogleAdsClient(int $loginCustomerId)
{ {
// Generates a refreshable OAuth2 credential for authentication. $advertiserId = getenv('GOOGLE_ADS_CUSTOMER_ID');
// 从数据库获取 access_token
$refreshToken = self::getRefreshTokenFromDatabase($advertiserId);
if (!$refreshToken) {
throw new \Exception("Access token not found for advertiserId: " . $advertiserId);
}
// OAuth2 Token Authentication
$oAuth2Credential = (new OAuth2TokenBuilder()) $oAuth2Credential = (new OAuth2TokenBuilder())
// Sets the properties based on the default properties file ->fromFile() // 如果需要从文件获取其他配置,可以继续使用 fromFile()
->fromFile() ->withRefreshToken($refreshToken) // 使用动态获取的 access_token
->build(); ->build();
if($loginCustomerId >0){ if ($loginCustomerId > 0) {
// Builds and returns the Google Ads client // Builds and returns the Google Ads client
return (new GoogleAdsClientBuilder()) return (
// Sets the properties based on the default properties file new GoogleAdsClientBuilder())
->fromFile() // Sets the properties based on the default properties file
// eUses the OAuth2 credentials crated above. ->fromFile()
->withOAuth2Credential($oAuth2Credential) // eUses the OAuth2 credentials crated above.
// Overrides the login customer ID with the given one. ->withOAuth2Credential($oAuth2Credential)
->withLoginCustomerId($loginCustomerId) // Overrides the login customer ID with the given one.
->build(); ->withLoginCustomerId($loginCustomerId)
}else{ ->build();
// Builds and returns the Google Ads client } else {
return (new GoogleAdsClientBuilder()) // Builds and returns the Google Ads client
// Sets the properties based on the default properties file return (new GoogleAdsClientBuilder())
->fromFile() // Sets the properties based on the default properties file
// eUses the OAuth2 credentials crated above. ->fromFile()
->withOAuth2Credential($oAuth2Credential) // eUses the OAuth2 credentials crated above.
// Overrides the login customer ID with the given one. ->withOAuth2Credential($oAuth2Credential)
->build(); // Overrides the login customer ID with the given one.
->build();
} }
} }
// 从数据库动态获取 google RefreshToken
private function getRefreshTokenFromDatabase($advertiserId)
{
// 使用 ThinkDb 进行联表查询
// $advertiserId = 'your-advertiser-id'; // 假设你已经获得了广告商ID
$user = ThinkDb::table('bps_third_user_advertiser as a')
->join('bps_third_user as u', 'a.doc_ = u.id', 'left') // 连接 bps_third_user 表
->where('a.advertiser_id', $advertiserId)
->select('u.access_token') // 只选择 access_token 字段
->first();
return $user ? $user->access_token : null;
}
} }

View File

@ -44,10 +44,20 @@ class GoogleAdsAdService
public function __construct() public function __construct()
{ {
// $this->customerId = getenv('GOOGLE_ADS_CUSTOMER_ID'); $advertiserId = getenv('GOOGLE_ADS_CUSTOMER_ID');
// 从数据库获取 access_token
$refreshToken = $this->getRefreshTokenFromDatabase($advertiserId);
if (!$refreshToken) {
throw new \Exception("Access token not found for advertiserId: " . $advertiserId);
}
// OAuth2 Token Authentication // OAuth2 Token Authentication
$oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build(); $oAuth2Credential = (new OAuth2TokenBuilder())
->fromFile() // 如果需要从文件获取其他配置,可以继续使用 fromFile()
->withRefreshToken($refreshToken) // 使用动态获取的 access_token
->build();
// Google Ads Client initialization // Google Ads Client initialization
$this->googleAdsClient = (new GoogleAdsClientBuilder()) $this->googleAdsClient = (new GoogleAdsClientBuilder())
@ -56,6 +66,20 @@ class GoogleAdsAdService
->build(); ->build();
} }
// 从数据库动态获取 google RefreshToken
private function getRefreshTokenFromDatabase($advertiserId)
{
// 使用 ThinkDb 进行联表查询
// $advertiserId = 'your-advertiser-id'; // 假设你已经获得了广告商ID
$user = ThinkDb::table('bps_third_user_advertiser as a')
->join('bps_third_user as u', 'a.doc_ = u.id', 'left') // 连接 bps_third_user 表
->where('a.advertiser_id', $advertiserId)
->select('u.access_token') // 只选择 access_token 字段
->first();
return $user ? $user->access_token : null;
}
/* @param int $customerId the customer ID /* @param int $customerId the customer ID
@ -87,8 +111,8 @@ class GoogleAdsAdService
{ {
$tableName = 'bps_google_ads_ad'; $tableName = 'bps_google_ads_ad';
$tableName = getenv('DB_PG_SCHEMA') ? getenv('DB_PG_SCHEMA') . '.' . $tableName : 'public' . $tableName; $tableName = getenv('DB_PG_SCHEMA') ? getenv('DB_PG_SCHEMA') . '.' . $tableName : 'public' . $tableName;
foreach ($groupadsResourceName as $data){ foreach ($groupadsResourceName as $data) {
$sql = "INSERT INTO {$tableName} $sql = "INSERT INTO {$tableName}
(ad_id, ad_group_id, customer_id, ad_name, status, resource_name) (ad_id, ad_group_id, customer_id, ad_name, status, resource_name)
VALUES (:ad_id, :ad_group_id, :customer_id, :ad_name, :status, :resource_name) VALUES (:ad_id, :ad_group_id, :customer_id, :ad_name, :status, :resource_name)
ON CONFLICT (ad_id) ON CONFLICT (ad_id)
@ -100,7 +124,7 @@ class GoogleAdsAdService
resource_name = EXCLUDED.resource_name, resource_name = EXCLUDED.resource_name,
update_at = EXCLUDED.update_at"; update_at = EXCLUDED.update_at";
// dump($sql); // dump($sql);
ThinkDb::execute($sql, $data); ThinkDb::execute($sql, $data);
} }
} }
@ -139,18 +163,18 @@ class GoogleAdsAdService
// the campaign in each row. // the campaign in each row.
foreach ($stream->iterateAllElements() as $googleAdsRow) { foreach ($stream->iterateAllElements() as $googleAdsRow) {
/** @var GoogleAdsRow $googleAdsRow */ /** @var GoogleAdsRow $googleAdsRow */
// 假设 $googleAdsRow 是从 Google Ads API 中获取的对象 // 假设 $googleAdsRow 是从 Google Ads API 中获取的对象
// $finalUrlsList = $googleAdsRow->getAdGroupAd()->getAd()->getFinalUrls(); // $finalUrlsList = $googleAdsRow->getAdGroupAd()->getAd()->getFinalUrls();
// 将最终的 URL 列表转换为 PHP 数组 // 将最终的 URL 列表转换为 PHP 数组
// $finalUrlsArray = iterator_to_array($finalUrlsList); // $finalUrlsArray = iterator_to_array($finalUrlsList);
$resourceName['ad_id'] = $googleAdsRow->getAdGroupAd()->getAd()->getId(); $resourceName['ad_id'] = $googleAdsRow->getAdGroupAd()->getAd()->getId();
$resourceName['ad_name'] = $googleAdsRow->getAdGroupAd()->getAd()->getName(); $resourceName['ad_name'] = $googleAdsRow->getAdGroupAd()->getAd()->getName();
$resourceName['ad_group_id'] = $googleAdsRow->getAdGroup()->getId(); $resourceName['ad_group_id'] = $googleAdsRow->getAdGroup()->getId();
$resourceName['customer_id'] = $googleAdsRow->getCustomer()->getId(); $resourceName['customer_id'] = $googleAdsRow->getCustomer()->getId();
// $resourceName['final_urls'] = $finalUrlsArray; // $resourceName['final_urls'] = $finalUrlsArray;
$resourceName['status'] = $googleAdsRow->getAdGroupAd()->getStatus(); $resourceName['status'] = $googleAdsRow->getAdGroupAd()->getStatus();
$resourceName['resource_name'] = $googleAdsRow->getAdGroupAd()->getAd()->getResourceName(); $resourceName['resource_name'] = $googleAdsRow->getAdGroupAd()->getAd()->getResourceName();
$resourceNames[] = $resourceName; $resourceNames[] = $resourceName;
} }
return $resourceNames; return $resourceNames;
} }

View File

@ -43,10 +43,20 @@ class GoogleAdsCampaignService
public function __construct() public function __construct()
{ {
// $this->customerId = getenv('GOOGLE_ADS_CUSTOMER_ID'); $advertiserId = getenv('GOOGLE_ADS_CUSTOMER_ID');
// 从数据库获取 access_token
$refreshToken = $this->getRefreshTokenFromDatabase($advertiserId);
if (!$refreshToken) {
throw new \Exception("Access token not found for advertiserId: " . $advertiserId);
}
// OAuth2 Token Authentication // OAuth2 Token Authentication
$oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build(); $oAuth2Credential = (new OAuth2TokenBuilder())
->fromFile() // 如果需要从文件获取其他配置,可以继续使用 fromFile()
->withRefreshToken($refreshToken) // 使用动态获取的 access_token
->build();
// Google Ads Client initialization // Google Ads Client initialization
$this->googleAdsClient = (new GoogleAdsClientBuilder()) $this->googleAdsClient = (new GoogleAdsClientBuilder())
@ -55,6 +65,21 @@ class GoogleAdsCampaignService
->build(); ->build();
} }
// 从数据库动态获取 google RefreshToken
private function getRefreshTokenFromDatabase($advertiserId)
{
// 使用 ThinkDb 进行联表查询
// $advertiserId = 'your-advertiser-id'; // 假设你已经获得了广告商ID
$user = ThinkDb::table('bps_third_user_advertiser as a')
->join('bps_third_user as u', 'a.doc_ = u.id', 'left') // 连接 bps_third_user 表
->where('a.advertiser_id', $advertiserId)
->select('u.access_token') // 只选择 access_token 字段
->first();
return $user ? $user->access_token : null;
}
/** /**
* Runs the example. * Runs the example.
@ -267,15 +292,15 @@ class GoogleAdsCampaignService
// $googleAdsRow->getCampaignBudget()->getName(), // $googleAdsRow->getCampaignBudget()->getName(),
// PHP_EOL // PHP_EOL
// ); // );
$resourceName['campaign_id'] = $googleAdsRow->getCampaign()->getId(); $resourceName['campaign_id'] = $googleAdsRow->getCampaign()->getId();
$resourceName['campaign_name'] = $googleAdsRow->getCampaign()->getName(); $resourceName['campaign_name'] = $googleAdsRow->getCampaign()->getName();
$resourceName['advertising_channel_type'] = $googleAdsRow->getCampaign()->getAdvertisingChannelType(); $resourceName['advertising_channel_type'] = $googleAdsRow->getCampaign()->getAdvertisingChannelType();
$resourceName['status'] = $googleAdsRow->getCampaign()->getStatus(); $resourceName['status'] = $googleAdsRow->getCampaign()->getStatus();
$resourceName['start_date'] = $googleAdsRow->getCampaign()->getStartDate(); $resourceName['start_date'] = $googleAdsRow->getCampaign()->getStartDate();
$resourceName['end_date'] = $googleAdsRow->getCampaign()->getEndDate(); $resourceName['end_date'] = $googleAdsRow->getCampaign()->getEndDate();
$resourceName['budget_amount_micros'] = $googleAdsRow->getCampaignBudget()->getAmountMicros(); $resourceName['budget_amount_micros'] = $googleAdsRow->getCampaignBudget()->getAmountMicros();
$resourceName['customer_id'] = $googleAdsRow->getCustomer()->getId(); $resourceName['customer_id'] = $googleAdsRow->getCustomer()->getId();
$resourceNames[] = $resourceName; $resourceNames[] = $resourceName;
} }
return $resourceNames; return $resourceNames;
} }
@ -340,7 +365,7 @@ class GoogleAdsCampaignService
public static function saveCampaigns($campaignsResourceName) public static function saveCampaigns($campaignsResourceName)
{ {
$tableName = 'bps_google_ads_campaign'; $tableName = 'bps_google_ads_campaign';
$tableName = getenv('DB_PG_SCHEMA')? getenv('DB_PG_SCHEMA').'.'.$tableName: 'public'.$tableName; $tableName = getenv('DB_PG_SCHEMA') ? getenv('DB_PG_SCHEMA') . '.' . $tableName : 'public' . $tableName;
// foreach ($campaignsResourceName as $data) { // foreach ($campaignsResourceName as $data) {
// $sql = "INSERT INTO {$tableName} // $sql = "INSERT INTO {$tableName}
// (campaign_id, customer_id, campaign_name, status, advertising_channel_type, start_date, end_date, budget_amount_micros) // (campaign_id, customer_id, campaign_name, status, advertising_channel_type, start_date, end_date, budget_amount_micros)
@ -381,7 +406,7 @@ class GoogleAdsCampaignService
// VALUES (:ad_id, :customer_id, :ad_name, :ad_resource_name, :ad_group_id, :campaign_id, :clicks, :cost_micros, :conversions, :conversions_value, :impressions, :date)"; // VALUES (:ad_id, :customer_id, :ad_name, :ad_resource_name, :ad_group_id, :campaign_id, :clicks, :cost_micros, :conversions, :conversions_value, :impressions, :date)";
// ThinkDb::execute($sql, $data); // ThinkDb::execute($sql, $data);
$sql = "INSERT INTO public.bps_google_ad_day_data $sql = "INSERT INTO public.bps_google_ad_day_data
(ad_id, customer_id, ad_name, ad_resource_name, ad_group_id, campaign_id, clicks, cost_micros, conversions, conversions_value, impressions, date) (ad_id, customer_id, ad_name, ad_resource_name, ad_group_id, campaign_id, clicks, cost_micros, conversions, conversions_value, impressions, date)
VALUES (:ad_id, :customer_id, :ad_name, :ad_resource_name, :ad_group_id, :campaign_id, :clicks, :cost_micros, :conversions, :conversions_value, :impressions, :date) VALUES (:ad_id, :customer_id, :ad_name, :ad_resource_name, :ad_group_id, :campaign_id, :clicks, :cost_micros, :conversions, :conversions_value, :impressions, :date)
ON CONFLICT (ad_id, date) -- 假设 (ad_id, date) 为唯一约束 ON CONFLICT (ad_id, date) -- 假设 (ad_id, date) 为唯一约束

View File

@ -30,10 +30,20 @@ class GoogleAdsGroupService
public function __construct() public function __construct()
{ {
// $this->customerId = getenv('GOOGLE_ADS_CUSTOMER_ID'); $advertiserId = getenv('GOOGLE_ADS_CUSTOMER_ID');
// 从数据库获取 access_token
$refreshToken = $this->getRefreshTokenFromDatabase($advertiserId);
if (!$refreshToken) {
throw new \Exception("Access token not found for advertiserId: " . $advertiserId);
}
// OAuth2 Token Authentication // OAuth2 Token Authentication
$oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build(); $oAuth2Credential = (new OAuth2TokenBuilder())
->fromFile() // 如果需要从文件获取其他配置,可以继续使用 fromFile()
->withRefreshToken($refreshToken) // 使用动态获取的 access_token
->build();
// Google Ads Client initialization // Google Ads Client initialization
$this->googleAdsClient = (new GoogleAdsClientBuilder()) $this->googleAdsClient = (new GoogleAdsClientBuilder())
@ -43,6 +53,22 @@ class GoogleAdsGroupService
} }
// 从数据库动态获取 google RefreshToken
private function getRefreshTokenFromDatabase($advertiserId)
{
// 使用 ThinkDb 进行联表查询
// $advertiserId = 'your-advertiser-id'; // 假设你已经获得了广告商ID
$user = ThinkDb::table('bps_third_user_advertiser as a')
->join('bps_third_user as u', 'a.doc_ = u.id', 'left') // 连接 bps_third_user 表
->where('a.advertiser_id', $advertiserId)
->select('u.access_token') // 只选择 access_token 字段
->first();
return $user ? $user->access_token : null;
}
/* @param int $customerId the customer ID /* @param int $customerId the customer ID
* @param $options * @param $options
* @return mixed * @return mixed

View File

@ -32,7 +32,7 @@ loginCustomerId = 1509096882
; For installed application flow. ; For installed application flow.
clientId = "117429539543-t73vtg7v1vag5b2dg68qaaaj00gmacjs.apps.googleusercontent.com" clientId = "117429539543-t73vtg7v1vag5b2dg68qaaaj00gmacjs.apps.googleusercontent.com"
clientSecret = "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" clientSecret = "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"
refreshToken = "1//0eNpv3UrnIRMaCgYIARAAGA4SNwF-L9Ir_W9Fs5CrdW_7IFjRkq2nA6TZwSyi9Y8ukj8nirWt3BvOR74j3HatYX3cug7vfzGPUhs" ;refreshToken = "1//0eNpv3UrnIRMaCgYIARAAGA4SNwF-L9Ir_W9Fs5CrdW_7IFjRkq2nA6TZwSyi9Y8ukj8nirWt3BvOR74j3HatYX3cug7vfzGPUhs"
; For service account flow. ; For service account flow.
; jsonKeyFilePath = "INSERT_ABSOLUTE_PATH_TO_OAUTH2_JSON_KEY_FILE_HERE" ; jsonKeyFilePath = "INSERT_ABSOLUTE_PATH_TO_OAUTH2_JSON_KEY_FILE_HERE"