1

I have a plugin that is listening to the onOrderComplete event within commerce. I am able to get the email address like this:

craft()->on('commerce_orders.onOrderComplete', function (Event $event) {
    $event->params['order']->email;  // name@email.com

});

I can see the Id in the log, but since I'm in the order class, I'm not sure how to get to it. I can see customerId:

$event->params['order']->customerId; // 3

But I've noticed the customerId and the userId are different. I need to be able to get the logged in userId vs. the customerId

When I try getting just the id, I get the product id back (Which is what I would expect).

$event->params['order']->id;  // 123

To relate to the twig side it would be something like this (obviously won't work):

$event->params['order']['currentUser']->id;  // 12

Here is a part of the log:

...
[_attributes:Craft\BaseModel:private] => Array
(
    [enabled] => 1
    [archived] => 0
    [locale] => en_us
    [localeEnabled] => 1
    [itemTotal] => 375
    [baseDiscount] => 0
    [baseShippingCost] => 0
    [totalPrice] => 375
    [totalPaid] => 375.00
    [billingAddressId] => 122
    [shippingAddressId] => 123
    [paymentMethodId] => 1
    [customerId] => 3
    [id] => 12   //  <-- This guy right here
    [orderStatusId] => 1
...
  • Are all of your orders going to be with logged in users or do you have a guest checkout workflow? – Brad Bell Dec 11 '15 at 2:13
  • They will always be logged in. You must have an account on my site in order to purchase a product. – Damon Dec 11 '15 at 2:49
  • Unless I'm missing something isn't currentUser what you're looking for? – Brad Bell Dec 11 '15 at 2:51
4

Since this is happening from the onOrderComplete event, the easiest way to get the currently logged in user is with UserSessionService::getUser():

$user = craft()->userSession->getUser();

Alternatively, if you want to go through the actual Commerce_OrderModel that was passed as a parameter on the event, you can do this:

$user = $event->params['order']->getCustomer()->getUser();

Either way, it’s a good idea to verify that $user gets set to something, just in case:

if ($user) {
    // ...
}
| improve this answer | |

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.