-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathGateway.php
1103 lines (973 loc) · 33.8 KB
/
Gateway.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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license MIT
*/
namespace craft\commerce\paypalcheckout\gateways;
use Craft;
use craft\commerce\base\Gateway as BaseGateway;
use craft\commerce\base\RequestResponseInterface;
use craft\commerce\base\ShippingMethod;
use craft\commerce\elements\Order;
use craft\commerce\errors\PaymentException;
use craft\commerce\helpers\Currency;
use craft\commerce\models\payments\BasePaymentForm;
use craft\commerce\models\payments\OffsitePaymentForm;
use craft\commerce\models\PaymentSource;
use craft\commerce\models\Transaction;
use craft\commerce\paypalcheckout\events\BuildGatewayRequestEvent;
use craft\commerce\paypalcheckout\injectors\PayPalAuthorizationInjector;
use craft\commerce\paypalcheckout\PayPalCheckoutBundle;
use craft\commerce\paypalcheckout\responses\CheckoutResponse;
use craft\commerce\paypalcheckout\responses\RefundResponse;
use craft\commerce\Plugin;
use craft\elements\Address;
use craft\helpers\App;
use craft\helpers\ArrayHelper;
use craft\helpers\Json;
use craft\helpers\StringHelper;
use craft\helpers\UrlHelper;
use craft\web\Response as WebResponse;
use craft\web\View;
use PayPalCheckoutSdk\Core\AuthorizationInjector;
use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Core\ProductionEnvironment;
use PayPalCheckoutSdk\Core\SandboxEnvironment;
use PayPalCheckoutSdk\Orders\OrdersAuthorizeRequest;
use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
use PayPalCheckoutSdk\Payments\AuthorizationsCaptureRequest;
use PayPalCheckoutSdk\Payments\CapturesRefundRequest;
use PayPalHttp\HttpException;
use PayPalHttp\HttpResponse;
use PayPalHttp\IOException;
use Throwable;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
use yii\base\Exception;
use yii\base\InvalidConfigException;
use yii\base\NotSupportedException;
/**
* This class represents the PayPal Checkout gateway
*
* @property string|null $brandName
* @property string|null $clientId PayPal account client ID
* @property string|null $secret PayPal account secret API key
* @property string|null $landingPage The gateway’s landing page
* @property bool $sendCartInfo Whether cart information should be sent to the payment gateway
* @property bool|string $sendShippingInfo
* @property bool $testMode Whether Test Mode should be used
* @author Pixel & Tonic, Inc. <[email protected]>
* @since 1.0
*
* @property-read null|string $settingsHtml
*/
class Gateway extends BaseGateway
{
public const PAYMENT_TYPES = [
'authorize' => 'AUTHORIZE',
'purchase' => 'CAPTURE',
];
/**
* @since 1.1.0
*/
public const SDK_URL = 'https://www.paypal.com/sdk/js';
/**
* @event BuildGatewayRequestEvent The event that is triggered when a gateway request is being built.
*
* Plugins get a chance to provide additional data to any request that is made to PayPal in the context of paying for an order.
*
* There are some restrictions:
* Changes to the `Transaction` model available as the `transaction` property will be ignored;
* Changes to amounts sent to paypal that cause the payment to be less that the transaction amount will not complete the order and cause unforeseen problems.
*
* ```php
* use craft\commerce\models\Transaction;
* use craft\commerce\paypalcheckout\events\BuildGatewayRequestEvent;
* use craft\commerce\paypalcheckout\base\Gateway as PaypalGateway;
* use yii\base\Event;
*
* Event::on(PaypalGateway::class, PaypalGateway::EVENT_BUILD_GATEWAY_REQUEST, function(BuildGatewayRequestEvent $e) {
* if ($e->transaction->type === 'purchase') {
* $e->request['someKey'] = 'some value';
* }
* });
* ```
*
*/
public const EVENT_BUILD_GATEWAY_REQUEST = 'buildGatewayRequest';
/**
* @var string|null PayPal account client ID.
* @see getClientId()
* @see setClientId()
*/
private ?string $_clientId = null;
/**
* @var string|null PayPal account secret API key.
* @see getSecret()
* @see setSecret()
*/
private ?string $_secret = null;
/**
* @var string|null The label that overrides the business name on off-site PayPal pages.
* @see getBrandName()
* @see setBrandName()
*/
public ?string $_brandName = null;
/**
* @var string|null The type of landing page to display on the PayPal site for user checkout.
*
* To use the non-PayPal account landing page, set to `Billing`. To use the PayPal account login landing page, set to `Login`.
*
* @see getLandingPage()
* @see setLandingPage()
*/
private ?string $_landingPage = null;
/**
* @var bool|string Whether cart information should be sent to the payment gateway
* @see getSendCartInfo()
* @see setSendCartInfo()
*/
private string|bool $_sendCartInfo = false;
/**
* @var bool|string Whether shipping information should be sent to the payment gateway
* @see getSendShippingInfo()
* @see setSendShippingInfo()
* @since 2.0.1
*/
private string|bool $_sendShippingInfo = true;
/**
* @var bool|string Whether Test Mode should be used
* @see getTestMode()
* @see setTestMode()
*/
private string|bool $_testMode = false;
/**
* @inheritdoc
*/
public function getSettings(): array
{
$settings = parent::getSettings();
$settings['brandName'] = $this->getBrandName(false);
$settings['clientId'] = $this->getClientId(false);
$settings['secret'] = $this->getSecret(false);
$settings['landingPage'] = $this->getLandingPage(false);
$settings['sendCartInfo'] = $this->getSendCartInfo(false);
$settings['sendShippingInfo'] = $this->getSendShippingInfo(false);
$settings['testMode'] = $this->getTestMode(false);
return $settings;
}
/**
* Returns the gateway’s client ID.
*
* @param bool $parse Whether to parse the value as an environment variable
* @return string|null
* @since 1.3.1
*/
public function getClientId(bool $parse = true): ?string
{
return $parse ? App::parseEnv($this->_clientId) : $this->_clientId;
}
/**
* Sets the gateway’s client ID.
*
* @param string|null $clientId
* @since 1.3.1
*/
public function setClientId(?string $clientId): void
{
$this->_clientId = $clientId;
}
/**
* Returns the gateway’s brand name.
*
* @param bool $parse Whether to parse the value as an environment variable
* @return string|null
* @since 2.0.0
*/
public function getBrandName(bool $parse = true): ?string
{
return $parse ? App::parseEnv($this->_brandName) : $this->_brandName;
}
/**
* Sets the gateway’s brand name.
*
* @param string|null $brandName
* @since 2.0.0
*/
public function setBrandName(?string $brandName): void
{
$this->_brandName = $brandName;
}
/**
* Returns the gateway’s secret API key.
*
* @param bool $parse Whether to parse the value as an environment variable
* @return string|null
* @since 1.3.1
*/
public function getSecret(bool $parse = true): ?string
{
return $parse ? App::parseEnv($this->_secret) : $this->_secret;
}
/**
* Sets the gateway’s secret API key.
*
* @param string|null $secret
* @since 1.3.1
*/
public function setSecret(?string $secret): void
{
$this->_secret = $secret;
}
/**
* Returns the gateway’s landing page.
*
* @param bool $parse Whether to parse the value as an environment variable
* @return string|null
* @since 1.3.1
*/
public function getLandingPage(bool $parse = true): ?string
{
return $parse ? App::parseEnv($this->_landingPage) : $this->_landingPage;
}
/**
* Sets the gateway’s landing page.
*
* @param string|null $landingPage
* @since 1.3.1
*/
public function setLandingPage(?string $landingPage): void
{
$this->_landingPage = $landingPage;
}
/**
* Returns whether Test Mode should be used.
*
* @param bool $parse Whether to parse the value as an environment variable
* @return bool|string
* @since 1.3.1
*/
public function getTestMode(bool $parse = true): bool|string
{
return $parse ? App::parseBooleanEnv($this->_testMode) : $this->_testMode;
}
/**
* Sets whether Test Mode should be used.
*
* @param bool|string $testMode
* @since 1.3.1
*/
public function setTestMode(bool|string $testMode): void
{
$this->_testMode = $testMode;
}
/**
* Returns whether cart information should be sent to the payment gateway.
*
* @param bool $parse Whether to parse the value as an environment variable
* @return bool|string
* @since 1.3.1
*/
public function getSendCartInfo(bool $parse = true): bool|string
{
return $parse ? App::parseBooleanEnv($this->_sendCartInfo) : $this->_sendCartInfo;
}
/**
* Sets whether cart information should be sent to the payment gateway.
*
* @param bool|string $sendCartInfo
* @since 1.3.1
*/
public function setSendCartInfo(bool|string $sendCartInfo): void
{
$this->_sendCartInfo = $sendCartInfo;
}
/**
* Returns whether shipping information should be sent to the payment gateway.
*
* @param bool $parse Whether to parse the value as an environment variable
* @return bool|string
* @since 2.0.1
*/
public function getSendShippingInfo(bool $parse = true): bool|string
{
return $parse ? App::parseBooleanEnv($this->_sendShippingInfo) : $this->_sendShippingInfo;
}
/**
* Sets whether shipping information should be sent to the payment gateway.
*
* @param bool|string $sendShippingInfo
* @since 2.0.1
*/
public function setSendShippingInfo(bool|string $sendShippingInfo): void
{
$this->_sendShippingInfo = $sendShippingInfo;
}
/**
* @inheritdoc
*/
public static function displayName(): string
{
return Craft::t('commerce', 'PayPal Checkout');
}
/**
* @inheritdoc
*/
public function getSettingsHtml(): ?string
{
return Craft::$app->getView()->renderTemplate('commerce-paypal-checkout/settings', ['gateway' => $this]);
}
/**
* Returns payment Form HTML
*
* @param array $params
* @return string|null
* @throws LoaderError
* @throws RuntimeError
* @throws SyntaxError
* @throws Exception
* @throws InvalidConfigException
*/
public function getPaymentFormHtml(array $params): ?string
{
$defaults = [
'gateway' => $this,
'currency' => Plugin::getInstance()->getPaymentCurrencies()->getPrimaryPaymentCurrencyIso(),
];
$params = array_merge($defaults, $params);
$view = Craft::$app->getView();
$previousMode = $view->getTemplateMode();
$view->setTemplateMode(View::TEMPLATE_MODE_CP);
$view->registerJsFile(self::SDK_URL . '?' . $this->_sdkQueryParameters($params), ['data-namespace' => 'paypal_checkout_sdk']);
// IE polyfill
$view->registerJsFile('https://cdnjs.cloudflare.com/polyfill/v3/polyfill.min.js?features=fetch%2CPromise%2CPromise.prototype.finally');
$view->registerAssetBundle(PayPalCheckoutBundle::class);
$html = Craft::$app->getView()->renderTemplate('commerce-paypal-checkout/paymentForm', $params);
$view->setTemplateMode($previousMode);
return $html;
}
/**
* @param HttpResponse $data
* @return RequestResponseInterface
*/
public function getResponseModel(HttpResponse $data): RequestResponseInterface
{
return new CheckoutResponse($data);
}
/**
* @param array|HttpResponse $data
* @return RefundResponse
*/
public function getRefundResponseModel(array|HttpResponse $data): RefundResponse
{
return new RefundResponse($data);
}
/**
* Makes an authorize request.
*
* @param Transaction $transaction The authorize transaction
* @param BasePaymentForm $form A form filled with payment info
* @return RequestResponseInterface
* @throws Exception
* @throws PaymentException
*/
public function authorize(Transaction $transaction, BasePaymentForm $form): RequestResponseInterface
{
// Authorize is the same request as purchase only that the intent is different
// which is set from the gateway settings
return $this->purchase($transaction, $form);
}
/**
* Makes a capture request.
*
* @param Transaction $transaction The capture transaction
* @param string $reference Reference for the transaction being captured.
* @return RequestResponseInterface
* @throws InvalidConfigException
* @throws PaymentException
*/
public function capture(Transaction $transaction, string $reference): RequestResponseInterface
{
$parentTransaction = $transaction->getParent();
if (!$parentTransaction) {
Craft::error('Cannot retrieve parent transaction', __METHOD__);
}
$response = json_decode($parentTransaction->response, false);
$authorizationId = $response->result->purchase_units[0]->payments->authorizations[0]->id ?? null;
if (!$authorizationId) {
Craft::error('An Authorization ID is required to capture', __METHOD__);
}
$request = new AuthorizationsCaptureRequest($authorizationId);
$request->body = '{}';
$request->prefer('return=representation');
$client = $this->createClient();
try {
$apiResponse = $client->execute($request);
} catch (\Exception $e) {
throw new PaymentException($e->getMessage());
}
return $this->getResponseModel($apiResponse);
}
/**
* Complete the authorization for offsite payments.
*
* @param Transaction $transaction The transaction
* @return RequestResponseInterface
* @throws PaymentException
*/
public function completeAuthorize(Transaction $transaction): RequestResponseInterface
{
$request = new OrdersAuthorizeRequest($transaction->reference);
$request->body = '{}';
$request->prefer('return=representation');
$client = $this->createClient();
try {
$data = $client->execute($request);
} catch (\Exception $e) {
$data = $this->_getErrorResponse($e, $transaction);
}
return $this->getResponseModel($data);
}
/**
* Complete the purchase for offsite payments.
*
* @param Transaction $transaction The transaction
* @return RequestResponseInterface
*/
public function completePurchase(Transaction $transaction): RequestResponseInterface
{
$request = new OrdersCaptureRequest($transaction->reference);
$request->prefer('return=representation');
$client = $this->createClient();
try {
$data = $client->execute($request);
} catch (HttpException|IOException $e) {
$data = $this->_getErrorResponse($e, $transaction);
}
return $this->getResponseModel($data);
}
/**
* Creates a payment source from source data and user id.
*
* @param BasePaymentForm $sourceData
* @param int $customerId
* @return PaymentSource
* @throws NotSupportedException
*/
public function createPaymentSource(BasePaymentForm $sourceData, int $customerId): PaymentSource
{
if (!$this->supportsPaymentSources()) {
throw new NotSupportedException(Craft::t('commerce', 'Payment sources are not supported by this gateway'));
}
return new PaymentSource();
}
/**
* Deletes a payment source on the gateway by its token.
*
* @param string $token
* @return bool
* @throws NotSupportedException
*/
public function deletePaymentSource(string $token): bool
{
if (!$this->supportsPaymentSources()) {
throw new NotSupportedException(Craft::t('commerce', 'Payment sources are not supported by this gateway'));
}
return false;
}
/**
* Returns payment form model to use in payment forms.
*
* @return BasePaymentForm
*/
public function getPaymentFormModel(): BasePaymentForm
{
return new OffsitePaymentForm();
}
/**
* Makes a purchase request.
*
* @param Transaction $transaction The purchase transaction
* @param BasePaymentForm $form A form filled with payment info
* @return RequestResponseInterface
* @throws PaymentException
* @throws Exception
*/
public function purchase(Transaction $transaction, BasePaymentForm $form): RequestResponseInterface
{
$requestData = $this->buildCreateOrderRequestData($transaction);
$request = new OrdersCreateRequest();
$request->prefer('return=representation');
$request->body = $requestData;
$client = $this->createClient();
try {
$apiResponse = $client->execute($request);
} catch (\Exception $e) {
throw new PaymentException($e->getMessage());
}
return $this->getResponseModel($apiResponse);
}
/**
* @return PayPalHttpClient
*/
public function createClient(): PayPalHttpClient
{
if (!$this->getTestMode()) {
$environment = new ProductionEnvironment($this->getClientId(), $this->getSecret());
} else {
$environment = new SandboxEnvironment($this->getClientId(), $this->getSecret());
}
$httpClient = new PayPalHttpClient($environment);
foreach ($httpClient->injectors as &$injector) {
if (!$injector instanceof AuthorizationInjector) {
continue;
}
// Replace the core authorization injector
$injector = new PayPalAuthorizationInjector($httpClient, $environment);
}
return $httpClient;
}
/**
* Makes a refund request.
*
* @param Transaction $transaction The refund transaction
* @return RequestResponseInterface
* @throws InvalidConfigException
* @throws \Exception
*/
public function refund(Transaction $transaction): RequestResponseInterface
{
$parentTransaction = $transaction->getParent();
if (!$parentTransaction) {
Craft::error('Cannot retrieve parent transaction', __METHOD__);
}
$paymentCurrency = Plugin::getInstance()->getPaymentCurrencies()->getPaymentCurrencyByIso($transaction->paymentCurrency);
$amountValue = $paymentCurrency ? Currency::round($transaction->paymentAmount, $paymentCurrency) : $transaction->paymentAmount;
$body = [
'amount' => [
'value' => (string)$amountValue,
'currency_code' => $transaction->paymentCurrency,
],
];
$event = new BuildGatewayRequestEvent([
'type' => 'refund',
'transaction' => $transaction,
'request' => $body,
]);
if ($this->hasEventHandlers(self::EVENT_BUILD_GATEWAY_REQUEST)) {
$this->trigger(self::EVENT_BUILD_GATEWAY_REQUEST, $event);
}
// Get the data from different locations based on which type of transaction
// the parent was
$response = json_decode($parentTransaction->response, true);
if ($parentTransaction->type == 'capture') {
$captureId = ArrayHelper::getValue($response, 'result.id');
} else {
$captureId = ArrayHelper::getValue($response, 'result.purchase_units.0.payments.captures.0.id');
}
$request = new CapturesRefundRequest($captureId);
$request->body = $event->request;
$request->prefer('return=representation');
$client = $this->createClient();
try {
$apiResponse = $client->execute($request);
return $this->getRefundResponseModel($apiResponse);
} catch (HttpException|IOException $e) {
return $this->getRefundResponseModel(new HttpResponse(0, Json::decodeIfJson($e->getMessage()), []));
}
}
/**
* Processes a webhook and return a response
*
* @return WebResponse
* @throws Throwable if something goes wrong
*/
public function processWebHook(): WebResponse
{
$response = Craft::$app->getResponse();
$response->data = 'ok';
return $response;
}
/**
* Returns true if gateway supports authorize requests.
*
* @return bool
*/
public function supportsAuthorize(): bool
{
return true;
}
/**
* Returns true if gateway supports capture requests.
*
* @return bool
*/
public function supportsCapture(): bool
{
return true;
}
/**
* Returns true if gateway supports completing authorize requests
*
* @return bool
*/
public function supportsCompleteAuthorize(): bool
{
return true;
}
/**
* Returns true if gateway supports completing purchase requests
*
* @return bool
*/
public function supportsCompletePurchase(): bool
{
return true;
}
/**
* Returns true if gateway supports payment sources
*
* @return bool
*/
public function supportsPaymentSources(): bool
{
return false;
}
/**
* Returns true if gateway supports purchase requests.
*
* @return bool
*/
public function supportsPurchase(): bool
{
return true;
}
/**
* Returns true if gateway supports refund requests.
*
* @return bool
*/
public function supportsRefund(): bool
{
return true;
}
/**
* Returns true if gateway supports partial refund requests.
*
* @return bool
*/
public function supportsPartialRefund(): bool
{
return true;
}
/**
* Returns true if gateway supports webhooks.
*
* @return bool
*/
public function supportsWebhooks(): bool
{
return false;
}
/**
* @inheritdoc
*/
public function cpPaymentsEnabled(): bool
{
return false;
}
/**
* @return bool
*/
public function showPaymentFormSubmitButton(): bool
{
return false;
}
/**
* @param Transaction $transaction
* @return array
* @throws Exception
*/
protected function buildCreateOrderRequestData(Transaction $transaction): array
{
$order = $transaction->order;
$requestData = [];
$requestData['intent'] = self::PAYMENT_TYPES[$this->paymentType] ?? 'CAPTURE';
if ($payer = $this->_buildPayer($order)) {
$requestData['payer'] = $payer;
}
$requestData['purchase_units'] = $this->_buildPurchaseUnits($order, $transaction);
$shippingPreference = isset($requestData['purchase_units'][0]['shipping']) && !empty($requestData['purchase_units'][0]['shipping']) && isset($requestData['purchase_units'][0]['shipping']['address']) ? 'SET_PROVIDED_ADDRESS' : 'NO_SHIPPING';
$requestData['application_context'] = [
'brand_name' => $this->brandName,
'locale' => Craft::$app->getLocale()->id,
'landing_page' => $this->getLandingPage(),
'shipping_preference' => $shippingPreference,
'user_action' => 'PAY_NOW',
'return_url' => UrlHelper::siteUrl($order->returnUrl),
'cancel_url' => UrlHelper::siteUrl($order->cancelUrl),
];
$event = new BuildGatewayRequestEvent([
'type' => 'purchase',
'transaction' => $transaction,
'request' => $requestData,
]);
if ($this->hasEventHandlers(self::EVENT_BUILD_GATEWAY_REQUEST)) {
$this->trigger(self::EVENT_BUILD_GATEWAY_REQUEST, $event);
}
return $event->request;
}
/**
* Build purchase units adhering to the criteria set out in the docs
* https://developer.paypal.com/docs/api/orders/v2/#definition-purchase_unit
*
* @param Order $order
* @param Transaction $transaction
* @return array
* @throws \craft\errors\SiteNotFoundException
*/
private function _buildPurchaseUnits(Order $order, Transaction $transaction): array
{
$siteName = Craft::$app->getSites()->getCurrentSite()->getName();
$purchaseUnits = [
'description' => StringHelper::truncate($siteName, 127, ''),
'invoice_id' => StringHelper::truncate($order->number, 127, ''),
'custom_id' => StringHelper::truncate($transaction->hash, 127, ''),
'soft_descriptor' => StringHelper::truncate(StringHelper::regexReplace($siteName, "[^a-zA-Z0-9\*\.\-\s]", ''), 22, ''),
'amount' => $this->_buildAmount($order, $transaction),
'items' => $this->_buildItems($order, $transaction),
];
$shipping = $this->_buildShipping($order);
if (!empty($shipping)) {
$purchaseUnits['shipping'] = $shipping;
}
return [
$purchaseUnits,
];
}
/**
* @param Order $order
* @param Transaction $transaction
* @return array
*/
private function _buildAmount(Order $order, Transaction $transaction): array
{
$return = [
'currency_code' => $transaction->paymentCurrency,
'value' => (string)$transaction->paymentAmount,
];
if ($this->getSendCartInfo() && !$this->_isPartialPayment($order) && $this->_isPaymentInBaseCurrency($order, $transaction)) {
$return['breakdown'] = [
'item_total' =>
[
'currency_code' => $order->paymentCurrency,
'value' => (string)Currency::round($order->getItemSubtotal()),
],
'shipping' =>
[
'currency_code' => $order->paymentCurrency,
'value' => (string)Currency::round($order->getTotalShippingCost()),
],
'tax_total' =>
[
'currency_code' => $order->paymentCurrency,
'value' => (string)Currency::round($order->getTotalTax()),
],
];
// $discount = $order->getAdjustmentsTotalByType('discount') * -1;
$discount = $order->getTotalDiscount();
if ($discount != 0) {
$return['breakdown']['discount'] = [
'currency_code' => $order->paymentCurrency,
'value' => (string)Currency::round($discount * -1), // Needs to be a positive number
];
}
}
return $return;
}
/**
* Build items array adhering to the PayPal API spec
* https://developer.paypal.com/docs/api/orders/v2/#definition-item
*
* @param Order $order
* @param Transaction $transaction
* @return array
*/
private function _buildItems(Order $order, Transaction $transaction): array
{
if (!$this->getSendCartInfo() || $this->_isPartialPayment($order) || !$this->_isPaymentInBaseCurrency($order, $transaction)) {
return [];
}
$lineItems = [];
foreach ($order->getLineItems() as $lineItem) {
$lineItems[] = [
'name' => StringHelper::truncate($lineItem->getDescription(), 127, ''), // required
'sku' => StringHelper::truncate($lineItem->getSku(), 127, ''),
'unit_amount' => [
'currency_code' => $order->paymentCurrency,
'value' => (string)Currency::round($lineItem->getOnPromotion() ? $lineItem->salePrice : $lineItem->price),
], // required
'quantity' => $lineItem->qty, // required
];
}
return $lineItems;
}
/**
* @param Order $order
* @return array
*/
private function _buildShipping(Order $order): array
{
$return = [];
if (!$this->getSendShippingInfo()) {
return $return;
}
/** @var ShippingMethod|null $shippingMethod */
$shippingMethod = $order->getShippingMethod();
/** @var Address|null $shippingAddress */
$shippingAddress = $order->getShippingAddress();
if ($shippingAddress && $shippingAddress->getCountryCode()) {
$return['address'] = $this->_buildAddressArray($shippingAddress);
/** @var string|null $fullName */
$fullName = $shippingAddress->fullName;
/** @var string|null $firstName */
$firstName = $shippingAddress->firstName;
/** @var string|null $lastName */
$lastName = $shippingAddress->lastName;
$name = $fullName ?: $firstName . ' ' . $lastName;
if (trim($name)) {
$return['name'] = ['full_name' => StringHelper::truncate($name, 300, '')];
}
}
if ($shippingAddress && $shippingMethod) {
$return['method'] = $shippingMethod->name;
}
return $return;
}
/**
* Build payer data based on APi spec
* https://developer.paypal.com/docs/api/orders/v2/#definition-payer
*
* @param Order $order
* @return ?array
* @since 1.1.0
*/
private function _buildPayer(Order $order): ?array
{
/** @var Address|null $billingAddress */
$billingAddress = $order->billingAddress;
if (!$billingAddress && !$order->email) {
return null;
}
$return = [
'email_address' => StringHelper::truncate($order->email, 254, ''),
];
if (!$billingAddress) {
return $return;
}
$name = [];
if ($billingAddress->firstName || $billingAddress->fullName) {
$name['given_name'] = StringHelper::truncate($billingAddress->firstName ?: $billingAddress->fullName, 140, '');
}
if ($billingAddress->lastName || $billingAddress->fullName) {
$name['surname'] = StringHelper::truncate($billingAddress->lastName ?: $billingAddress->fullName, 140, '');
}
if (!empty($name)) {
$return['name'] = $name;
}