Magento event always dispatched when order is placed successfully? - magento

I'm finding Magento event dispatching is quite a frustrating area. I suppose a lot of that frustration is, as usual, down to the lack of documentation.
I would like my code to be triggered at various stages as a visitor traverses through a site. So I put some debug in Mage::dispatchEvent, and I walked through the site to see what events are fired at each stage. There are a lot!
Two places I am interested in are:
when the visitor had selected a billing address and moved on to the next stage of the checkout process.
when a user successfully places an order
For the billing address one, the events that I saw being fired that look relevant are:
controller_action_predispatch_checkout_onepage_saveBilling
controller_action_postdispatch_checkout_onepage_saveBilling
The 'pre' and 'post' suggested to me that there is actually a 'checkout_onepage_saveBilling' event, but there isn't, so my first question is why the 'pre' and 'post'?
For the successful order, the events that look good are:
checkout_onepage_controller_success_action
checkout_multishipping_controller_success_action
My second question is will these events be fired for all payment methods? For example, if using Google Checkout, or PayPal (standard redirect), will the event fire, and at what point? When returning to the site from PayPal? If so that would beg the question what if the user does not return after completing payment.
Thanks for any help.

Sadly, I've noticed that checkout_submit_all_after does not fire for Paypal Express orders.
Short of modifying the Paypal models to add this (or perhaps hooking into events they may fire - I haven't checked on that yet), I think checkout_onepage_controller_success_action may really be the only event you can absolutely count on for every type of order.

The predispatch event will fire before the action has been called, the postdispatch event will fire after the action has been completed. So if you need to know what the result of the action was, you should use the postdispatch event.
For successful orders, checkout the checkout_submit_all_after event.
If you haven't seen it, https://www.nicksays.co.uk/magento-events-cheat-sheet-1-9/, is a handy reference for Magento events.

Related

DDD and EventSourcing how to detect redundant events in design

We are developing our application with help of EventSourcing. Let's imagine we have an Aggregate "InvestorAccount" - holds information about Investor's portfolio (stocks).
We have 2 options which events should we have:
InvestorAccountCreated event
SharesBought event
SharesSold event
or
SharesBought event
SharesSold event
We are not sure we need InvestorAccountCreated event. We can use just SharesBought as a first initial event. The idea is - when investor bought shares - we automatically create account for him. Right now it's doesn't make sense to have empty Invetor's account (with out shares) and we don't see bebefits of having InvestorAccountCreated event, but may be we still should have it, because it will be useful in the future?
Do we need to to have InvestorAccountCreated ? And why?
The short answer is (as nearly always in DDD): it depends.
If there's no concept in the domain of an investor account which has never owned a share, then it's probably not a great idea to have an InvestorAccountCreated event, because that makes the state of an investor account which has never owned a share derivable from persisted events and forces a runtime validation that no InvestorAccountCreated event is issued without immediately (or even better atomically) issuing a SharesBought event.
That said, by not having an InvestorAccountCreated event, you are making it more difficult if it turns out that, actually, the domain needs to model an investor account that hasn't bought a share. The event can be added, but you've given up the ability to guarantee that for every investor account there's exactly one InvestorAccountCreated (and thus, for instance, you can't count the number of investor accounts by counting the InvestorAccountCreated events).

how to do mixpanel.people.increment in Segment

I'm using Segment and have Mixpanel enabled. I used to track our user's life time revenue like this:
mixpanel.people.increment('Lifetime Revenue', 21.99);
The question is how do I do this in Segment?
Looked everywhere, it seems like they do have increment setting under advanced setting. However, I still don't know how to fire those events/trackers.
Thanks!
I too was wondering on how to do this, based on Mixpanel's article (https://mixpanel.com/blog/2014/07/21/revenue-best-practices). I did a lot of back and forth with Segment's tech support, and after a couple of days of repeatedly telling them to read the article, they finally got me to an engineer who actually read it, and was able to answer my question about this as well. Here's his answer:
It looks like a few things need to happen for this lifetime revenue value to be tracked.
First, track_charge needs to be called. Fortunately we're already firing a track_charge call when revenue is passed as a trait in track calls. You can see where that happens in the code here.
Secondly, a the people.increment() needs to be called. We also fire this on the page as you can see here, but it doesn't look like we currently have a way to pass through the revenue in that people.increment call.
Looks like your best bet here would be to fire off the increment and set calls directly. As you may know, we're loading the Mixpanel library on the page so all you have to do is execute the calls within an analytics.ready() method. Doing so ensures that the native calls only fire when the Mixpanel library has properly loaded on the page.
For reference, here are the calls you'd want to place within the ready() method.
mixpanel.people.increment("Lifetime Value", 27);
mixpanel.people.set("Last Item Purchase", new Date.toISOString());
To increment events, log into your account at Segment.com, select the Mixpanel integration, then select "Advanced Options". Within "Advanced Options", there's a text field labeled "Events to Increment in People" where you can specify events you'd like to be incremented.

