65 lines
1.9 KiB
PHP
65 lines
1.9 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;
|
||
private $googleAdsClientWithloginCustomerId;
|
||
|
||
public function __construct($refreshToken = null, $loginCustomerId = 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: " . $refreshToken);
|
||
}
|
||
|
||
// OAuth2 Token Authentication
|
||
$oAuth2Credential = (new OAuth2TokenBuilder())
|
||
->fromFile() // 如果需要从文件获取其他配置
|
||
->withRefreshToken($refreshToken) // 使用动态获取的 access_token
|
||
->build();
|
||
|
||
// 初始化 Google Ads Client
|
||
if ($loginCustomerId) {
|
||
$this->googleAdsClientWithloginCustomerId = (new GoogleAdsClientBuilder())
|
||
->fromFile()
|
||
->withOAuth2Credential($oAuth2Credential)
|
||
->withLoginCustomerId($loginCustomerId)
|
||
->build();
|
||
} else {
|
||
$this->googleAdsClient = (new GoogleAdsClientBuilder())
|
||
->fromFile()
|
||
->withOAuth2Credential($oAuth2Credential)
|
||
->build();
|
||
}
|
||
|
||
|
||
}
|
||
|
||
public function getGoogleAdsClient()
|
||
{
|
||
return $this->googleAdsClient;
|
||
}
|
||
|
||
public function getGoogleAdsClientWithloginCustomerId()
|
||
{
|
||
return $this->googleAdsClientWithloginCustomerId;
|
||
}
|
||
|
||
}
|