3

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?

3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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