更新层级账号的是否test、是否经理的判定和采集

This commit is contained in:
hgc 2025-01-04 15:16:11 +08:00
parent bf7b16c1e0
commit dbdca8658d
16 changed files with 358 additions and 135 deletions

View File

@ -8,6 +8,7 @@ use Google\ApiCore\ApiException;
use support\Request;
use support\Response;
use DI\Annotation\Inject;
//use app\model\ThirdUserAdvertiser;
class CustomerController
@ -55,21 +56,37 @@ class CustomerController
public function accessibleCustomers(Request $request)
{
$options = $request->all();
$options = $request->all();
$options['refresh_token'] = $request->refresh_token;
$options['login_customer_id'] = $request->login_customer_id;
// 继续处理 Google Ads API 操作
return $this->listAccessibleCustomers($options);
}
public function accountHierarchy(Request $request)
{
$options = $request->all();
$options = $request->all();
$options['refresh_token'] = $request->refresh_token;
$options['login_customer_id'] = $request->login_customer_id;
// 继续处理 Google Ads API 操作
return $this->getAccountHierarchy($options);
}
//管理用户访问权限
public function accountAccess(Request $request)
{
$options = $request->all();
/**
$options['refresh_token'] = $request->refresh_token;
$options['login_customer_id'] = $request->login_customer_id;
// 继续处理 Google Ads API 操作
return $this->getAccountAccess($options);
}
/**
* 关联广告客户ID
* @throws ApiException
*/
@ -85,10 +102,23 @@ class CustomerController
*/
public function getAccountHierarchy($options): Response
{
// dump($options);
$resourceName = $this->googleAdsAccountService->runGetAccountHierarchy($options);
return $this->successResponse(['links_resource_name' => $resourceName]);
}
/**
* 管理用户访问权限
* @throws ApiException
*/
public function getAccountAccess($options): Response
{
// dump($options);
$resourceName = $this->googleAdsAccountService->runGetAccountAccess($options);
return $this->successResponse(['links_resource_name' => $resourceName]);
}
// 可以加入一些公共方法
protected function successResponse($data): Response

View File

@ -107,7 +107,7 @@ class GoogleAdsController
if($options['asset_type'] == 2){
return $this->getVideoAssetRelations($options);
}elseif($options['asset_type'] == 4){
$this->getAssetRelations($options);
return $this->getAssetRelations($options);
}
}
@ -287,8 +287,11 @@ class GoogleAdsController
*/
public function getAssetRelations($options): Response
{
// dump($options);
$resourceName = $this->googleAdsAssetRelationService->runListAssetRelations($options['customer_id']);
return $this->successResponse(['assets_relation_list' => $resourceName]);
// dump($resourceName);
// return $this->successResponse($resourceName);
return $this->successResponse(['assets_list' => $resourceName]);
// return $this->successResponse(['assets_relation_list' => 'succeed added']);
}
@ -309,7 +312,9 @@ class GoogleAdsController
*/
public function getDateDatas($options): Response
{
$resourceName = $this->googleAdsCampaignService->runListDateDatas($options['customer_id'], '2024-12-18');
$options['login_customer_id'] = 1509096882;
$options['refresh_token'] = '1//0eOTBBKbP-sPACgYIARAAGA4SNwF-L9Irg1hApAtVpZfvSCKX_pSSV2CJ7Fye3m1p3Nw12VbCjJ2Ey2D02dVy5iDhCET79TfWY0s';
$resourceName = $this->googleAdsCampaignService->runListDateDatas($options['customer_id'],$options, '2025-01-04');
return $this->successResponse(['date_datas_list' => $resourceName]);
}
@ -390,6 +395,7 @@ class GoogleAdsController
if (!in_array($options['status'], $adGroupStatus)) {
return $this->errorResponse(101, 'status参数错误');
}
// dump($options['status'],$adGroupStatus);
$resourceName = $this->googleAdsAdService->runUpdateAd($options);
return $this->successResponse(['ad_updated' => $resourceName]);
}

View File

