-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathAds.php
More file actions
524 lines (456 loc) · 15.4 KB
/
Ads.php
File metadata and controls
524 lines (456 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
<?php
declare( strict_types=1 );
namespace Automattic\WooCommerce\GoogleListingsAndAds\API\Google;
use Automattic\WooCommerce\GoogleListingsAndAds\API\Google\Query\AdsAccountAccessQuery;
use Automattic\WooCommerce\GoogleListingsAndAds\API\Google\Query\AdsAccountQuery;
use Automattic\WooCommerce\GoogleListingsAndAds\API\Google\Query\AdsBillingStatusQuery;
use Automattic\WooCommerce\GoogleListingsAndAds\API\Google\Query\AdsProductLinkInvitationQuery;
use Automattic\WooCommerce\GoogleListingsAndAds\Exception\ExceptionWithResponseData;
use Automattic\WooCommerce\GoogleListingsAndAds\Google\Ads\GoogleAdsClient;
use Automattic\WooCommerce\GoogleListingsAndAds\Options\OptionsAwareInterface;
use Automattic\WooCommerce\GoogleListingsAndAds\Options\OptionsAwareTrait;
use Automattic\WooCommerce\GoogleListingsAndAds\Options\OptionsInterface;
use Exception;
use Google\Ads\GoogleAds\Util\V23\ResourceNames;
use Google\Ads\GoogleAds\V23\Enums\AccessRoleEnum\AccessRole;
use Google\Ads\GoogleAds\V23\Enums\ProductLinkInvitationStatusEnum\ProductLinkInvitationStatus;
use Google\Ads\GoogleAds\V23\Resources\ProductLinkInvitation;
use Google\Ads\GoogleAds\V23\Services\ApplyIncentiveRequest;
use Google\Ads\GoogleAds\V23\Services\FetchIncentiveRequest;
use Google\Ads\GoogleAds\V23\Services\FetchIncentiveRequest\IncentiveType;
use Google\Ads\GoogleAds\V23\Services\Incentive;
use Google\Ads\GoogleAds\V23\Services\IncentiveOffer\OfferType;
use Google\Ads\GoogleAds\V23\Services\ListAccessibleCustomersRequest;
use Google\Ads\GoogleAds\V23\Services\UpdateProductLinkInvitationRequest;
use Google\ApiCore\ApiException;
use Google\ApiCore\ValidationException;
use Google\Type\Money;
defined( 'ABSPATH' ) || exit;
/**
* Class Ads
*
* @package Automattic\WooCommerce\GoogleListingsAndAds\API\Google
*/
class Ads implements OptionsAwareInterface {
use ExceptionTrait;
use OptionsAwareTrait;
/**
* The Google Ads Client.
*
* @var GoogleAdsClient
*/
protected $client;
/**
* Ads constructor.
*
* @param GoogleAdsClient $client
*/
public function __construct( GoogleAdsClient $client ) {
$this->client = $client;
}
/**
* Get Ads accounts associated with the connected Google account.
*
* @return array
* @throws ExceptionWithResponseData When an ApiException is caught.
*/
public function get_ads_accounts(): array {
try {
$customers = $this->client->getCustomerServiceClient()->listAccessibleCustomers( new ListAccessibleCustomersRequest() );
$accounts = [];
foreach ( $customers->getResourceNames() as $name ) {
$account = $this->get_account_details( $name );
if ( $account ) {
$accounts[] = $account;
}
}
return $accounts;
} catch ( ApiException $e ) {
do_action( 'woocommerce_gla_ads_client_exception', $e, __METHOD__ );
$errors = $this->get_exception_errors( $e );
// Return an empty list if the user has not signed up to ads yet.
if ( isset( $errors['NOT_ADS_USER'] ) ) {
return [];
}
throw new ExceptionWithResponseData(
/* translators: %s Error message */
sprintf( __( 'Error retrieving accounts: %s', 'google-listings-and-ads' ), reset( $errors ) ),
$this->map_grpc_code_to_http_status_code( $e ),
null,
[ 'errors' => $errors ]
);
}
}
/**
* Get billing status.
*
* @return string
*/
public function get_billing_status(): string {
$ads_id = $this->options->get_ads_id();
if ( ! $ads_id ) {
return BillingSetupStatus::UNKNOWN;
}
try {
$results = ( new AdsBillingStatusQuery() )
->set_client( $this->client, $this->options->get_ads_id() )
->get_results();
foreach ( $results->iterateAllElements() as $row ) {
$billing_setup = $row->getBillingSetup();
$status = BillingSetupStatus::label( $billing_setup->getStatus() );
return apply_filters( 'woocommerce_gla_ads_billing_setup_status', $status, $ads_id );
}
} catch ( ApiException | ValidationException $e ) {
// Do not act upon error as we might not have permission to access this account yet.
if ( 'PERMISSION_DENIED' !== $e->getStatus() ) {
do_action( 'woocommerce_gla_ads_client_exception', $e, __METHOD__ );
}
}
return apply_filters( 'woocommerce_gla_ads_billing_setup_status', BillingSetupStatus::UNKNOWN, $ads_id );
}
/**
* Accept the pending approval link sent from a merchant account.
*
* @param int $merchant_id Merchant Center account id.
* @throws Exception When the pending approval link can not be found.
*/
public function accept_merchant_link( int $merchant_id ) {
$link = $this->get_merchant_link( $merchant_id, 10 );
$request = new UpdateProductLinkInvitationRequest();
$request->setCustomerId( $this->options->get_ads_id() );
$request->setResourceName( $link->getResourceName() );
$request->setProductLinkInvitationStatus( ProductLinkInvitationStatus::ACCEPTED );
$this->client->getProductLinkInvitationServiceClient()->updateProductLinkInvitation( $request );
}
/**
* Check if we have access to the ads account.
*
* @param string $email Email address of the connected account.
*
* @return bool
*/
public function has_access( string $email ): bool {
$ads_id = $this->options->get_ads_id();
try {
$results = ( new AdsAccountAccessQuery() )
->set_client( $this->client, $ads_id )
->where( 'customer_user_access.email_address', $email )
->get_results();
foreach ( $results->iterateAllElements() as $row ) {
$access = $row->getCustomerUserAccess();
if ( AccessRole::ADMIN === $access->getAccessRole() ) {
return true;
}
}
} catch ( ApiException $e ) {
do_action( 'woocommerce_gla_ads_client_exception', $e, __METHOD__ );
}
return false;
}
/**
* Get the ads account currency.
*
* @since 1.4.1
*
* @return string
*/
public function get_ads_currency(): string {
// Retrieve account currency from the API if we haven't done so previously.
if ( $this->options->get_ads_id() && ! $this->options->get( OptionsInterface::ADS_ACCOUNT_CURRENCY ) ) {
$this->request_ads_currency();
}
return strtoupper( $this->options->get( OptionsInterface::ADS_ACCOUNT_CURRENCY ) ?? get_woocommerce_currency() );
}
/**
* Request the Ads Account currency, and cache it as an option.
*
* @since 1.1.0
*
* @return boolean
*/
public function request_ads_currency(): bool {
try {
$ads_id = $this->options->get_ads_id();
$account = ResourceNames::forCustomer( $ads_id );
$customer = ( new AdsAccountQuery() )
->set_client( $this->client, $ads_id )
->columns( [ 'customer.currency_code' ] )
->where( 'customer.resource_name', $account, '=' )
->get_result()
->getCustomer();
$currency = $customer->getCurrencyCode();
} catch ( ApiException $e ) {
do_action( 'woocommerce_gla_ads_client_exception', $e, __METHOD__ );
$currency = null;
}
return $this->options->update( OptionsInterface::ADS_ACCOUNT_CURRENCY, $currency );
}
/**
* Save the Ads account currency to the same value as the Store currency.
*
* @since 1.1.0
*
* @return boolean
*/
public function use_store_currency(): bool {
return $this->options->update( OptionsInterface::ADS_ACCOUNT_CURRENCY, get_woocommerce_currency() );
}
/**
* Fetch available incentive offers from the Google Ads API.
*
* @since 3.3.0
*
* @param string $country_code ISO 3166-1 alpha-2 country code.
* @param string $language_code ISO 639-1 language code.
*
* @return array Structured incentive offer data. Always returns a valid structure,
* falling back to an empty CYO_INCENTIVE response on API errors.
*/
public function fetch_incentives( string $country_code, string $language_code ): array {
$empty_response = [
'type' => OfferType::name( OfferType::CYO_INCENTIVE ),
'termsAndConditionsUrl' => '',
'incentives' => [],
];
try {
$request = new FetchIncentiveRequest();
$request->setCountryCode( $country_code );
$request->setLanguageCode( $language_code );
$response = $this->client->getIncentiveServiceClient()->fetchIncentive( $request );
$offer = $response->getIncentiveOffer();
if ( ! $offer || ! $offer->hasType() ) {
return $empty_response;
}
$result = [
'type' => OfferType::name( $offer->getType() ),
'termsAndConditionsUrl' => $offer->getConsolidatedTermsAndConditionsUrl(),
'incentives' => [],
];
if ( OfferType::CYO_INCENTIVE === $offer->getType() && $offer->hasCyoIncentives() ) {
$cyo = $offer->getCyoIncentives();
$offer_map = [
'low' => $cyo->getLowOffer(),
'medium' => $cyo->getMediumOffer(),
'high' => $cyo->getHighOffer(),
];
foreach ( $offer_map as $level => $incentive ) {
if ( $incentive ) {
$result['incentives'][] = $this->format_incentive( $incentive, $level );
}
}
}
return $result;
} catch ( ApiException $e ) {
do_action( 'woocommerce_gla_ads_client_exception', $e, __METHOD__ );
return $empty_response;
}
}
/**
* Format an Incentive protobuf message into an array for the REST response.
*
* @since 3.3.0
*
* @param Incentive $incentive The incentive object.
* @param string $level The offer level (low, medium, high).
*
* @return array
*/
protected function format_incentive( Incentive $incentive, string $level ): array {
$data = [
'id' => (string) $incentive->getIncentiveId(),
'type' => IncentiveType::name( $incentive->getType() ),
'offer' => $level,
'termsAndConditionsUrl' => $incentive->getIncentiveTermsAndConditionsUrl(),
'requirement' => [],
];
if ( $incentive->hasRequirement() ) {
$requirement = $incentive->getRequirement();
if ( $requirement->hasSpend() ) {
$spend = $requirement->getSpend();
$data['requirement']['spend'] = [
'awardAmount' => $this->format_money( $spend->getAwardAmount() ),
'requiredAmount' => $this->format_money( $spend->getRequiredAmount() ),
];
}
}
return $data;
}
/**
* Format a Money protobuf message into an array.
*
* @since 3.3.0
*
* @param Money|null $money The Money object.
*
* @return array
*/
protected function format_money( ?Money $money ): array {
if ( ! $money ) {
return [
'currencyCode' => '',
'units' => '0',
];
}
return [
'currencyCode' => $money->getCurrencyCode(),
'units' => (string) $money->getUnits(),
];
}
/**
* Apply a selected incentive to the connected Google Ads account.
*
* @since 3.3.0
*
* @param string $incentive_id The selected incentive ID.
* @param string $country_code ISO 3166-1 alpha-2 country code.
*
* @return array The applied incentive data with coupon_code and creation_time.
* @throws ExceptionWithResponseData When the API call fails.
*/
public function apply_incentive( string $incentive_id, string $country_code ): array {
try {
$request = new ApplyIncentiveRequest(
[
'selected_incentive_id' => (int) $incentive_id,
'customer_id' => (string) $this->options->get_ads_id(),
'country_code' => $country_code,
]
);
$response = $this->client->getIncentiveServiceClient()->applyIncentive( $request );
return [
'coupon_code' => $response->getCouponCode(),
'creation_time' => $response->getCreationTime(),
];
} catch ( ApiException $e ) {
do_action( 'woocommerce_gla_ads_client_exception', $e, __METHOD__ );
$errors = $this->get_exception_errors( $e );
throw new ExceptionWithResponseData(
sprintf(
/* translators: %s Error message */
__( 'Error applying incentive: %s', 'google-listings-and-ads' ),
reset( $errors )
),
$this->map_grpc_code_to_http_status_code( $e ),
null,
[ 'errors' => $errors ]
);
}
}
/**
* Convert ads ID from a resource name to an int.
*
* @param string $name Resource name containing ID number.
*
* @return int
*/
public function parse_ads_id( string $name ): int {
return absint( str_replace( 'customers/', '', $name ) );
}
/**
* Update the Ads ID to use for requests.
*
* @param int $id Ads ID number.
*
* @return bool
*/
public function update_ads_id( int $id ): bool {
return $this->options->update( OptionsInterface::ADS_ID, $id );
}
/**
* Returns true if the Ads id exists in the options.
*
* @return bool
*/
public function ads_id_exists(): bool {
return ! empty( $this->options->get( OptionsInterface::ADS_ID ) );
}
/**
* Update the billing flow URL so we can retrieve it again later.
*
* @param string $url Billing flow URL.
*
* @return bool
*/
public function update_billing_url( string $url ): bool {
return $this->options->update( OptionsInterface::ADS_BILLING_URL, $url );
}
/**
* Update the OCID for the account so that we can reference it later in order
* to link to accept invite link or to send customer to conversion settings page
* in their account.
*
* @param string $url Billing flow URL.
*
* @return bool
*/
public function update_ocid_from_billing_url( string $url ): bool {
$query_string = wp_parse_url( $url, PHP_URL_QUERY );
// Return if no params.
if ( empty( $query_string ) ) {
return false;
}
parse_str( $query_string, $params );
if ( empty( $params['ocid'] ) ) {
return false;
}
return $this->options->update( OptionsInterface::ADS_ACCOUNT_OCID, $params['ocid'] );
}
/**
* Fetch the account details.
* Returns null for any account that fails or is not the right type.
*
* @param string $account Customer resource name.
* @return null|array
*/
private function get_account_details( string $account ): ?array {
try {
$customer = ( new AdsAccountQuery() )
->set_client( $this->client, $this->parse_ads_id( $account ) )
->where( 'customer.resource_name', $account, '=' )
->get_result()
->getCustomer();
if ( ! $customer || $customer->getManager() || $customer->getTestAccount() ) {
return null;
}
return [
'id' => $customer->getId(),
'name' => $customer->getDescriptiveName(),
];
} catch ( ApiException $e ) {
do_action( 'woocommerce_gla_ads_client_exception', $e, __METHOD__ );
}
return null;
}
/**
* Get the pending approval link sent from a Google Merchant account.
*
* The invitation link may not be available in Google Ads immediately after
* the invitation is sent from Google Merchant Center, so this method offers
* a parameter to specify the number of retries.
*
* @param int $merchant_id Merchant Center account id.
* @param int $attempts_left The number of attempts left to get the link.
*
* @return ProductLinkInvitation
* @throws Exception When the pending approval link can not be found.
*/
private function get_merchant_link( int $merchant_id, int $attempts_left = 0 ): ProductLinkInvitation {
$res = ( new AdsProductLinkInvitationQuery() )
->set_client( $this->client, $this->options->get_ads_id() )
->where( 'product_link_invitation.status', ProductLinkInvitationStatus::name( ProductLinkInvitationStatus::PENDING_APPROVAL ) )
->get_results();
foreach ( $res->iterateAllElements() as $row ) {
$link = $row->getProductLinkInvitation();
$mc = $link->getMerchantCenter();
$mc_id = $mc->getMerchantCenterId();
if ( absint( $mc_id ) === $merchant_id ) {
return $link;
}
}
if ( $attempts_left > 0 ) {
sleep( 1 );
return $this->get_merchant_link( $merchant_id, $attempts_left - 1 );
}
throw new Exception( __( 'Unable to find the pending approval link sent from the Merchant Center account', 'google-listings-and-ads' ) );
}
}