forked from craftcms/commerce-paypal-checkout
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Gateway.php
763 lines (660 loc) · 21.6 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
<?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\Address;
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\PayPalCheckoutBundle;
use craft\commerce\paypalcheckout\responses\CheckoutResponse;
use craft\commerce\paypalcheckout\responses\RefundResponse;
use craft\commerce\Plugin;
use craft\helpers\ArrayHelper;
use craft\helpers\UrlHelper;
use craft\web\Response as WebResponse;
use craft\web\View;
use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Core\SandboxEnvironment;
use PayPalCheckoutSdk\Core\ProductionEnvironment;
use PayPalCheckoutSdk\Orders\OrdersAuthorizeRequest;
use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
use PayPalCheckoutSdk\Payments\AuthorizationsCaptureRequest;
use PayPalCheckoutSdk\Payments\CapturesRefundRequest;
use Throwable;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
use yii\base\Exception;
use yii\base\InvalidConfigException;
use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
/**
* This class represents the PayPal Checkout gateway
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 1.0
*/
class Gateway extends BaseGateway
{
const PAYMENT_TYPES = [
'authorize' => 'AUTHORIZE',
'purchase' => 'CAPTURE'
];
/**
* @since 1.1.0
*/
CONST SDK_URL = 'https://www.paypal.com/sdk/js';
// Public Properties
// =========================================================================
/**
* @var string
*/
public $clientId;
/**
* @var string
*/
public $secret;
/**
* @var string
*/
public $testMode;
/**
* @var string
*/
public $brandName;
/**
* @var string
*/
public $landingPage;
/**
* @var bool Whether cart information should be sent to the payment gateway
*/
public $sendCartInfo = false;
// Public Methods
// =========================================================================
/**
* @inheritdoc
*/
public static function displayName(): string
{
return Craft::t('commerce', 'PayPal Checkout');
}
/**
* @inheritdoc
*/
public function getSettingsHtml()
{
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)
{
$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://polyfill.io/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;
}
/**
* @inheritdoc
*/
public function getResponseModel($data): RequestResponseInterface
{
return new CheckoutResponse($data);
}
/**
* @param $data
* @return RefundResponse
*/
public function getRefundResponseModel($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 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 {
$apiResponse = $client->execute($request);
} catch (\Exception $e) {
throw new PaymentException($e->getMessage());
}
return $this->getResponseModel($apiResponse);
}
/**
* Complete the purchase for offsite payments.
*
* @param Transaction $transaction The transaction
* @return RequestResponseInterface
* @throws PaymentException
*/
public function completePurchase(Transaction $transaction): RequestResponseInterface
{
$request = new OrdersCaptureRequest($transaction->reference);
$client = $this->createClient();
try {
$apiResponse = $client->execute($request);
} catch (\Exception $e) {
throw new PaymentException($e->getMessage());
}
return $this->getResponseModel($apiResponse);
}
/**
* Creates a payment source from source data and user id.
*
* @param BasePaymentForm $sourceData
* @param int $userId
* @return PaymentSource
*/
public function createPaymentSource(BasePaymentForm $sourceData, int $userId): PaymentSource
{
// TODO: Implement createPaymentSource() method.
}
/**
* Deletes a payment source on the gateway by its token.
*
* @param string $token
* @return bool
*/
public function deletePaymentSource($token): bool
{
// TODO: Implement deletePaymentSource() method.
}
/**
* 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->testMode) {
$environment = new ProductionEnvironment(Craft::parseEnv($this->clientId), Craft::parseEnv($this->secret));
} else {
$environment = new SandboxEnvironment(Craft::parseEnv($this->clientId), Craft::parseEnv($this->secret));
}
return new PayPalHttpClient($environment);
}
/**
* Makes an refund request.
*
* @param Transaction $transaction The refund transaction
* @return RequestResponseInterface
*/
public function refund(Transaction $transaction): RequestResponseInterface
{
$parentTransaction = $transaction->getParent();
if (!$parentTransaction) {
Craft::error('Cannot retrieve parent transaction', __METHOD__);
}
$body = [
'amount' => [
'value' => $transaction->paymentAmount,
'currency_code' => $transaction->paymentCurrency
]
];
// 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', null);
} else {
$captureId = ArrayHelper::getValue($response, 'result.purchase_units.0.payments.captures.0.id', null);
}
$request = new CapturesRefundRequest($captureId);
$request->body = $body;
$request->prefer('return=representation');
$client = $this->createClient();
try {
$apiResponse = $client->execute($request);
return $this->getRefundResponseModel($apiResponse);
} catch (\Exception $e) {
return $this->getRefundResponseModel([
'message' => $e->getMessage()
]);
}
}
/**
* Processes a webhook and return a response
*
* @return WebResponse
* @throws Throwable if something goes wrong
*/
public function processWebHook(): WebResponse
{
}
/**
* 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;
}
/**
* @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->landingPage,
'shipping_preference' => $shippingPreference,
'user_action' => 'PAY_NOW',
'return_url' => UrlHelper::siteUrl($order->returnUrl),
'cancel_url' => UrlHelper::siteUrl($order->cancelUrl)
];
return $requestData;
}
// Private Methods
// =========================================================================
/**
* @param Order $order
* @param Transaction $transaction
* @return array
*/
private function _buildPurchaseUnits(Order $order, Transaction $transaction): array
{
$purchaseUnits = [
'description' => Craft::$app->getConfig()->getGeneral()->siteName,
'invoice_id' => $order->reference,
'custom_id' => $transaction->hash,
'soft_descriptor' => Craft::$app->getConfig()->getGeneral()->siteName,
'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->sendCartInfo && !$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;
}
/**
* @param Order $order
* @param Transaction $transaction
* @return array
*/
private function _buildItems(Order $order, Transaction $transaction): array
{
if (!$this->sendCartInfo || $this->_isPartialPayment($order) || !$this->_isPaymentInBaseCurrency($order, $transaction)) {
return [];
}
$lineItems = [];
foreach ($order->getLineItems() as $lineItem) {
$lineItems[] = [
'name' => $lineItem->description, // required
'sku' => $lineItem->sku,
'unit_amount' => [
'currency_code' => $order->paymentCurrency,
'value' => (string)Currency::round($lineItem->onSale ? $lineItem->salePrice : $lineItem->price),
], // required
'quantity' => $lineItem->qty, // required
];
}
return $lineItems;
}
/**
* @param Order $order
* @return array
*/
private function _buildShipping(Order $order): array
{
/** @var ShippingMethod $shippingMethod */
$shippingMethod = $order->getShippingMethod();
/** @var Address $shippingAddress */
$shippingAddress = $order->shippingAddress;
$return = [];
if ($shippingAddress && $shippingAddress->country) {
$return['address'] = $this->_buildAddressArray($shippingAddress);
$name = $shippingAddress->fullName ?: $shippingAddress->firstName . ' ' . $shippingAddress->lastName;
if ($name) {
$return['name'] = ['full_name' => $name];
}
}
if ($shippingAddress && $shippingMethod) {
$return['method'] = $shippingMethod->name;
}
return $return;
}
/**
* @param Order $order
* @return array
* @since 1.1.0
*/
private function _buildPayer(Order $order): array
{
/** @var Address $shippingAddress */
$billingAddress = $order->billingAddress;
$return = [
'email_address' => $order->email,
];
$name = [];
if ($billingAddress->fullName || $billingAddress->firstName) {
$name['given_name'] = $billingAddress->fullName ?: $billingAddress->firstName;
}
if (!$billingAddress->fullName && $billingAddress->lastName) {
$name['surname'] = $billingAddress->lastName;
}
if (!empty($name)) {
$return['name'] = $name;
}
if ($billingAddress && $billingAddress->country) {
$return['address'] = $this->_buildAddressArray($billingAddress);
}
return $return;
}
/**
* @param Address $address
* @return array
* @since 1.1.1
*/
private function _buildAddressArray(Address $address): array
{
$stateText = $address->stateText;
if ($address->stateId && $state = $address->getState()) {
$stateText = $state->abbreviation;
}
return [
'address_line_1' => $address->address1,
'address_line_2' => $address->address2,
'admin_area_2' => $address->city,
'admin_area_1' => $stateText,
'postal_code' => $address->zipCode,
'country_code' => $address->country->iso,
];
}
/**
* @param Order $order
* @return bool
* @since 1.0.5
*/
private function _isPartialPayment(Order $order): bool
{
return $order->hasOutstandingBalance() && $order->getOutstandingBalance() < $order->getTotal();
}
/**
* @param Order $order
* @param Transaction $transaction
* @return bool
* @since 1.1.0
*/
private function _isPaymentInBaseCurrency(Order $order, Transaction $transaction): bool
{
return $order->currency == $transaction->paymentCurrency;
}
/**
* @param array $passedParams
* @return string
* @since 1.1.0
*/
private function _sdkQueryParameters(Array $passedParams): string
{
$passedParamsMergeKeys = [
'currency',
'disable-card',
'disable-funding',
'locale',
];
$intent = strtolower(self::PAYMENT_TYPES[$this->paymentType]);
$params = [
'client-id' => Craft::parseEnv($this->clientId),
'intent' => $intent,
];
foreach ($passedParamsMergeKeys as $passedParamsMergeKey) {
if (isset($passedParams[$passedParamsMergeKey])) {
$params[$passedParamsMergeKey] = $passedParams[$passedParamsMergeKey];
}
}
foreach ($params as $key => &$param) {
$param = $key . '=' . urlencode($param);
}
return implode('&', $params);
}
}