-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathMiddleware.php
649 lines (560 loc) · 19.2 KB
/
Middleware.php
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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
<?php
declare( strict_types=1 );
namespace Automattic\WooCommerce\GoogleListingsAndAds\API\Google;
use Automattic\WooCommerce\GoogleListingsAndAds\Google\GoogleHelper;
use Automattic\WooCommerce\GoogleListingsAndAds\Exception\InvalidTerm;
use Automattic\WooCommerce\GoogleListingsAndAds\Exception\InvalidDomainName;
use Automattic\WooCommerce\GoogleListingsAndAds\Options\OptionsAwareInterface;
use Automattic\WooCommerce\GoogleListingsAndAds\Options\OptionsAwareTrait;
use Automattic\WooCommerce\GoogleListingsAndAds\Options\TransientsInterface;
use Automattic\WooCommerce\GoogleListingsAndAds\PluginHelper;
use Automattic\WooCommerce\GoogleListingsAndAds\Proxies\WP;
use Automattic\WooCommerce\GoogleListingsAndAds\Utility\DateTimeUtility;
use Automattic\WooCommerce\GoogleListingsAndAds\Value\TosAccepted;
use Automattic\WooCommerce\GoogleListingsAndAds\Vendor\GuzzleHttp\Client;
use DateTime;
use Exception;
use Psr\Container\ContainerInterface;
use Psr\Http\Client\ClientExceptionInterface;
defined( 'ABSPATH' ) || exit;
/**
* Class Middleware
*
* Container used for:
* - Ads
* - Client
* - DateTimeUtility
* - GoogleHelper
* - Merchant
* - WP
*
* @package Automattic\WooCommerce\GoogleListingsAndAds\API\Google
*/
class Middleware implements OptionsAwareInterface {
use ApiExceptionTrait;
use OptionsAwareTrait;
use PluginHelper;
/**
* @var ContainerInterface
*/
protected $container;
/**
* Middleware constructor.
*
* @param ContainerInterface $container
*/
public function __construct( ContainerInterface $container ) {
$this->container = $container;
}
/**
* Get all Merchant Accounts associated with the connected account.
*
* @return array
* @throws Exception When an Exception is caught.
* @since 1.7.0
*/
public function get_merchant_accounts(): array {
try {
/** @var Client $client */
$client = $this->container->get( Client::class );
$result = $client->get( $this->get_manager_url( 'merchant-accounts' ) );
$response = json_decode( $result->getBody()->getContents(), true );
$accounts = [];
if ( 200 === $result->getStatusCode() && is_array( $response ) ) {
foreach ( $response as $account ) {
$accounts[] = $account;
}
}
return $accounts;
} catch ( ClientExceptionInterface $e ) {
do_action( 'woocommerce_gla_guzzle_client_exception', $e, __METHOD__ );
throw new Exception(
$this->client_exception_message( $e, __( 'Error retrieving accounts', 'google-listings-and-ads' ) ),
$e->getCode()
);
}
}
/**
* Create a new Merchant Center account.
*
* @return int Created merchant account ID
*
* @throws Exception When an Exception is caught or we receive an invalid response.
*/
public function create_merchant_account(): int {
$user = wp_get_current_user();
$tos = $this->mark_tos_accepted( 'google-mc', $user->user_email );
if ( ! $tos->accepted() ) {
throw new Exception( __( 'Unable to log accepted TOS', 'google-listings-and-ads' ) );
}
$site_url = esc_url_raw( $this->get_site_url() );
if ( ! wc_is_valid_url( $site_url ) ) {
throw new Exception( __( 'Invalid site URL.', 'google-listings-and-ads' ) );
}
try {
return $this->create_merchant_account_request(
$this->new_account_name(),
$site_url
);
} catch ( InvalidTerm $e ) {
// Try again with a default account name.
return $this->create_merchant_account_request(
$this->default_account_name(),
$site_url
);
}
}
/**
* Send a request to create a merchant account.
*
* @param string $name Site name
* @param string $site_url Website URL
*
* @return int Created merchant account ID
*
* @throws Exception When an Exception is caught or we receive an invalid response.
* @throws InvalidTerm When the account name contains invalid terms.
* @throws InvalidDomainName When the site URL ends with an invalid top-level domain.
* @since 1.5.0
*/
protected function create_merchant_account_request( string $name, string $site_url ): int {
try {
/** @var Client $client */
$client = $this->container->get( Client::class );
$result = $client->post(
$this->get_manager_url( 'create-merchant' ),
[
'body' => json_encode(
[
'name' => $name,
'websiteUrl' => $site_url,
]
),
]
);
$response = json_decode( $result->getBody()->getContents(), true );
if ( 200 === $result->getStatusCode() && isset( $response['id'] ) ) {
$id = absint( $response['id'] );
$this->container->get( Merchant::class )->update_merchant_id( $id );
return $id;
}
do_action( 'woocommerce_gla_guzzle_invalid_response', $response, __METHOD__ );
$error = $response['message'] ?? __( 'Invalid response when creating account', 'google-listings-and-ads' );
throw new Exception( $error, $result->getStatusCode() );
} catch ( ClientExceptionInterface $e ) {
$message = $this->client_exception_message( $e, __( 'Error creating account', 'google-listings-and-ads' ) );
if ( preg_match( '/terms?.* are|is not allowed/', $message ) ) {
throw InvalidTerm::contains_invalid_terms( $name );
}
if ( strpos( $message, 'URL ends with an invalid top-level domain name' ) !== false ) {
throw InvalidDomainName::create_account_failed_invalid_top_level_domain_name(
$this->strip_url_protocol(
esc_url_raw( $this->get_site_url() )
)
);
}
do_action( 'woocommerce_gla_guzzle_client_exception', $e, __METHOD__ );
throw new Exception( $message, $e->getCode() );
}
}
/**
* Link an existing Merchant Center account.
*
* @param int $id Existing account ID.
*
* @return int
*/
public function link_merchant_account( int $id ): int {
$this->container->get( Merchant::class )->update_merchant_id( $id );
return $id;
}
/**
* Link Merchant Center account to MCA.
*
* @return bool
* @throws Exception When a ClientException is caught or we receive an invalid response.
*/
public function link_merchant_to_mca(): bool {
try {
/** @var Client $client */
$client = $this->container->get( Client::class );
$result = $client->post(
$this->get_manager_url( 'link-merchant' ),
[
'body' => json_encode(
[
'accountId' => $this->options->get_merchant_id(),
]
),
]
);
$response = json_decode( $result->getBody()->getContents(), true );
if ( 200 === $result->getStatusCode() && isset( $response['status'] ) && 'success' === $response['status'] ) {
return true;
}
do_action( 'woocommerce_gla_guzzle_invalid_response', $response, __METHOD__ );
$error = $response['message'] ?? __( 'Invalid response when linking merchant to MCA', 'google-listings-and-ads' );
throw new Exception( $error, $result->getStatusCode() );
} catch ( ClientExceptionInterface $e ) {
do_action( 'woocommerce_gla_guzzle_client_exception', $e, __METHOD__ );
throw new Exception(
$this->client_exception_message( $e, __( 'Error linking merchant to MCA', 'google-listings-and-ads' ) ),
$e->getCode()
);
}
}
/**
* Claim the website for a MCA.
*
* @param bool $overwrite To enable claim overwriting.
* @return bool
* @throws Exception When an Exception is caught or we receive an invalid response.
*/
public function claim_merchant_website( bool $overwrite = false ): bool {
try {
/** @var Client $client */
$client = $this->container->get( Client::class );
$result = $client->post(
$this->get_manager_url( 'claim-website' ),
[
'body' => json_encode(
[
'accountId' => $this->options->get_merchant_id(),
'overwrite' => $overwrite,
]
),
]
);
$response = json_decode( $result->getBody()->getContents(), true );
if ( 200 === $result->getStatusCode() && isset( $response['status'] ) && 'success' === $response['status'] ) {
do_action( 'woocommerce_gla_site_claim_success', [ 'details' => 'google_manager' ] );
return true;
}
do_action( 'woocommerce_gla_guzzle_invalid_response', $response, __METHOD__ );
do_action( 'woocommerce_gla_site_claim_failure', [ 'details' => 'google_manager' ] );
$error = $response['message'] ?? __( 'Invalid response when claiming website', 'google-listings-and-ads' );
throw new Exception( $error, $result->getStatusCode() );
} catch ( ClientExceptionInterface $e ) {
do_action( 'woocommerce_gla_guzzle_client_exception', $e, __METHOD__ );
do_action( 'woocommerce_gla_site_claim_failure', [ 'details' => 'google_manager' ] );
throw new Exception(
$this->client_exception_message( $e, __( 'Error claiming website', 'google-listings-and-ads' ) ),
$e->getCode()
);
}
}
/**
* Create a new Google Ads account.
*
* @return array
* @throws Exception When a ClientException is caught, unsupported store country, or we receive an invalid response.
*/
public function create_ads_account(): array {
try {
$country = WC()->countries->get_base_country();
/** @var GoogleHelper $google_helper */
$google_helper = $this->container->get( GoogleHelper::class );
if ( ! $google_helper->is_country_supported( $country ) ) {
throw new Exception( __( 'Store country is not supported', 'google-listings-and-ads' ) );
}
$user = wp_get_current_user();
$tos = $this->mark_tos_accepted( 'google-ads', $user->user_email );
if ( ! $tos->accepted() ) {
throw new Exception( __( 'Unable to log accepted TOS', 'google-listings-and-ads' ) );
}
/** @var Client $client */
$client = $this->container->get( Client::class );
$result = $client->post(
$this->get_manager_url( $country . '/create-customer' ),
[
'body' => json_encode(
[
'descriptive_name' => $this->new_account_name(),
'currency_code' => get_woocommerce_currency(),
'time_zone' => $this->get_site_timezone_string(),
]
),
]
);
$response = json_decode( $result->getBody()->getContents(), true );
if ( 200 === $result->getStatusCode() && isset( $response['resourceName'] ) ) {
/** @var Ads $ads */
$ads = $this->container->get( Ads::class );
$id = $ads->parse_ads_id( $response['resourceName'] );
$ads->update_ads_id( $id );
$ads->use_store_currency();
$billing_url = $response['invitationLink'] ?? '';
$ads->update_billing_url( $billing_url );
return [
'id' => $id,
'billing_url' => $billing_url,
];
}
do_action( 'woocommerce_gla_guzzle_invalid_response', $response, __METHOD__ );
$error = $response['message'] ?? __( 'Invalid response when creating account', 'google-listings-and-ads' );
throw new Exception( $error, $result->getStatusCode() );
} catch ( ClientExceptionInterface $e ) {
do_action( 'woocommerce_gla_guzzle_client_exception', $e, __METHOD__ );
throw new Exception(
$this->client_exception_message( $e, __( 'Error creating account', 'google-listings-and-ads' ) ),
$e->getCode()
);
}
}
/**
* Link an existing Google Ads account.
*
* @param int $id Existing account ID.
*
* @return array
* @throws Exception When a ClientException is caught or we receive an invalid response.
*/
public function link_ads_account( int $id ): array {
try {
/** @var Client $client */
$client = $this->container->get( Client::class );
$result = $client->post(
$this->get_manager_url( 'link-customer' ),
[
'body' => json_encode(
[
'client_customer' => $id,
]
),
]
);
$response = json_decode( $result->getBody()->getContents(), true );
$name = "customers/{$id}";
if ( 200 === $result->getStatusCode() && isset( $response['resourceName'] ) && 0 === strpos( $response['resourceName'], $name ) ) {
/** @var Ads $ads */
$ads = $this->container->get( Ads::class );
$ads->update_ads_id( $id );
$ads->request_ads_currency();
return [ 'id' => $id ];
}
do_action( 'woocommerce_gla_guzzle_invalid_response', $response, __METHOD__ );
$error = $response['message'] ?? __( 'Invalid response when linking account', 'google-listings-and-ads' );
throw new Exception( $error, $result->getStatusCode() );
} catch ( ClientExceptionInterface $e ) {
do_action( 'woocommerce_gla_guzzle_client_exception', $e, __METHOD__ );
throw new Exception(
$this->client_exception_message( $e, __( 'Error linking account', 'google-listings-and-ads' ) ),
$e->getCode()
);
}
}
/**
* Determine whether the TOS have been accepted.
*
* @param string $service Name of service.
*
* @return TosAccepted
*/
public function check_tos_accepted( string $service ): TosAccepted {
try {
/** @var Client $client */
$client = $this->container->get( Client::class );
$result = $client->get( $this->get_tos_url( $service ) );
return new TosAccepted( 200 === $result->getStatusCode(), $result->getBody()->getContents() );
} catch ( ClientExceptionInterface $e ) {
do_action( 'woocommerce_gla_guzzle_client_exception', $e, __METHOD__ );
return new TosAccepted( false, $e->getMessage() );
}
}
/**
* Record TOS acceptance for a particular email address.
*
* @param string $service Name of service.
* @param string $email
*
* @return TosAccepted
*/
public function mark_tos_accepted( string $service, string $email ): TosAccepted {
try {
/** @var Client $client */
$client = $this->container->get( Client::class );
$result = $client->post(
$this->get_tos_url( $service ),
[
'body' => json_encode(
[
'email' => $email,
]
),
]
);
return new TosAccepted(
200 === $result->getStatusCode(),
$result->getBody()->getContents() ?? $result->getReasonPhrase()
);
} catch ( ClientExceptionInterface $e ) {
do_action( 'woocommerce_gla_guzzle_client_exception', $e, __METHOD__ );
return new TosAccepted( false, $e->getMessage() );
}
}
/**
* Get the TOS endpoint URL
*
* @param string $service Name of service.
*
* @return string
*/
protected function get_tos_url( string $service ): string {
$url = $this->container->get( 'connect_server_root' ) . 'tos';
return $service ? trailingslashit( $url ) . $service : $url;
}
/**
* Get the manager endpoint URL
*
* @param string $name Resource name.
*
* @return string
*/
protected function get_manager_url( string $name = '' ): string {
$url = $this->container->get( 'connect_server_root' ) . 'google/manager';
return $name ? trailingslashit( $url ) . $name : $url;
}
/**
* Generate a descriptive name for a new account.
* Use site name if available.
*
* @return string
*/
protected function new_account_name(): string {
$site_name = get_bloginfo( 'name' );
return ! empty( $site_name ) ? $site_name : $this->default_account_name();
}
/**
* Generate a default account name based on the date.
*
* @return string
*/
protected function default_account_name(): string {
return sprintf(
/* translators: 1: current date in the format Y-m-d */
__( 'Account %1$s', 'google-listings-and-ads' ),
( new DateTime() )->format( 'Y-m-d' )
);
}
/**
* Get a timezone string from WP Settings.
*
* @return string
* @throws Exception If the DateTime instantiation fails.
*/
protected function get_site_timezone_string(): string {
/** @var WP $wp */
$wp = $this->container->get( WP::class );
$timezone = $wp->wp_timezone_string();
/** @var DateTimeUtility $datetime_util */
$datetime_util = $this->container->get( DateTimeUtility::class );
return $datetime_util->maybe_convert_tz_string( $timezone );
}
/**
* Get Account Review Status
*
* @return array With the response data
* @throws Exception When there is an invalid response.
*/
public function get_account_review_status() {
try {
if ( ! $this->is_subaccount() ) {
return [];
}
/** @var Client $client */
$client = $this->container->get( Client::class );
$result = $client->get(
$this->get_manager_url( 'account-review-status/' . $this->options->get_merchant_id() ),
);
$response = json_decode( $result->getBody()->getContents(), true );
if ( 200 === $result->getStatusCode() && isset( $response['freeListingsProgram'] ) && isset( $response['shoppingAdsProgram'] ) ) {
do_action( 'woocommerce_gla_request_review_response', $response );
return $response;
}
do_action( 'woocommerce_gla_guzzle_invalid_response', $response, __METHOD__ );
$error = $response['message'] ?? __( 'Invalid response getting account review status', 'google-listings-and-ads' );
throw new Exception( $error, $result->getStatusCode() );
} catch ( ClientExceptionInterface $e ) {
do_action( 'woocommerce_gla_guzzle_client_exception', $e, __METHOD__ );
throw new Exception(
$this->client_exception_message( $e, __( 'Error getting account review status', 'google-listings-and-ads' ) ),
$e->getCode()
);
}
}
/**
* Request a new account review
*
* @param array $regions Regions to request a review.
* @return array With a successful message
* @throws Exception When there is an invalid response.
*/
public function account_request_review( $regions ) {
try {
/** @var Client $client */
$client = $this->container->get( Client::class );
// For each region we request a new review
foreach ( $regions as $region_code ) {
$result = $client->post(
$this->get_manager_url( 'account-review-request' ),
[
'body' => json_encode(
[
'accountId' => $this->options->get_merchant_id(),
'regionCode' => $region_code,
]
),
]
);
$response = json_decode( $result->getBody()->getContents(), true );
if ( 200 !== $result->getStatusCode() ) {
do_action(
'woocommerce_gla_request_review_failure',
[
'error' => 'response',
'region_code' => $region_code,
'response' => $response,
]
);
do_action( 'woocommerce_gla_guzzle_invalid_response', $response, __METHOD__ );
$error = $response['message'] ?? __( 'Invalid response getting requesting a new review.', 'google-listings-and-ads' );
throw new Exception( $error, $result->getStatusCode() );
}
}
// Otherwise, return a successful message and update the account status
return [
'message' => __( 'A new review has been successfully requested', 'google-listings-and-ads' ),
];
} catch ( ClientExceptionInterface $e ) {
do_action( 'woocommerce_gla_guzzle_client_exception', $e, __METHOD__ );
throw new Exception(
$this->client_exception_message( $e, __( 'Error requesting a new review.', 'google-listings-and-ads' ) ),
$e->getCode()
);
}
}
/**
* This function detects if the current account is a sub-account
* This function is cached in the MC_IS_SUBACCOUNT transient
*
* @return bool True if it's a standalone account.
*/
public function is_subaccount(): bool {
/** @var TransientsInterface $transients */
$transients = $this->container->get( TransientsInterface::class );
$is_subaccount = $transients->get( $transients::MC_IS_SUBACCOUNT );
if ( is_null( $is_subaccount ) ) {
$is_subaccount = 0;
$merchant_id = $this->options->get_merchant_id();
$accounts = $this->get_merchant_accounts();
foreach ( $accounts as $account ) {
if ( $account['id'] === $merchant_id && $account['subaccount'] ) {
$is_subaccount = 1;
}
}
$transients->set( $transients::MC_IS_SUBACCOUNT, $is_subaccount );
}
// since transients don't support booleans, we save them as 0/1 and do the conversion here
return boolval( $is_subaccount );
}
}