OrderPaymentIntentSubscriber.php in Commerce Stripe 8
File
src/EventSubscriber/OrderPaymentIntentSubscriber.php
View source
<?php
namespace Drupal\commerce_stripe\EventSubscriber;
use Drupal\commerce_order\Event\OrderEvent;
use Drupal\commerce_order\Event\OrderEvents;
use Drupal\commerce_payment\Entity\PaymentGatewayInterface;
use Drupal\commerce_price\Calculator;
use Drupal\commerce_price\Price;
use Drupal\commerce_stripe\Plugin\Commerce\PaymentGateway\StripeInterface;
use Drupal\Core\DestructableInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Stripe\Exception\ApiErrorException as StripeError;
use Stripe\PaymentIntent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class OrderPaymentIntentSubscriber implements EventSubscriberInterface, DestructableInterface {
protected $entityTypeManager;
protected $updateList = [];
public function __construct(EntityTypeManagerInterface $entity_type_manager) {
$this->entityTypeManager = $entity_type_manager;
}
public static function getSubscribedEvents() {
return [
OrderEvents::ORDER_UPDATE => 'onOrderUpdate',
];
}
public function destruct() {
foreach ($this->updateList as $intent_id => $amount) {
try {
$intent = PaymentIntent::retrieve($intent_id);
if (in_array($intent->status, [
PaymentIntent::STATUS_REQUIRES_PAYMENT_METHOD,
PaymentIntent::STATUS_REQUIRES_CONFIRMATION,
], TRUE)) {
PaymentIntent::update($intent_id, [
'amount' => $amount,
]);
}
} catch (StripeError $e) {
}
}
}
public function onOrderUpdate(OrderEvent $event) {
$order = $event
->getOrder();
$gateway = $order
->get('payment_gateway');
if ($gateway
->isEmpty() || !$gateway->entity instanceof PaymentGatewayInterface) {
return;
}
$plugin = $gateway->entity
->getPlugin();
if (!$plugin instanceof StripeInterface) {
return;
}
$intent_id = $order
->getData('stripe_intent');
if ($intent_id === NULL) {
return;
}
$total_price = $order
->getTotalPrice();
if ($total_price !== NULL) {
$amount = $this
->toMinorUnits($order
->getTotalPrice());
$this->updateList[$intent_id] = $amount;
}
}
protected function toMinorUnits(Price $amount) {
$currency_storage = $this->entityTypeManager
->getStorage('commerce_currency');
$currency = $currency_storage
->load($amount
->getCurrencyCode());
$fraction_digits = $currency
->getFractionDigits();
$number = $amount
->getNumber();
if ($fraction_digits > 0) {
$number = Calculator::multiply($number, pow(10, $fraction_digits));
}
return round($number, 0);
}
}