5

I'm trying to do some different processing after an order is placed depending on which payment method a customer uses.

In my EventSubscriber, I have the following code:

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

  public function onPlaceTransition(WorkflowTransitionEvent $event) {
    $order = $event->getEntity();

Now I want to get the name or id of the payment method that was used from the order, but when I used kint($order) I couldn't find a way to access the payment method.

How do I access the payment method given an $order object?

2 Answers 2

10

The Commerce Payment module adds the payment_method base field when it is enabled, see commerce_payment_entity_base_field_info https://github.com/drupalcommerce/commerce/blob/8.x-2.x/modules/payment/commerce_payment.module#L28

You can access the payment method (and gateway) through

$order->get('payment_method')->first()->entity
$order->get('payment_gateway')->first()->entity

Example of when we get the payment method label for the order receipt email.

if (!$order->get('payment_method')->isEmpty()) {
  $variables['payment_method'] = [
    '#markup' => $order->get('payment_method')->first()->entity->label(),
  ];
}

From https://github.com/drupalcommerce/commerce/blob/77b25bf4889a940eed6652475c3952c36144efc0/modules/payment/commerce_payment.module#L122

1

It looks like it changed at some point after 2018. I could only get the label in this way (for my offsite payment method):

use Drupal\commerce_payment\Entity\PaymentGateway;

/** @var PaymentGateway $paymentGateway */
$paymentGateway = $order->get('payment_gateway')->entity;

$label = $paymentGateway->getPluginConfiguration()['display_label'];

$order->get('payment_method') was empty for my orders, but according to the code, payment methods are only set, if they are stored payment methods of the customer.

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.