0

I would like to know if it is possible to capture payments by subscribing to order transition events.

Example:

  1. Transaction mode: Authorize only
  2. On order placed - Capture some amount (application fee)
  3. On order validated - Capture outstanding amount

Thank you!

1 Answer 1

0

I've managed to create new payment and modify authorisation amount. Here is what I have so far:

public static function getSubscribedEvents() {
  $events = ['commerce_order.place.post_transition' => ['captureFee', -50]];
  return $events;
}

public function captureFee(WorkflowTransitionEvent $event) {
  /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
  $order = $event->getEntity();

  if ($order->bundle() != 'training') {
    return;
  }

  /** @var \Drupal\commerce_payment\Entity\PaymentGatewayInterface $payment_gateway */
  $payment_gateway = $order->payment_gateway->entity;
  $payment_gateway_plugin = $payment_gateway->getPlugin();

  $payment_storage = $this->entityTypeManager->getStorage('commerce_payment');

  // Load first order payment
  $payments = $payment_storage->loadMultipleByOrder($order);
  $first_payment = current($payments);

  // Only proceed if payment is not captured
  if ($first_payment->isCompleted()) {
    return;
  }

  // Default fee amount
  $fee_amount = new \Drupal\commerce_price\Price('50.00', 'USD');

  // Get fee amount from product variation
  if (isset($order->getItems()[0]->getPurchasedEntity()->field_app_fee) && !$order->getItems()[0]->getPurchasedEntity()->field_app_fee->isEmpty()) {
    $fee_amount = $order->getItems()[0]->getPurchasedEntity()->field_app_fee->first()->toPrice();
  }

  // Create fee payment
  /** @var \Drupal\commerce_payment\Entity\PaymentInterface $payment */
  $payment = $payment_storage->create([
    'state' => 'new',
    'amount' => $fee_amount,
    'payment_gateway' => $payment_gateway->id(),
    'order_id' => $order->id(),
  ]);

  // Capture fee payment
  if ($payment_gateway_plugin instanceof OnsitePaymentGatewayInterface) {
    $payment->payment_method = $order->payment_method->entity;
    $payment_gateway_plugin->createPayment($payment, 'capture');
  }
  elseif ($payment_gateway_plugin instanceof ManualPaymentGatewayInterface) {
    $payment_gateway_plugin->createPayment($payment, TRUE);
  }
  else {
    return;
  }

  // Subtract captured amount from authorized amount and save first payment
  $first_payment_amount = $first_payment->getAmount();
  $first_payment->setAmount($first_payment_amount->subtract($fee_amount));
  $first_payment->save();

}

I have "training" bundle that is limited to 1 item per cart. This is the result with variation price set to $2,100.00 and $45.00 fee.

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.