@ -101,10 +101,10 @@ class OAuthController
// $customerId = isset($requestData['customer_id']) ? $requestData['customer_id'] : getenv('GOOGLE_ADS_CUSTOMER_ID');
// $customerId = getenv('GOOGLE_ADS_CUSTOMER_ID'); //临时指定
$uid = $request->input('user_id');
$uid = $request->input('user_id') ?? $request->jwtClaims['uid'];
// 通过 advertiser_id 查询 ThirdUserAdvertiser联表查询 ThirdUser 数据
$thirdUser = ThirdUser::where('user_id', $uid)->find(); // 获取第一个结果
$thirdUser = ThirdUser::where('user_id', $uid)->where('third_type', 'google')->find(); // 获取第一个结果
// dump($thirdUser); return ($uid);
if (!$thirdUser) {
return $this->errorResponse(300, '未授权');
@ -120,7 +120,7 @@ class OAuthController
//保存某个主体的全部access广告账号
function saveAdvertisers(Request $request)
public function saveAdvertisers(Request $request)
{
$customerIds = $request->input('third_user_list_customers'); // customer_id_list每个元素包含advertiser_id

View File

@ -57,7 +57,10 @@ class GoogleAdsAds
$customers = $this->googleOAuthService->getGoogleAdCustomers([]);
foreach ($customers as $customer) {
$googleAdsAdService = new GoogleAdsAdService($customer['customer_id']);
$resourceName = $googleAdsAdService->runListAds($customer['customer_id'],$customer);
if ($customer['login_customer_id'] >0){
$resourceName = $googleAdsAdService->runListAds($customer['customer_id'],$customer);
}
}
// return $this->successResponse(['ads_list' => $resourceName]);

View File

@ -58,12 +58,16 @@ class GoogleAdsAssetRelations
$customers = $this->googleOAuthService->getGoogleAdCustomers([]);
foreach ($customers as $customer) {
// dump($customer);
$googleAdsAssetRelationService = new GoogleAdsAssetRelationService($customer['customer_id']);
$resourceName = $googleAdsAssetRelationService->runListAssetRelations($customer['customer_id']);
if ($customer['login_customer_id'] > 0) {
$googleAdsAssetRelationService = new GoogleAdsAssetRelationService($customer['customer_id']);
$resourceName = $googleAdsAssetRelationService->runListAssetRelations($customer['customer_id']);
}
}
// return $this->successResponse(['ads_list' => $resourceName]);
return $this->successResponse(['ads_list' => $resourceName]);
}
/**
* get asset relations
* @throws ApiException
@ -73,7 +77,7 @@ class GoogleAdsAssetRelations
$customers = $this->googleOAuthService->getGoogleAdCustomers([]);
foreach ($customers as $customer) {
$googleAdsAssetRelationService = new GoogleAdsAssetRelationService($customer['customer_id']);
$resourceName = $googleAdsAssetRelationService->runListVideoAssetRelations($customer['customer_id']);
$resourceName = $googleAdsAssetRelationService->runListVideoAssetRelations($customer['customer_id']);
}
// return $this->successResponse(['ads_list' => $resourceName]);

View File

@ -57,7 +57,10 @@ class GoogleAdsAssets
$customers = $this->googleOAuthService->getGoogleAdCustomers([]);
foreach ($customers as $customer) {
$googleAdsAssetService = new GoogleAdsAssetService($customer['customer_id']);
$resourceName = $googleAdsAssetService->runListAssets($customer['customer_id'],$customer);
if ($customer['login_customer_id'] >0){
$resourceName = $googleAdsAssetService->runListAssets($customer['customer_id'],$customer);
}
}
// return $this->successResponse(['ads_list' => $resourceName]);

View File

@ -62,7 +62,10 @@ class GoogleAdsCampaigns
// dump($customers);
foreach ($customers as $customer) {
$googleAdsCampaignService = new googleAdsCampaignService($customer['customer_id']);
$resourceName = $googleAdsCampaignService->runListCampaigns($customer['customer_id'],$customer);
if ($customer['login_customer_id'] >0){
$resourceName = $googleAdsCampaignService->runListCampaigns($customer['customer_id'],$customer);
}
}
// return $this->successResponse(['campaigns_list' => $resourceName]);
}

View File

@ -55,25 +55,38 @@ class GoogleAdsCustomers
{
// dump($options);
$thirdUser = ThirdUser::where('is_default', 'f')->where('third_type', 'google')
->find();
if (getenv('GOOGLE_DEVELOP_TOKEN_LEVEL') === 'test') {
$option['manager_customer_id'] = '1401879025'; //开发者
$option['login_customer_id'] = '1401879025';
->find();
if (!$thirdUser || !$thirdUser->access_token) {
dump('not found third user');
return;
}
$option['refresh_token'] = $thirdUser->access_token;
// dump($option);
$listAccessibleCustomers = $this->googleAdsAccountService->runListAccessibleCustomers($option);
// dump($listAccessibleCustomers);
if (getenv('GOOGLE_DEVELOP_TOKEN_LEVEL') === 'test') {
if (in_array(1509096882, $listAccessibleCustomers)) {
// $listAccessibleCustomers = [1509096882];
$option['manager_customer_id'] = 1509096882; //开发者
$option['login_customer_id'] = 1509096882;
}
if (in_array(1401879025, $listAccessibleCustomers)) {
// $listAccessibleCustomers = [1401879025];
$option['manager_customer_id'] = 1401879025; //开发者
$option['login_customer_id'] = 1401879025;
}
}
$allRootAccounts = $this->googleAdsAccountService->runGetAccountHierarchy($option);
// dump($allRootAccounts);
foreach ($allRootAccounts as $rootAccountId => $accounts) {
// dump($rootAccountId, $accounts);
foreach ($accounts as $account) {
$customerId = $account['customer_id'];
$customerName = $account['descriptive_name'];
// dump($customerId, $customerName, $thirdUser->id);
$this->googleOAuthService->saveThirdUserAdvertiser($customerId, $thirdUser->id,$rootAccountId, $customerName);
// $customerId = $account['customer_id'];
// dump($customerId, $thirdUser->id, $rootAccountId, $account);
// if($account['customer_id'] == 1509096882)continue;
$this->googleOAuthService->saveThirdUserAdvertiser($account['customer_id'], $thirdUser->id, $rootAccountId, $account);
}
}
$this->googleOAuthService->updateThirdUserDefault($thirdUser->id, 't');
// return $this->successResponse($allAccounts);
}

View File

@ -28,7 +28,6 @@ class GoogleAdsDateDatas
private $googleOAuthService;
//微博热榜地址
// const url = 'https://library.tiktok.com/api/v1/search?region=GB&type=1&start_time=1666540800&end_time=1666627200';
@ -43,8 +42,6 @@ class GoogleAdsDateDatas
const countries = ["GB", "BE"];
public function listCampaigns(Request $request)
{
$options = $request->all();
@ -60,9 +57,14 @@ class GoogleAdsDateDatas
public function getDateDatas($options)
{
$customers = $this->googleOAuthService->getGoogleAdCustomers([]);
foreach ($customers as $customerId) {
$googleAdsCampaignService = new googleAdsCampaignService($customerId);
$googleAdsCampaignService->runListDateDatas($customerId, $options['date']);
// dump($customers);
foreach ($customers as $customer) {
if ($customer['login_customer_id'] > 0 && ((isset($customer['manager']) && $customer['manager'] === false)) ) {
// dump($customer);
$googleAdsCampaignService = new googleAdsCampaignService($customer['customer_id']);
// dump($customer['customer_id'],$customer, $options['date']);
$googleAdsCampaignService->runListDateDatas($customer['customer_id'],$customer, $options['date']);
}
}
// $this->googleAdsCampaignService->runListDateDatas($options['customer_id'], $options['date']);

View File

@ -60,7 +60,9 @@ class GoogleAdsGroups
foreach ($customers as $customer) {
$googleAdsGroupService = new GoogleAdsGroupService($customer['customer_id']);
$resourceName = $googleAdsGroupService->runListGroups($customer['customer_id'],$customer);
if ($customer['login_customer_id'] >0){
$resourceName = $googleAdsGroupService->runListGroups($customer['customer_id'],$customer);
}
// return $this->successResponse(['groups_list' => $resourceName]);
}

View File

@ -19,9 +19,8 @@ class OauthCheck implements MiddlewareInterface
$uid = $request->jwtClaims['uid'];
// 查询指定 user_id 的 ThirdUser
$thirdUser = ThirdUser::where('user_id', $uid)->where('third_type', 'google')->find();
// dump($uid, $thirdUser);
if ($thirdUser) {
if ($thirdUser && $thirdUser->access_token) {
// 获取 access_token
$request->refresh_token = $thirdUser->access_token;
@ -33,11 +32,12 @@ class OauthCheck implements MiddlewareInterface
$request->login_customer_id = $advertiser->google_login_customer_id;
// dump( $request->access_token,$request->login_customer_id);
} else {
return Json([
'code' => 0,
'msg' => 'Ads Data is ready to collect,please wait',
'data' => []
]);
// return Json([
// 'code' => 0,
// 'msg' => 'Ads Data is ready to collect,please wait',
// 'data' => []
// ]);
}
} else {
return Json([

View File

@ -24,42 +24,46 @@ class UpdateGoogleAdsTask
// 每15分钟执行一次
new Crontab('10 */15 * * * *', function () {
new Crontab('10 */3 * * * *', function () {
// $dayBeforeYesterdayStart = date('Y-m-d', strtotime('-2 day'));
// dump($dayBeforeYesterdayStart . '更新' . GoogleAdsDateDatas::type . '开始');
// Event::emit(GoogleAdsDateDatas::type, ['date' => $dayBeforeYesterdayStart]);
$dayBeforeYesterdayStart = date('Y-m-d', strtotime('-2 day'));
dump($dayBeforeYesterdayStart . '更新' . GoogleAdsDateDatas::type . '开始');
Event::emit(GoogleAdsDateDatas::type, ['date' => $dayBeforeYesterdayStart]);
}
);
// 每15分钟执行一次
new Crontab('20 */15 * * * *', function () {
// $yesterdayStart = date('Y-m-d', strtotime('-1 day'));
// dump($yesterdayStart . '更新' . GoogleAdsDateDatas::type . '开始');
// Event::emit(GoogleAdsDateDatas::type, ['date' => $yesterdayStart]);
new Crontab('20 */3 * * * *', function () {
$yesterdayStart = date('Y-m-d', strtotime('-1 day'));
dump($yesterdayStart . '更新' . GoogleAdsDateDatas::type . '开始');
Event::emit(GoogleAdsDateDatas::type, ['date' => $yesterdayStart]);
}
);
// 每15分钟执行一次
new Crontab('30 */15 * * * *', function () {
//获取今天的 0 点的YYYY-MM-DD格式
// $todayStart = date('Y-m-d', strtotime('0 day'));
// dump($todayStart . '更新' . GoogleAdsDateDatas::type . '开始');
// Event::emit(GoogleAdsDateDatas::type, ['date' => $todayStart]);
new Crontab('30 */3 * * * *', function () {
//获取今天的 0 点的YYYY - MM - DD格式
$todayStart = date('Y-m-d', strtotime('0 day'));
dump($todayStart . '更新' . GoogleAdsDateDatas::type . '开始');
Event::emit(GoogleAdsDateDatas::type, ['date' => $todayStart]);
}
);
// 每15分钟执行一次
new Crontab('15 */10 * * * *', function () {
dump(date('Y-m-d H:i:s') . '更新' . GoogleAdsCampaigns::type . '开始');
Event::emit(GoogleAdsCampaigns::type, []);
new Crontab('15 */3 * * * *', function () {
dump(date('Y-m-d H:i:s') . '更新' . GoogleAdsAssetRelations::IMAGEASSET . '开始');
Event::emit(GoogleAdsAssetRelations::IMAGEASSET, []);
}
);
// 每15分钟执行一次
new Crontab('30 */10 * * * *', function () {
new Crontab('30 */3 * * * *', function () {
dump(date('Y-m-d H:i:s') . '更新' . GoogleAdsGroups::type . '开始');
Event::emit(GoogleAdsGroups::type, []);
dump(date('Y-m-d H:i:s') . '更新' . GoogleAdsCampaigns::type . '开始');
Event::emit(GoogleAdsCampaigns::type, []);
}
);
@ -77,10 +81,10 @@ class UpdateGoogleAdsTask
}
);
new Crontab('* */20 * * * *', function () {
dump(date('Y-m-d H:i:s') . '更新' . GoogleAdsAssetRelations::IMAGEASSET . '开始');
Event::emit(GoogleAdsAssetRelations::IMAGEASSET, []);
});
// new Crontab('* */2 * * * *', function () {
// dump(date('Y-m-d H:i:s') . '更新' . GoogleAdsAssetRelations::IMAGEASSET . '开始');
// Event::emit(GoogleAdsAssetRelations::IMAGEASSET, []);
// });
new Crontab('55 */51 * * * *', function () {
dump(date('Y-m-d H:i:s') . '更新' . GoogleAdsAssetRelations::VIDEOASSET . '开始');
@ -88,14 +92,13 @@ class UpdateGoogleAdsTask
}
);
new Crontab('0 */3 * * * *', function () {
new Crontab('0 */1 * * * *', function () {
dump(date('Y-m-d H:i:s') . '更新' . GoogleAdsCustomers::CUSTOMERADD . '开始');
Event::emit(GoogleAdsCustomers::CUSTOMERADD,[]);
Event::emit(GoogleAdsCustomers::CUSTOMERADD, []);
}
);
// 每15分钟执行一次
// new Crontab('58 */15 * * * *', function () {
// dump(date('Y-m-d H:i:s') . '更新' . GoogleAdsCampaigns::type . '开始');

View File

@ -12,13 +12,18 @@ use Google\Ads\GoogleAds\Lib\V18\GoogleAdsException;
use Google\Ads\GoogleAds\Lib\V18\GoogleAdsServerStreamDecorator;
use Google\Ads\GoogleAds\Util\FieldMasks;
use Google\Ads\GoogleAds\Util\V18\ResourceNames;
use Google\Ads\GoogleAds\V18\Enums\AccessRoleEnum\AccessRole;
use Google\Ads\GoogleAds\V18\Enums\ManagerLinkStatusEnum\ManagerLinkStatus;
use Google\Ads\GoogleAds\V18\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V18\Resources\CustomerClient;
use Google\Ads\GoogleAds\V18\Resources\CustomerUserAccess;
use Google\Ads\GoogleAds\V18\Services\Client\CustomerServiceClient;
//use Google\Ads\GoogleAds\V18\Services\CustomerServiceClient;
use Google\Ads\GoogleAds\V18\Services\CustomerUserAccessOperation;
use Google\Ads\GoogleAds\V18\Services\GoogleAdsRow;
use Google\Ads\GoogleAds\V18\Services\ListAccessibleCustomersRequest;
use Google\Ads\GoogleAds\V18\Services\MutateCustomerUserAccessRequest;
use Google\Ads\GoogleAds\V18\Services\SearchGoogleAdsStreamRequest;
use Google\Ads\GoogleAds\V18\Resources\CustomerClientLink;
use Google\Ads\GoogleAds\V18\Resources\CustomerManagerLink;
@ -287,7 +292,7 @@ class GoogleAdsAccountService extends BaseService
* @return GoogleAdsClient the created client
*/
// public function createGoogleAdsClientWithloginCustomerId(int $thirdUserId,int $loginCustomerId)
public function createGoogleAdsClientWithloginCustomerId($refreshToken,int $loginCustomerId)
public function createGoogleAdsClientWithloginCustomerId($refreshToken, int $loginCustomerId)
{
// $advertiserId = getenv('GOOGLE_ADS_CUSTOMER_ID');
@ -333,20 +338,152 @@ class GoogleAdsAccountService extends BaseService
// Issues a request for listing all accessible customers.
$accessibleCustomers =
$customerServiceClient->listAccessibleCustomers(new ListAccessibleCustomersRequest());
print 'Total results: ' . count($accessibleCustomers->getResourceNames()) . PHP_EOL;
$resourceNameArray = [];
// Iterates over all accessible customers' resource names and prints them.
foreach ($accessibleCustomers->getResourceNames() as $resourceName) {
/** @var string $resourceName */
printf("Customer resource name: '%s'%s", $resourceName, PHP_EOL);
$resourceNameArray[] = $resourceName;
$accessibleCustomerIds = [];
foreach ($accessibleCustomers->getResourceNames() as $customerResourceName) {
$customer = CustomerServiceClient::parseName($customerResourceName)['customer_id'];
print $customer . PHP_EOL;
$accessibleCustomerIds[] = intval($customer);
}
return $resourceNameArray;
return $accessibleCustomerIds;
// print 'Total results: ' . count($accessibleCustomers->getResourceNames()) . PHP_EOL;
// $resourceNameArray = [];
// // Iterates over all accessible customers' resource names and prints them.
// foreach ($accessibleCustomers->getResourceNames() as $resourceName) {
// /** @var string $resourceName */
// printf("Customer resource name: '%s'%s", $resourceName, PHP_EOL);
// $resourceNameArray[] = $resourceName;
// }
// return $resourceNameArray;
}
// [END list_accessible_customers]
/**
* Runs the example.
*
* @param GoogleAdsClient $googleAdsClient the Google Ads API client
* @param int $customerId the customer ID
* @param string $emailAddress the email address of the user whose access role should be updated
* @param string $accessRole the updated access role
*/
public function runGetAccountAccess(
$option)
{
$managerCustomerId = isset($option['manager_customer_id']) ? (int)$option['manager_customer_id'] : null;
$loginCustomerId = isset($option['login_customer_id']) ? (int)$option['login_customer_id'] : null;
$refreshToken = isset($option['refresh_token']) ? $option['refresh_token'] : null;
// $thirdUserId = (int)$option['third_user_id'];
// Creates a client with the manager customer ID as login customer ID.
$googleAdsClient = $this->createGoogleAdsClientWithloginCustomerId($refreshToken,$loginCustomerId);
$customerId = 8452924576;
$userId = $this->getUserAccess($googleAdsClient, $customerId,'s5O0z@example.com');
// if (!is_null($userId)) {
// $this->modifyUserAccess($googleAdsClient, $customerId, $userId, $accessRole);
// }
return $userId;
}
/**
* Gets the customer user access given an email address.
*
* @param GoogleAdsClient $googleAdsClient the Google Ads API client
* @param int $customerId the customer ID
* @param string $emailAddress the email address of the user whose access role should be updated
* @return int|null the user ID if a customer is found, or null if no matching customers were
* found
*/
public function getUserAccess(
GoogleAdsClient $googleAdsClient,
int $customerId,
string $emailAddress
)
{
$googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
// Creates a query that retrieves all customer user accesses.
// Use the LIKE query for filtering to ignore the text case for email address when
// searching for a match.
// $query = "SELECT customer_user_access.user_id, "
// . "customer_user_access.email_address, customer_user_access.access_role,"
// . "customer_user_access.access_creation_date_time FROM customer_user_access "
// . "WHERE customer_user_access.email_address LIKE '$emailAddress'";
$query = "SELECT customer_user_access.user_id, "
. "customer_user_access.email_address, customer_user_access.access_role,"
. "customer_user_access.access_creation_date_time FROM customer_user_access "
. "WHERE customer_user_access.user_id = $customerId";
// Issues a search request by to retrieve the customer user accesses.
$response =
$googleAdsServiceClient->search(SearchGoogleAdsRequest::build($customerId, $query));
if (iterator_count($response) > 0) {
/** @var CustomerUserAccess $customerUserAccess */
$customerUserAccess = $response->getIterator()->current()->getCustomerUserAccess();
printf(
"Customer user access with User ID = %d, Email Address = "
. "'%s', Access Role = '%s' and Creation Time = %s was found in "
. "Customer ID: %d.%s",
$customerUserAccess->getUserId(),
$customerUserAccess->getEmailAddress(),
AccessRole::name($customerUserAccess->getAccessRole()),
$customerUserAccess->getAccessCreationDateTime(),
$customerId,
PHP_EOL
);
return $customerUserAccess->getUserId();
} else {
print 'No customer user access with requested email was found.' . PHP_EOL;
return null;
}
}
/**
* Modifies the user access role to a specified value.
*
* @param GoogleAdsClient $googleAdsClient the Google Ads API client
* @param int $customerId the customer ID
* @param int $userId ID of the user whose access role is modified
* @param string $accessRole the updated access role
*/
public function modifyUserAccess(
GoogleAdsClient $googleAdsClient,
int $customerId,
int $userId,
string $accessRole
)
{
// Creates the modified user access.
$customerUserAccess = new CustomerUserAccess([
'resource_name' => ResourceNames::forCustomerUserAccess($customerId, $userId),
'access_role' => AccessRole::value($accessRole)
]);
// Constructs an operation that will update the customer user access with the specified
// resource name, using the FieldMasks utility to derive the update mask. This mask tells
// the Google Ads API which attributes of the customer user access you want to change.
$customerUserAccessOperation = new CustomerUserAccessOperation();
$customerUserAccessOperation->setUpdate($customerUserAccess);
$customerUserAccessOperation->setUpdateMask(
FieldMasks::allSetFieldsOf($customerUserAccess)
);
// Issues a mutate request to update the customer user access.
$customerUserAccessServiceClient = $googleAdsClient->getCustomerUserAccessServiceClient();
$response = $customerUserAccessServiceClient->mutateCustomerUserAccess(
MutateCustomerUserAccessRequest::build($customerId, $customerUserAccessOperation)
);
// Prints the resource name of the updated customer user access.
printf(
"Successfully modified customer user access with resource name: '%s'%s",
$response->getResult()->getResourceName(),
PHP_EOL
);
}
/**
* 层级账号信息
*
@ -358,9 +495,9 @@ class GoogleAdsAccountService extends BaseService
self::$rootCustomerClients = []; //初始化静态变量
$managerCustomerId = isset($option['manager_customer_id'])?(int)$option['manager_customer_id']: null;
$loginCustomerId = isset($option['login_customer_id'])?(int)$option['login_customer_id']: null;
$refreshToken = isset($option['refresh_token'])?$option['refresh_token']: null;
$managerCustomerId = isset($option['manager_customer_id']) ? (int)$option['manager_customer_id'] : null;
$loginCustomerId = isset($option['login_customer_id']) ? (int)$option['login_customer_id'] : null;
$refreshToken = isset($option['refresh_token']) ? $option['refresh_token'] : null;
// $thirdUserId = (int)$option['third_user_id'];
// Creates a client with the manager customer ID as login customer ID.
@ -385,7 +522,7 @@ class GoogleAdsAccountService extends BaseService
// Constructs a map of account hierarchies.
foreach ($rootCustomerIds as $rootCustomerId) {
$customerClientToHierarchy =
$this->createCustomerClientToHierarchy($refreshToken,$loginCustomerId, $rootCustomerId);
$this->createCustomerClientToHierarchy($refreshToken, $loginCustomerId, $rootCustomerId);
if (is_null($customerClientToHierarchy)) {
$accountsWithNoInfo[] = $rootCustomerId;
} else {
@ -444,21 +581,21 @@ class GoogleAdsAccountService extends BaseService
*/
public function createCustomerClientToHierarchy(
string $refreshToken,
?int $loginCustomerId,
int $rootCustomerId
?int $loginCustomerId,
int $rootCustomerId
): ?array
{
// Creates a client with the manager customer ID as login customer ID.
$googleAdsClient = $this->createGoogleAdsClientWithloginCustomerId($refreshToken,$loginCustomerId ?? $rootCustomerId);
$googleAdsClient = $this->createGoogleAdsClientWithloginCustomerId($refreshToken, $loginCustomerId ?? $rootCustomerId);
// Creates the Google Ads Service client.
$googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
// Creates a query that retrieves all child accounts of the manager specified in search
// calls below.
$query = 'SELECT customer_client.client_customer, customer_client.level,'
. ' customer_client.manager, customer_client.descriptive_name,'
. ' customer_client.manager,customer_client.test_account, customer_client.descriptive_name,'
. ' customer_client.currency_code, customer_client.time_zone,'
. ' customer_client.id FROM customer_client WHERE customer_client.level <= 1';
@ -566,16 +703,18 @@ class GoogleAdsAccountService extends BaseService
)
{
if ($depth === 0) {
print 'Customer ID (Descriptive Name, Currency Code, Time Zone)' . PHP_EOL;
print 'Customer ID (Descriptive Name, Currency Code, Time Zone, Manager, Test Account)' . PHP_EOL;
}
$customerId = $customerClient->getId();
print str_repeat('-', $depth * 2);
printf(
" %d ('%s', '%s', '%s')%s",
" %d ('%s', '%s', '%s', '%s', '%s')%s",
$customerId,
$customerClient->getDescriptiveName(),
$customerClient->getCurrencyCode(),
$customerClient->getTimeZone(),
$customerClient->getManager(),
$customerClient->getTestAccount(),
PHP_EOL
);
@ -588,29 +727,31 @@ class GoogleAdsAccountService extends BaseService
}
private static function getAccountHierarchy(
CustomerClient $customerClient,
array $customerIdsToChildAccounts,
int $depth,
array &$result = [] // 这里使用引用传递
)
{
// Store the current customer ID and descriptive name in the result array
$customerId = $customerClient->getId();
$result[] = [
'customer_id' => $customerId,
'descriptive_name' => $customerClient->getDescriptiveName(),
];
CustomerClient $customerClient,
array $customerIdsToChildAccounts,
int $depth,
array &$result = [] // 这里使用引用传递
)
{
// Store the current customer ID and descriptive name in the result array
$customerId = $customerClient->getId();
$result[] = [
'customer_id' => $customerId,
'descriptive_name' => $customerClient->getDescriptiveName(),
'manager' => $customerClient->getManager(),
'test_account' => $customerClient->getTestAccount(),
];
// Recursively call this function for all child accounts of $customerClient.
if (array_key_exists($customerId, $customerIdsToChildAccounts)) {
foreach ($customerIdsToChildAccounts[$customerId] as $childAccount) {
// Recursively add the child account information
$result = self::getAccountHierarchy($childAccount, $customerIdsToChildAccounts, $depth + 1, $result);
// Recursively call this function for all child accounts of $customerClient.
if (array_key_exists($customerId, $customerIdsToChildAccounts)) {
foreach ($customerIdsToChildAccounts[$customerId] as $childAccount) {
// Recursively add the child account information
$result = self::getAccountHierarchy($childAccount, $customerIdsToChildAccounts, $depth + 1, $result);
}
}
return $result;
}
return $result;
}
}

View File

@ -75,17 +75,18 @@ class GoogleAdsAssetRelationService extends BaseService
* @return mixed
* @throws ApiException
*/
public function runListAssetRelations(int $customerId): mixed
public function runListAssetRelations(int $customerId): array
{
// dump($customerId);
// Creates a single shared budget to be used by the campaigns added below.
$assetsResourceName = self::getAssetRelations($customerId);
// dump(json_encode($assetsResourceName));
if (is_array($assetsResourceName && count($assetsResourceName) > 0)) {
if (is_array($assetsResourceName) && count($assetsResourceName) > 0) {
// dump($assetsResourceName);
self::saveAssetRelations($assetsResourceName);
}
// return $assetsResourceName;
return 'insert success';
return $assetsResourceName;
// return 'insert success';
}
@ -123,7 +124,6 @@ class GoogleAdsAssetRelationService extends BaseService
VALUES (:asset_id, :ad_id, :ad_group_id, :campaign_id, :date,:month,:season,:year, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
ON CONFLICT (asset_id, ad_id, date)
DO NOTHING"; // 如果 (asset_id, ad_id, date) 存在,忽略插入操作
ThinkDb::execute($sql, $data);
}
}
@ -250,7 +250,7 @@ class GoogleAdsAssetRelationService extends BaseService
// 提取年和月
$year = (int)$dateObj->format('Y');
$month = (int)$dateObj->format('Ym');
$month = (int)$dateObj->format('m');
// 计算季度
if ($month >= 1 && $month <= 3) {
@ -262,7 +262,7 @@ class GoogleAdsAssetRelationService extends BaseService
} else {
$season = (int)$dateObj->format('Y') . '04'; // Q4
}
$month = (int)$dateObj->format('Ym');
return [
'year' => $year,
'month' => $month,

View File

@ -7,6 +7,7 @@ use app\model\ThirdUserAdvertiser;
use app\util\Helper;
use app\util\ArgumentNames;
use app\util\ArgumentParser;
use DateTime;
use Google\Ads\GoogleAds\Lib\V18\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V18\GoogleAdsServerStreamDecorator;
use Google\Ads\GoogleAds\Util\FieldMasks;
@ -217,13 +218,13 @@ class GoogleAdsCampaignService extends BaseService
* @return mixed
* @throws ApiException
*/
public function runListDateDatas(int $customerId, $date): mixed
public function runListDateDatas($customerId,$options, $date): mixed
{
// $googleAdsClient = $this->googleAdsClient;
$googleAdsClient = new GoogleAdsClientService($customerId);
$googleAdsClient = new GoogleAdsClientService($options['refresh_token'], $options['login_customer_id']);
// Creates a single shared budget to be used by the campaigns added below.
$dayResourceName = self::getDateDatas($googleAdsClient->getGoogleAdsClient(), $customerId, $date);
$dayResourceName = self::getDateDatas($googleAdsClient->getGoogleAdsClientWithloginCustomerId(), $customerId, $date);
// dump(json_encode($dayResourceName));
if (is_array($dayResourceName)) {
self::saveDateDatas($dayResourceName);
@ -365,15 +366,15 @@ class GoogleAdsCampaignService extends BaseService
// 计算季度
if ($month >= 1 && $month <= 3) {
$season = (int)$dateObj->format('Ym') . '01'; // Q1
$season = (int)$dateObj->format('Y') . '01'; // Q1
} elseif ($month >= 4 && $month <= 6) {
$season = (int)$dateObj->format('Ym') . '02'; // Q2
$season = (int)$dateObj->format('Y') . '02'; // Q2
} elseif ($month >= 7 && $month <= 9) {
$season = (int)$dateObj->format('Ym') . '03'; // Q3
$season = (int)$dateObj->format('Y') . '03'; // Q3
} else {
$season = (int)$dateObj->format('Ym') . '04'; // Q4
$season = (int)$dateObj->format('Y') . '04'; // Q4
}
$month = (int)$dateObj->format('Ym');
return [
'year' => $year,
'month' => $month,
@ -441,7 +442,7 @@ class GoogleAdsCampaignService extends BaseService
$sql = "INSERT INTO bps.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, month, season, year)
VALUES (:ad_id, :customer_id, :ad_name, :ad_resource_name, :ad_group_id, :campaign_id, :clicks, :cost_micros, :conversions, :conversions_value, :impressions, :date, :month, :season, :year)
ON CONFLICT (ad_id, date) -- 假设 (ad_id, date) 为唯一约束
ON CONFLICT (ad_id, date)
DO UPDATE SET
customer_id = EXCLUDED.customer_id,
ad_name = EXCLUDED.ad_name,
@ -457,7 +458,7 @@ class GoogleAdsCampaignService extends BaseService
season = EXCLUDED.season,
year = EXCLUDED.year,
update_at = EXCLUDED.update_at"; // 更新其他字段和更新时间戳
// dump($sql, $data);
ThinkDb::execute($sql, $data);
}

View File

@ -88,7 +88,7 @@ class GoogleOAuthService
}
//保存或更新某个主体部广告账号
public function saveThirdUserAdvertiser($customer_id, $third_user_id,$login_customer_id,$customer_name = '')
public function saveThirdUserAdvertiser($customer_id, $third_user_id,$login_customer_id,$customer)
{
// 确保 customer_id 和 third_user_id 是字符串
$customer_id = (string) $customer_id;
@ -97,18 +97,30 @@ class GoogleOAuthService
$data = [
'doc_' => $third_user_id,
'advertiser_id' => $customer_id,
'advertiser_name' => $customer_name,
'advertiser_name' => $customer['descriptive_name'],
'google_login_customer_id' => $login_customer_id,
];
if($customer['manager'] === true){
$data['google_manager'] = 't';
}else{
$data['google_manager'] = 'f';
}
if($customer['test_account'] === true){
$data['google_test_account'] = 't';
}else{
$data['google_test_account'] = 'f';
}
// dump($data);
$sql = "
INSERT INTO {$tableName}
(advertiser_id,advertiser_name, doc_,google_login_customer_id)
VALUES (:advertiser_id, :advertiser_name,:doc_,:google_login_customer_id)
(advertiser_id,advertiser_name, doc_,google_login_customer_id,google_manager,google_test_account)
VALUES (:advertiser_id, :advertiser_name,:doc_,:google_login_customer_id,:google_manager,:google_test_account)
ON CONFLICT (advertiser_id,doc_)
DO UPDATE SET
advertiser_name = EXCLUDED.advertiser_name,
google_login_customer_id = EXCLUDED.google_login_customer_id
google_login_customer_id = EXCLUDED.google_login_customer_id,
google_manager = EXCLUDED.google_manager,
google_test_account = EXCLUDED.google_test_account
";
// dump($sql,$data);
ThinkDb::execute($sql, $data);
@ -130,17 +142,17 @@ class GoogleOAuthService
ThinkDb::execute($sql, $data);
}
public function updateThirdUser($state, $refreshToken): void
public function updateThirdUserDefault($third_user_id, $is_default = 't'): void
{
$tableName = 'bps_third_user';
$tableName = getenv('DB_PG_SCHEMA') ? getenv('DB_PG_SCHEMA') . '.' . $tableName : 'bps' . $tableName;
$data = [
'access_token' => $refreshToken,
'random_code' => $state,];
'is_default' => $is_default,
'id' => $third_user_id,];
$sql = "
UPDATE {$tableName}
SET access_token = :access_token
WHERE random_code = :random_code
SET is_default = :is_default
WHERE id = :id
";
ThinkDb::execute($sql, $data);
}
@ -158,14 +170,14 @@ class GoogleOAuthService
// $thirdUser->save();
$data = [
'access_token' => $refreshToken,
'is_default' => 't',
'is_default' => 'f',
'third_type' => 'google',
];
$tableName = 'bps_third_user';
$tableName = getenv('DB_PG_SCHEMA') ? getenv('DB_PG_SCHEMA') . '.' . $tableName : 'bps' . $tableName;
if (!empty($state)) {
$thirdUser = ThirdUser::where('user_id', $state)->find(); // 获取第一个结果
$thirdUser = ThirdUser::where('user_id', $state)->where('third_type', 'google')->find(); // 获取第一个结果
// dump($thirdUser); return ($uid);
if ($thirdUser) {
$data['id'] = $thirdUser->id;
@ -263,7 +275,7 @@ class GoogleOAuthService
$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 as customer_id,tua.google_login_customer_id as login_customer_id, tu.access_token as refresh_token') // 获取 advertiser_id 字段
->field('CAST(tua.advertiser_id AS BIGINT) as customer_id,tua.google_login_customer_id as login_customer_id,tua.google_test_account as test_account,tua.google_manager as manager, tu.access_token as refresh_token') // 获取 advertiser_id 字段
->select(); // 执行查询
// 如果没有找到符合条件的广告主,抛出异常