How to fire an event on payment received in magento?

Im using one page checkout and I need to pass few information after payment has been successfully made. I have used sales_order_payment_pay, checkout_type_onepage_save_order_after, sales_order_payment_place_end & checkout_onepage_controller_success_action events. But these events are triggered as soon as clicking on place order. Even if the payment is failure also its triggering that event. I need to pass information only on successful payment.
sales_order_payment_place_end should be good enough. Just add whatever logic you need to use. You can grab the $payment from the $observer and the $order from the $payment
Try looking into $payment->getAmountAuthorized If the payment succeeded this should be greater then 0.
EDIT: $observer->getEvent()->getPayment(); (should work)
Normally the Status of an Order changes After Payment notification. You can watch for Status change have a Look at:
http://www.cartware.de/blog/detail/article/kein-magento-event-fuer-statusaenderung/
Its written in german Language but by watching the Code you may get the clue

Why use event listeners over function calls?

I've been studying event listeners lately and I think I've finally gotten them down. Basically, they are functions that are called on another object's method. My question is, why create an event listener when calling the function will work just fine?
Example, I want to call player.display_health(), and when this is fired, the method player.get_health() should be fired and stored so that display_health() has access to it. Why should I use an event listener over simply calling the function? Even if display_health() were in another object, this still doesn't appear to be a problem to me.
If you have another example that fits the usage better, please let me know. Perhaps particular languages don't benefit from it as much? (Javascript, PHP, ASP?)
You might not always be in control of the code that's doing the calling. Or even if you are, you don't want to introduce dependencies into that code. In cases like that, it's better for the code to fire an event and allow the code you do control, or the code that should have the dependency, to listen for the event and act accordingly.
For example, perhaps you're creating a library that will be used by other people. They don't have the source code or in some way can't/shouldn't be able to modify it (or shouldn't have to). Your documentation states that specific events are raised under specific circumstances. They can then, in turn, respond to those events.
Or perhaps you have some domain libraries in your enterprise. You do control them and can modify them, but architecturally they're generally considered to be working as they currently are coded and shouldn't be changed. (Don't want to incur a round of QA to re-validate the updated code, the code belongs to another department and they don't want you to change it, etc.) And you're in the position where you want that code to be able to do different things in different circumstances/environments. If that code raises and event where relevant, you can hook your code into it (and/or swap out accordingly) without having to mess with that code.
Just a couple quick examples, I'm sure others have more.
My question is, why create an event listener when calling the function will work just fine?
What if you don't know what function you want to call?
Take the classic example, a Button that the user can click on. Whoever writes the library has no idea what function you want called when the button is clicked. It would also be pretty prohibitive if every Button could only call the same function when it is clicked.
So instead, you can attach an event handler to the event. Then when the event is triggered, the Button can do what it needs to, without having to know at compile-time exactly what function it's supposed to be calling.
In Brief, you can write the code without event listener, but using event listener help other to use the same code as library.
Even with the detailed answers above, I was still having trouble understanding what the actual difference was between using a controller / functions OR an event listener.
One of the things that has been left out in all of these answers is that the use of Events and Event Listeners comes in handy when you do not want to couple your code so closely. Each function, class, etc, should have singleness of purpose.
So say you are getting hit with an API request from an outsider. In my case, my exact problem understanding this concept was when I am receiving API calls from Stripe Webhooks.
The purpose of Stripe Webhooks is: say a customer spends $10,000 on your website. Your standard procedure is to Auth and Capture. Update DB to reflect their new membership status. In a perfect world, and in our company's case, 999/1000 times, this goes perfectly. Either their card is declined on the spot, or the payment goes through. In both cases, we send them an email letting them know.
But what about the 1/1000 time when the user pays and Stripe returns a Card Failure error (which can be a number of different things)? In our case, we email them and tell them the billing has failed. The problem we've encountered is that some BANKS are investigating large charges, which comes back as an Error, but then a few minutes later the bank authorizes the charges and the payment is captured.
So what is there to do? Enter Stripe Webhooks. Stripe Webhooks will hit an API endpoint if something like this occurs. Actually, Stripe Webhooks can hit your API any and every time a payment isn't instantly Authed, Captured, or if the customer asks for a refund.
This is where an Event Listener comes in handy. Stripe shoots over a POST with the customer info, as well as the Webhook type. We will now process that, update the database, and shoot them a success email.
But why not just use a standard route and controller?
The reason we don't just use a standard route and controller is because we would either need to modify the already defined functions, classes, etc, or create a new series of classes that are coupled together, such as -> Stripe API Calls Received, Update DB, Send Email. Instead of coupling these closely together, we use an Event Listener to first accept the API Call, then hit each of those Classes, Functions, etc., leaving everything uncoupled.
I looked everywhere, and I think the Laravel documentation explains it best. I finally understood when given a concrete example, and what the purpose of an Event Listener is:
Events serve as a great way to decouple various aspects of your application, since a single event can have multiple listeners that do not depend on each other. For example, you may wish to send a Slack notification to your user each time an order has shipped. Instead of coupling your order processing code to your Slack notification code, you can raise an OrderShipped event, which a listener can receive and transform into a Slack notification.
https://laravel.com/docs/5.6/events
I think the main reason for events vs function calls is that events are 'listened to' while calls are 'made'. So a function call is always made to another object whereas listeners 'choose' to listen for an event to be broadcast from your object.
The observer pattern is a good study for this capability. Here is a brief node.js example which illustrates the concept:
var events = require('events');
var Person = function(pname) {
var name = pname;
};
var james = new Person('james');
var mary = new Person('mary');
var loudmouth = new Person('blabberer');
loudmouth.mouth = new events.EventEmitter();
//jame's observer.
james.read_lips = function(msg){
console.log("james found out: " + msg);
};
//james adds his event to the emitter's event listener.
james.enter_elevator = function(){
console.log('james is in the elevator');
//NOTE: james adds HIMSELF as a listener for the events that may
//transpire while he is in the elevator.
loudmouth.mouth.on('elevator gossip', james.read_lips)
};
//james removes his event from the emitter when he leaves the elevator.
james.leave_elevator = function(){
// read lips is how james responds to the event.
loudmouth.mouth.removeListener('elevator gossip', james.read_lips);
console.log('james has left the elevator');
};
//mary's observer
mary.overhear = function(msg){
console.log("mary heard: " + msg);
};
//mary adds her observer event to the emitter's event listeners
mary.enter_elevator = function(){
// overhear is how mary responds to the event.
console.log('mary is in the elevator');
//NOTE: now mary adds HERSELF to the listeners in the elevator and
//she observes using a different method than james which suits her.
loudmouth.mouth.on('elevator gossip', mary.overhear);
};
loudmouth.speaks = function(what_is_said){
console.log('loudmouth: ' + what_is_said);
this.mouth.emit('elevator gossip', what_is_said);
};
james.enter_elevator();
mary.enter_elevator();
loudmouth.speaks('boss is having an affair');
james.leave_elevator();
loudmouth.speaks('just kidding');
console.log('james did not hear the last line because he was not listening anymore =)');
so in this 'story' the actors choose to listen or when to not listen for events from a third party. I hope this helps.

Naming an event: describe what just happened or describe what is about to happen? And why?

Note: I'm not talking about the names of event handlers. I'm talking about the names of the events themselves.
I tend to name events such that they describe what happened just before the event was raised. Adjectives tend to dominate this convention (CLICKED, SAVED, CHANGED, LOADED, etc).
Some competent peers have recently exposed me to the idea of naming events to describe what's about to happen (in response to the event). Verbs tend to dominate here (SAVE_DATA, GET_MEMBER, LOAD_RESULTS, SHOW_REPORT -- again, these are the names of events, not handlers or methods called from them).
I've decided the latter works well enough when you're in charge of both the event and the handler, and especially when there will only ever be one response you'll ever want to that event. Conversely, you can't very well name the event to match the verb (handler) that will follow if you don't have visibility to or control over it.
How do you name events, and why? Should one convention be enough (in a given shop, at the very least), or is it wiser to changed based on the size and scope of the code/project?
"Saving" for before event gets fired, and "Saved" after event happened.
Framework Design Guidelines suggest the following scheme:
Event Naming Guidelines
I name my events in the first way you described. This is because I want my handler to decide what to do with the event.
I think there are two things in interaction here:
Event - what has happened
Action - what you are going to do
Naming event by how you are going to react is a BAD IDEA. Name event by what has happened. Otherwise it will confuse people. If the reaction changes in the future and the name of event stays the same, it will perplex developers.
Example:
Event: Click(ed)
Action: LoadProducts
If you were to name the event "ToLoadProducts", then change your action to "DisplayFilterForm" and forget to update the event, it will look like:
Event: ToLoadProducts
Action: DisplayFilterForm
It's clear it looks strange and untidy, as though somebody dropped the work in the middle.

Resources