49 lines
1.4 KiB
PHP
49 lines
1.4 KiB
PHP
<?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;
|
||
}
|
||
|
||
}
|