forked from craftcms/commerce-stripe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPaymentIntents.php
730 lines (614 loc) · 27.8 KB
/
PaymentIntents.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
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license MIT
*/
namespace craft\commerce\stripe\gateways;
use Craft;
use craft\commerce\base\Plan as BasePlan;
use craft\commerce\base\RequestResponseInterface;
use craft\commerce\base\SubscriptionResponseInterface;
use craft\commerce\behaviors\CustomerBehavior;
use craft\commerce\elements\Order;
use craft\commerce\elements\Subscription;
use craft\commerce\errors\PaymentSourceCreatedLaterException;
use craft\commerce\errors\SubscriptionException;
use craft\commerce\models\payments\BasePaymentForm;
use craft\commerce\models\PaymentSource;
use craft\commerce\models\subscriptions\SubscriptionForm as BaseSubscriptionForm;
use craft\commerce\models\Transaction;
use craft\commerce\Plugin;
use craft\commerce\Plugin as Commerce;
use craft\commerce\stripe\base\SubscriptionGateway as BaseGateway;
use craft\commerce\stripe\errors\PaymentSourceException;
use craft\commerce\stripe\events\BuildGatewayRequestEvent;
use craft\commerce\stripe\events\PaymentIntentConfirmationEvent;
use craft\commerce\stripe\events\SubscriptionRequestEvent;
use craft\commerce\stripe\models\forms\payment\PaymentIntent as PaymentIntentForm;
use craft\commerce\stripe\models\forms\Subscription as SubscriptionForm;
use craft\commerce\stripe\Plugin as StripePlugin;
use craft\commerce\stripe\responses\CheckoutSessionResponse;
use craft\commerce\stripe\responses\PaymentIntentResponse;
use craft\commerce\stripe\web\assets\elementsform\ElementsFormAsset;
use craft\commerce\stripe\web\assets\intentsform\IntentsFormAsset;
use craft\elements\User;
use craft\helpers\ArrayHelper;
use craft\helpers\Json;
use craft\helpers\StringHelper;
use craft\helpers\UrlHelper;
use craft\web\View;
use Exception;
use Stripe\Card;
use Stripe\Checkout\Session as StripeCheckoutSession;
use Stripe\PaymentIntent;
use Throwable;
use yii\base\NotSupportedException;
/**
* This class represents the Stripe Payment Intents gateway
*
* @property-read null|string $settingsHtml
* @property bool $sendReceiptEmail
* @property string $apiKey
* @property string $publishableKey
* @property string $signingSecret
* @author Pixel & Tonic, Inc. <[email protected]>
* @since 2.0
**/
class PaymentIntents extends BaseGateway
{
public const PAYMENT_FORM_TYPE_CHECKOUT = 'checkout';
public const PAYMENT_FORM_TYPE_ELEMENTS = 'elements';
/**
* @event BeforeConfirmPaymentIntent The event that is triggered before a PaymentIntent is confirmed
*/
public const EVENT_BEFORE_CONFIRM_PAYMENT_INTENT = 'beforeConfirmPaymentIntent';
/**
* @inheritdoc
*/
public static function displayName(): string
{
return Craft::t('commerce-stripe', 'Stripe');
}
/**
* @inheritDoc
*/
public function showPaymentFormSubmitButton(): bool
{
return false;
}
/**
* @inheritdoc
*/
public function getOldPaymentFormHtml(array $params): ?string
{
$defaults = [
'gateway' => $this,
'paymentForm' => $this->getPaymentFormModel(),
'scenario' => 'payment',
'handle' => $this->handle,
];
$params = ArrayHelper::merge($defaults, $params);
// If there's no order passed, add the current cart if we're not messing around in backend.
if (!isset($params['order']) && !Craft::$app->getRequest()->getIsCpRequest()) {
if ($cart = Commerce::getInstance()->getCarts()->getCart()) {
$billingAddress = $cart->getBillingAddress();
/** @var User|CustomerBehavior|null $user */
$user = $cart->getCustomer();
if (!$billingAddress && $user) {
$billingAddress = $user->getPrimaryBillingAddress();
}
}
} else {
$billingAddress = $params['order']->getBillingAddress();
}
if ($billingAddress) {
$params['billingAddress'] = $billingAddress;
}
$view = Craft::$app->getView();
$previousMode = $view->getTemplateMode();
$view->setTemplateMode(View::TEMPLATE_MODE_CP);
$view->registerScript('', View::POS_END, ['src' => 'https://js.stripe.com/v3/']); // we need this to load at end of body
$view->registerAssetBundle(IntentsFormAsset::class);
$html = $view->renderTemplate('commerce-stripe/paymentForms/oldIntentsForm', $params);
$view->setTemplateMode($previousMode);
return $html;
}
/**
* @inheritdoc
*/
public function getPaymentFormHtml(array $params): ?string
{
$defaults = [
'clientSecret' => '',
'scenario' => 'payment',
'order' => null,
'gateway' => $this,
'handle' => $this->handle,
'appearance' => [
'theme' => 'stripe',
],
'elementOptions' => [
'layout' => [
'type' => 'tabs',
],
],
'hiddenClass' => 'hidden',
'submitButtonClasses' => '',
'errorMessageClasses' => '',
'submitButtonText' => Craft::t('commerce', 'Pay'),
'processingButtonText' => Craft::t('commerce', 'Processing…'),
'paymentFormType' => self::PAYMENT_FORM_TYPE_ELEMENTS,
];
/** @var ?Order $order */
$order = $params['order'] ?? null;
if ($order && $order->getBillingAddress()) {
$defaultBillingAddressValues = [
'country' => $order->getBillingAddress()->getCountryCode() ?: '',
'line1' => $order->getBillingAddress()->addressLine1 ?? '',
'line2' => $order->getBillingAddress()->addressLine2 ?? '',
'city' => $order->getBillingAddress()->locality ?? '',
'postal_code' => $order->getBillingAddress()->postalCode ?? '',
'state' => $order->getBillingAddress()->getAdministrativeArea() ?? '',
];
$defaults['elementOptions']['defaultValues'] = [
'billingDetails' => [
'name' => $order->getBillingAddress()->fullName ?? '',
'email' => $order->email,
'address' => $defaultBillingAddressValues,
],
];
}
$params = ArrayHelper::merge($defaults, $params);
if ($params['scenario'] == '') {
return Craft::t('commerce-stripe', 'Commerce Stripe 4.0+ requires a scenario is set on the payment form.');
}
$view = Craft::$app->getView();
$previousMode = $view->getTemplateMode();
if (Craft::$app->getRequest()->isCpRequest) {
$view->setTemplateMode(View::TEMPLATE_MODE_CP);
}
$view->registerScript('', View::POS_END, ['src' => 'https://js.stripe.com/v3/']); // we need this to load at end of body
if ($params['paymentFormType'] == self::PAYMENT_FORM_TYPE_ELEMENTS) {
$view->registerAssetBundle(ElementsFormAsset::class);
}
// Template mode needs to be CP for the payment form to work
$view->setTemplateMode(View::TEMPLATE_MODE_CP);
$templatePath = ($params['paymentFormType'] == self::PAYMENT_FORM_TYPE_CHECKOUT)
? 'commerce-stripe/paymentForms/checkoutForm'
: 'commerce-stripe/paymentForms/elementsForm';
$html = $view->renderTemplate($templatePath, $params);
$view->setTemplateMode($previousMode);
return $html;
}
public function capture(Transaction $transaction, string $reference): RequestResponseInterface
{
try {
$intent = $this->getStripeClient()->paymentIntents->retrieve($reference);
$intent->capture([], ['idempotency_key' => $reference]);
return $this->createPaymentResponseFromApiResource($intent);
} catch (Exception $exception) {
return $this->createPaymentResponseFromError($exception);
}
}
/**
* @inheritdoc
*/
public function getPaymentFormModel(): BasePaymentForm
{
return new PaymentIntentForm();
}
/**
* @inheritdoc
*/
public function getResponseModel(mixed $data): RequestResponseInterface
{
return new PaymentIntentResponse($data);
}
/**
* @inheritdoc
*/
public function completePurchase(Transaction $transaction): RequestResponseInterface
{
$data = Json::decodeIfJson($transaction->response);
$paymentIntentOptions = [
'expand' => ['payment_method'],
];
if ($data['object'] == 'payment_intent') {
$paymentIntent = $this->getStripeClient()->paymentIntents->retrieve($data['id'], $paymentIntentOptions);
} else {
// Likely a checkout object
$checkoutSession = $this->getStripeClient()->checkout->sessions->retrieve($data['id']);
$paymentIntent = $checkoutSession['payment_intent'];
$paymentIntent = $this->getStripeClient()->paymentIntents->retrieve($paymentIntent, $paymentIntentOptions);
}
return $this->createPaymentResponseFromApiResource($paymentIntent);
}
/**
* @inheritdoc
*/
public function getSettingsHtml(): ?string
{
return Craft::$app->getView()->renderTemplate('commerce-stripe/gatewaySettings/intentsSettings', ['gateway' => $this]);
}
/**
* @inheritdoc
*/
public function refund(Transaction $transaction): RequestResponseInterface
{
$currency = Commerce::getInstance()->getCurrencies()->getCurrencyByIso($transaction->paymentCurrency);
if (!$currency) {
throw new NotSupportedException('The currency “' . $transaction->paymentCurrency . '” is not supported!');
}
// Are we dealing with a transaction that was created under the previous 'Charge' gateway?
if (substr($transaction->reference, 0, 3) === "ch_") {
try {
$request = [
'charge' => $transaction->reference,
'amount' => (int) bcmul($transaction->paymentAmount, 10 ** $currency->minorUnit),
];
$refund = $this->getStripeClient()->refunds->create($request);
return $this->createPaymentResponseFromApiResource($refund);
} catch (Exception $exception) {
return $this->createPaymentResponseFromError($exception);
}
}
$stripePaymentIntent = $this->getStripeClient()->paymentIntents->retrieve($transaction->reference);
try {
if ($stripePaymentIntent->status == 'succeeded') {
$refund = $this->getStripeClient()->refunds->create([
'payment_intent' => $stripePaymentIntent->id,
'amount' => (int) bcmul($transaction->paymentAmount, 10 ** $currency->minorUnit),
]);
return $this->createPaymentResponseFromApiResource($refund);
}
} catch (Exception $exception) {
return $this->createPaymentResponseFromError($exception);
}
return $this->createPaymentResponseFromError(new Exception('Unable to refund payment intent.'));
}
/**
* @inheritdoc
*/
public function createPaymentSource(BasePaymentForm $sourceData, int $customerId): PaymentSource
{
// Is Craft request the commerce/pay controller action?
$appRequest = Craft::$app->getRequest();
$isCommercePayRequest = $appRequest->getIsSiteRequest() && $appRequest->getIsActionRequest() && $appRequest->getActionSegments() == ['commerce', 'pay', 'index'];
if ($isCommercePayRequest) {
throw new PaymentSourceCreatedLaterException(Craft::t('commerce', 'The payment source should be created after successful payment.'));
}
/** @var PaymentIntentForm $sourceData */
try {
$lockName = "commerceTransaction:{$sourceData->paymentMethodId}";
if (!Craft::$app->getMutex()->acquire($lockName, 15)) {
throw new Exception("Unable to acquire mutex lock: $lockName");
}
$stripeCustomer = $this->getStripeCustomer($customerId);
$paymentMethod = $this->getStripeClient()->paymentMethods->retrieve($sourceData->paymentMethodId);
$paymentMethod = $paymentMethod->attach(['customer' => $stripeCustomer->id]);
switch ($paymentMethod->type) {
case 'card':
/** @var Card $card */
$card = $paymentMethod->card;
$description = Craft::t('commerce-stripe', '{cardType} ending in ••••{last4}', ['cardType' => StringHelper::upperCaseFirst($card->brand), 'last4' => $card->last4]);
break;
default:
if (isset($paymentMethod->{$paymentMethod->type}, $paymentMethod->{$paymentMethod->type}->last4)) {
$description = Craft::t('commerce-stripe', 'Payment method ending in ••••{last4}', ['last4' => $paymentMethod->{$paymentMethod->type}->last4]);
} else {
$description = $paymentMethod->type;
}
}
// Make it the default in Stripe if its the only one for this gateway
$existingPaymentSources = Commerce::getInstance()->getPaymentSources()->getAllPaymentSourcesByCustomerId($customerId, $this->id);
if (!$existingPaymentSources) {
$this->setPaymentSourceAsDefault($stripeCustomer->id, $paymentMethod->id);
}
$paymentSource = Plugin::getInstance()->getPaymentSources()->getPaymentSourceByTokenAndGatewayId($paymentMethod->id, $this->id);
if (!$paymentSource) {
$paymentSource = new PaymentSource();
}
$paymentSource->customerId = $customerId;
$paymentSource->gatewayId = $this->id;
$paymentSource->token = $paymentMethod->id;
$paymentSource->response = $paymentMethod->toJSON() ?? '';
$paymentSource->description = $description;
Craft::$app->getMutex()->release($lockName);
return $paymentSource;
} catch (Throwable $exception) {
Craft::$app->getMutex()->release($lockName);
throw new PaymentSourceException($exception->getMessage());
}
}
/**
* @inheritdoc
* @throws SubscriptionException if there was a problem subscribing to the plan
*/
public function subscribe(User $user, BasePlan $plan, BaseSubscriptionForm $parameters): SubscriptionResponseInterface
{
/** @var SubscriptionForm $parameters */
$customer = StripePlugin::getInstance()->getCustomers()->getCustomer($this->id, $user);
$stripeCustomer = $this->getStripeClient()->customers->retrieve($customer->reference);
$defaultPaymentMethod = $stripeCustomer['invoice_settings']['default_payment_method']
?? $stripeCustomer['default_source'] // backward compatible
?? null;
if (!$defaultPaymentMethod) {
throw new PaymentSourceException(Craft::t('commerce-stripe', 'No payment sources are saved to use for subscriptions.'));
}
$subscriptionParameters = [
'customer' => $customer->reference,
'items' => [['plan' => $plan->reference]],
];
if ($parameters->trialDays !== null) {
$subscriptionParameters['trial_period_days'] = (int)$parameters->trialDays;
} elseif ($parameters->trialEnd !== null) {
$subscriptionParameters['trial_end'] = (int)$parameters->trialEnd;
} else {
$subscriptionParameters['trial_from_plan'] = true;
}
$subscriptionParameters['expand'] = ['latest_invoice.payment_intent'];
$event = new SubscriptionRequestEvent([
'plan' => $plan,
'parameters' => $subscriptionParameters,
'user' => $user,
]);
$this->trigger(self::EVENT_BEFORE_SUBSCRIBE, $event);
try {
$subscription = $this->getStripeClient()->subscriptions->create($event->parameters);
} catch (Throwable $exception) {
Craft::warning($exception->getMessage(), 'stripe');
throw new SubscriptionException(Craft::t('commerce-stripe', 'Unable to subscribe. ' . $exception->getMessage()));
}
return $this->createSubscriptionResponse($subscription);
}
/**
* @inheritdoc
*/
public function deletePaymentSource($token): bool
{
$commercePaymentSource = Commerce::getInstance()->getPaymentSources()->getPaymentSourceByTokenAndGatewayId($token, $this->id);
try {
$paymentMethod = $this->getStripeClient()->paymentMethods->retrieve($token);
$paymentMethod->detach();
} catch (Throwable $throwable) {
// Assume already deleted.
}
if ($commercePaymentSource->getIsPrimary()) {
$paymentSources = Commerce::getInstance()->getPaymentSources()->getAllPaymentSourcesByCustomerId($commercePaymentSource->getCustomer()->id, $this->id);
foreach ($paymentSources as $source) {
// Set it to the first that is not the one being deleted
if ($source->token !== $token) {
Commerce::getInstance()->getCustomers()->savePrimaryPaymentSourceId($commercePaymentSource->getCustomer(), $source->id);
break;
}
}
}
return true;
}
/**
* @inheritdoc
*/
public function getBillingIssueResolveFormHtml(Subscription $subscription): string
{
$subscriptionData = $this->getExpandedSubscriptionData($subscription);
$intentData = $subscriptionData['latest_invoice']['payment_intent'];
if (in_array($subscriptionData['status'], ['incomplete', 'past_due', 'unpaid'])) {
$clientSecret = $intentData['client_secret'];
switch ($intentData['status']) {
case 'requires_payment_method':
case 'requires_confirmation':
return $this->getPaymentFormHtml(['clientSecret' => $clientSecret]);
case 'requires_action':
return $this->getPaymentFormHtml(['clientSecret' => $clientSecret, 'scenario' => 'requires_action']);
}
}
return '';
}
/**
* @param Transaction $transaction
* @param int $amount
* @param array $metadata
* @param bool $capture
* @param PaymentIntentForm $form
* @return PaymentIntent
* @throws \Stripe\Exception\ApiErrorException
* @throws \craft\commerce\stripe\errors\CustomerException
* @throws \yii\base\InvalidConfigException
*/
public function createPaymentIntent(Transaction $transaction, int $amount, array $metadata, bool $capture, PaymentIntentForm $form): PaymentIntent
{
// Base information for the payment intent
$paymentIntentData = [
'amount' => $amount,
'currency' => $transaction->paymentCurrency,
'confirm' => false,
'metadata' => $metadata,
'capture_method' => $capture ? 'automatic' : 'manual',
];
$paymentIntentData['automatic_payment_methods'] = ['enabled' => true];
// If we have a payment method ID use it
if ($form->paymentMethodId) {
$paymentIntentData['payment_method'] = $form->paymentMethodId;
}
// Add the receipt email if enabled
if ($this->sendReceiptEmail) {
$paymentIntentData['receipt_email'] = $transaction->getOrder()->getEmail();
}
// Add customer
if ($orderCustomer = $transaction->getOrder()->getCustomer()) {
// Will always create a customer in Stripe if none exists
$paymentIntentData['customer'] = StripePlugin::getInstance()->getCustomers()->getCustomer($this->id, $orderCustomer)->reference;
if ($form->savePaymentSource) {
$paymentIntentData['setup_future_usage'] = 'off_session';
}
}
$event = new BuildGatewayRequestEvent([
'type' => 'payment_intent',
'transaction' => $transaction,
'request' => $paymentIntentData,
]);
if ($this->hasEventHandlers(self::EVENT_BUILD_GATEWAY_REQUEST)) {
$this->trigger(self::EVENT_BUILD_GATEWAY_REQUEST, $event);
// Do not allow these to be modified by event handlers
$event->request['amount'] = $paymentIntentData['amount'];
$event->request['currency'] = $paymentIntentData['currency'];
}
return $this->getStripeClient()->paymentIntents->create($event->request);
}
/**
* @param Transaction $transaction
* @param int $amount
* @param array $metadata
* @param bool $capture
* @param ?User $user
* @return StripeCheckoutSession
* @throws \Stripe\Exception\ApiErrorException
* @throws \craft\commerce\stripe\errors\CustomerException
* @throws \craft\errors\SiteNotFoundException
* @throws \yii\base\InvalidConfigException
*/
public function createCheckoutSession(Transaction $transaction, int $amount, array $metadata, bool $capture, ?User $user): StripeCheckoutSession
{
$lineItems = [];
$lineItems[] = [
'price_data' => [
'currency' => $transaction->paymentCurrency,
'unit_amount' => $amount,
'tax_behavior' => 'unspecified',
'product_data' => [
'name' => Craft::$app->getSites()->getCurrentSite()->name . ' Order #' . $transaction->getOrder()->shortNumber,
'metadata' => [
'order_id' => $transaction->getOrder()->id,
'order_number' => $transaction->getOrder()->number,
'order_short_number' => $transaction->getOrder()->shortNumber,
],
],
],
'adjustable_quantity' => [
'enabled' => false,
],
'quantity' => 1,
];
$paymentIntentData = [
'capture_method' => $capture ? 'automatic' : 'manual',
];
$data = [
'cancel_url' => $transaction->getOrder()->cancelUrl,
'success_url' => UrlHelper::actionUrl('commerce/payments/complete-payment', ['commerceTransactionId' => $transaction->id, 'commerceTransactionHash' => $transaction->hash]),
'mode' => 'payment',
'client_reference_id' => $transaction->hash,
'line_items' => $lineItems,
'metadata' => $metadata,
'allow_promotion_codes' => false,
'payment_intent_data' => $paymentIntentData,
];
if ($orderCustomer = $transaction->getOrder()->getCustomer()) {
$data['customer'] = StripePlugin::getInstance()->getCustomers()->getCustomer($this->id, $orderCustomer)->reference;
} else {
$data['customer_email'] = $transaction->getOrder()->email;
}
$event = new BuildGatewayRequestEvent([
'transaction' => $transaction,
'type' => 'checkout.session',
'request' => $data,
]);
if ($this->hasEventHandlers(self::EVENT_BUILD_GATEWAY_REQUEST)) {
$this->trigger(self::EVENT_BUILD_GATEWAY_REQUEST, $event);
}
return $this->getStripeClient()->checkout->sessions->create($event->request);
}
/**
* @inheritdoc
*/
protected function authorizeOrPurchase(Transaction $transaction, PaymentIntentForm|BasePaymentForm $form, bool $capture = true): RequestResponseInterface
{
$currency = Commerce::getInstance()->getCurrencies()->getCurrencyByIso($transaction->paymentCurrency);
$user = Craft::$app->getUser()->getIdentity();
// This is the metadata that will be sent to Stripe for checkout and payment intents
$metadata = [
'order_id' => $transaction->getOrder()->id,
'order_number' => $transaction->getOrder()->number,
'order_short_number' => $transaction->getOrder()->shortNumber,
'transaction_id' => $transaction->id,
'transaction_reference' => $transaction->hash,
'description' => Craft::t('commerce-stripe', 'Order') . ' #' . $transaction->orderId,
];
$appRequest = Craft::$app->getRequest();
if (!$appRequest->getIsConsoleRequest()) {
$metadata['client_ip'] = $appRequest->getUserIP();
}
// Normalized amount for Stripe into minor units
$amount = (int) bcmul($transaction->paymentAmount, 10 ** $currency->minorUnit);
/** @var PaymentIntentForm $form */
if ($form->paymentFormType == self::PAYMENT_FORM_TYPE_CHECKOUT) {
$session = $this->createCheckoutSession($transaction, $amount, $metadata, $capture, $user);
return new CheckoutSessionResponse($session->toArray());
}
/**
* The previous version of the Stripe plugin accepted a payment method ID on initial
* payment intent creation. We can attach it to the payment intent
* before creating it, and we will immediately confirm it later in this function to match the previous behavior.
*/
$immediatelyConfirmLegacy = false;
if ($form->paymentMethodId) {
$immediatelyConfirmLegacy = true;
}
$paymentIntent = $this->createPaymentIntent($transaction, $amount, $metadata, $capture, $form);
if ($immediatelyConfirmLegacy) {
// Mutates the payment intent that has been confirmed
$this->_confirmPaymentIntent($paymentIntent, $transaction);
}
return new PaymentIntentResponse($paymentIntent->toArray());
}
/**
* Confirm a payment intent and set the return URL.
*
* @param PaymentIntent $stripePaymentIntent
* @param Transaction $transaction
* @throws \Stripe\Exception\ApiErrorException
*/
private function _confirmPaymentIntent(PaymentIntent $stripePaymentIntent, Transaction $transaction, ?string $returnUrl = null): void
{
// The URL to redirect your customer back to after they authenticate or cancel their payment on the payment method’s app or site.
// If you’d prefer to redirect to a mobile application, you can alternatively supply an application URI scheme.
// This parameter can only be used with confirm=true.
// https://stripe.com/docs/api/payment_intents/create#create_payment_intent-return_url
$defaultReturnUrl = UrlHelper::actionUrl('commerce/payments/complete-payment', ['commerceTransactionId' => $transaction->id, 'commerceTransactionHash' => $transaction->hash]);
$returnUrl = $returnUrl ?? $defaultReturnUrl;
$parameters = [
'return_url' => $returnUrl,
];
$event = new PaymentIntentConfirmationEvent([
'parameters' => $parameters,
]);
$this->trigger(self::EVENT_BEFORE_CONFIRM_PAYMENT_INTENT, $event);
$stripePaymentIntent->confirm($event->parameters);
}
/**
* @inheritdoc
*/
public function supportsPaymentSources(): bool
{
return parent::supportsPaymentSources();
}
/**
* @inheritdoc
*/
public function getBillingPortalUrl(User $user, ?string $returnUrl = null, string $configurationId = null): string
{
if (!$returnUrl) {
$returnUrl = Craft::$app->getRequest()->pathInfo;
}
$customer = StripePlugin::getInstance()->getCustomers()->getCustomer($this->id, $user);
$params = [
'customer' => $customer->reference,
'return_url' => UrlHelper::siteUrl($returnUrl),
];
if ($configurationId) {
$params['configuration'] = $configurationId;
}
$session = $this->getStripeClient()->billingPortal->sessions->create($params);
return $session->url . '?customer_id=' . $customer->reference;
}
}