Magento - getting data from an order or invoice - magento

I'm trying to write a Magento (CE 1.4) extension to export order data once an order has been paid for. I’ve set up an observer that hooks in to the sales_order_invoice_save_after event, and that is working properly - my function gets executed when an invoice is generated. But I’m having trouble getting information about the order, such as the shipping address, billing address, items ordered, order total, etc.
This is my attempt:
class Lightbulb_Blastramp_Model_Observer {
public function sendOrderToBlastramp(Varien_Event_Observer $observer) {
$invoice = $observer->getEvent()->getInvoice();
$order = $invoice->getOrder();
$shipping_address = $order->getShippingAddress();
$billing_address = $order->getBillingAddress();
$items = $invoice->getAllItems();
$total = $invoice->getGrandTotal();
return $this;
}
}
I tried doing a print_r on all those variables, and ended up getting a lot of data back. Could someone point me in the right direction of getting the shipping address of an order?
Thanks!

Many Magento objects are based on Varien_Object, which has a method called getData() to get just the usually interesting data of the object (excluding the tons of other, but mostly useless data).
With your code you could either go for all the data at once:
$shipping_address = $order->getShippingAddress();
var_dump($shipping_address->getData());
or directly for specific single properties like this:
$shipping_address = $order->getShippingAddress();
var_dump(
$shipping_address->getFirstname(),
$shipping_address->getLastname(),
$shipping_address->getCity()
);
To understand how this works, I'd recommend to make yourself more familiar with the Varien_Object and read a bit about PHPs magic methods, like __call(), __get() and __set().

Try print_r($shipping_address->toArray());

Related

Magento: catching a placed order, but the transaction id is empty

I want to catch all placed order with an observer to use the data in a further process.
In my Observer I wrote:
class Custom_CrmApi_Model_Observer extends Varien_Object {
….
public function placeOrder( $observer ){
$order = $observer->getOrder();
$payment = $order->getPayment();
$transId = $order->getPayment()->getTransactionId();
//$transId = $order->getPayment()->getLastTransId();
....
But the transaction ID of all ebay orders is empty (but not in the backend). I am using the M2E extension for ebay integration. But that shouldn’t be the problem, because the observer catch any placed order, or? At this time the transaction Id supposed to be available. But for some reason it isn’t available.
Any ideas? Perhaps a work around?
Thank you so much in advanced,
Hannes
It may be too late for you but maybe works for someone else.
I used this code to get the Transaction id for my report. It is on a different place then the normal ones for m2epro orders.
$additional_data = $order->getPayment()->getData();
//print_r($additional_data['additional_data']);
$component_mode = $additional_data['additional_data'];
additional_data in payment gives you the information about the transaction.
I am getting channel, payment, channel_order_id, channel_final_fee, transaction_id, fee, sum and transaction_date from aditional_data of the order. It is possible to get the same data from the same place on placeOrder function in m2epro.
app\code\community\Ess\M2ePro\Model\Magento\Order.php -> placeOrder
if (version_compare(Mage::helper('M2ePro/Magento')->getVersion(false), '1.4.1', '>=')) {
/** #var $service Mage_Sales_Model_Service_Quote */
$service = Mage::getModel('sales/service_quote', $this->quote);
$service->submitAll();
// You can get this order before you return it and get the data maybe!
return $service->getOrder();
}
Worths to try.
Cheers

Get Magento defined values for model "sales/order" status

I'm trying to perform some operations on an order if its status/state is "processing" (not sure if I should use status or state here .. any help on this would be great too).
Running a ->getStatus() on a sales/order model tells me the value I'm looking for is "processing", but I don't want to compare this to a string literal. I would like to compare it to the Magento defined value, so I'm wondering how it determines this value "processing" and how can I do the same?
Here is some code..
$order = Mage::getModel('sales/order')->loadByIncrementId($orderID);
if($order->getStatus() == "processing") {
//do stuff
}
I would like to change "processing" to something like Mage::getModel('sales/order')->STATUS_PROCESSING
I'm sure the answer lies somewhere in the Mage_Sales_Model_Order::getStatus() method, but I'm having a very hard time locating that method. I've even used ReflectionClass to view the methods and do not see it!
The following code will go off of the Magento status code:
$orders = Mage::getModel('sales/order')->getCollection()
->addFieldToFilter('status', 'Processing')
;
foreach ($orders as $order) {
//do stuff
}
I hope that is what you are looking for.

Magento returning incorrect customer data on frontend pages

isn't this the right method to get Name of logged in customer?
<?php echo Mage::helper('customer')->getCustomer()->getName(); ?>
I have a website with live chat functionality. Yesterday I have been asked to pass email address and the name of the logged into the user into the Javascript Tracking variable code placed in the head section of the website. So that the operators could see who is on the website and whom are they talking to without any need to ask about their information.
So I passed the information from Magento into the Javascript code but now I see this very strange thing happening. For example,
If I am logged in with credentials Name = John Email =
john12#yahoo.com
Then This name and email variable values are changing with the change of pages. For example if I click on any product page the variable values which I am passing changes to some other user's information.
Name becomes Ricky Email becomes ricky23#gmail.com
this variable values are kept on changing back to john and from john to something else with the change of pages. So operator does not have any idea whom are they talking because the values are kept on changing. Also, user ricky or who ever it changes to also exist in the database. so it is picking up random person from the database.
This is what i did to pass the code to javascript. Please let me know if that is not the right code to pass the information. Please check the php code I am using to fetch information from Magento. Roughly, I receive incorrect value once in 5 times. Please provide some assistance. Thanks in advance.
<?php
$customer = Mage::getSingleton('customer/session')->getCustomer();
$email = $customer->getEmail();
$firstname = $customer->getFirstname();
$lastname= $customer->getLastname();
$name = $firstname . ' ' . $lastname;
?>
<script type="text/javascript">
if (typeof(lpMTagConfig) == "undefined"){ lpMTagConfig = {};}
if (typeof(lpMTagConfig.visitorVar) == "undefined"){ lpMTagConfig.visitorVar = [];}
lpMTagConfig.visitorVar[lpMTagConfig.visitorVar.length] = 'Email=<?php echo $email; ?>';
lpMTagConfig.visitorVar[lpMTagConfig.visitorVar.length] = 'Name=<?php echo $name; ?>';
</script>
I'm also attaching a snap shot
I'd be interested to hear how you're adding this code to the page? Is it in it's own block, or are you adding it to footer.phtml, or similar? If your adding to an existing block be sure to check the block caching settings of that template.
To confirm the caching hypothesis I'd ask the following:
Do you get the same name, all the time, on the same page? When you refresh the page, do you get the same name and email in the Javascript?
Does the problem persist with caching disabled?
This doesn't sound like a singleton problem at all. Each execution of the PHP script is isolated from the others, serving one page request. There's no chance of another customer's object moving between invokations of the script.
It is a matter of understanding the singleton pattern. If you call your code twice:
$customer_1 = Mage::helper('customer')->getCustomer()->getName();
$customer_2 = Mage::helper('customer')->getCustomer()->getName();
you get two different instances of the object. But... if one of them has already implemented a singleton pattern in its constructor or has implemented a singleton getInstance then both objects will actually point to the same thing.
Looking at the customer/helper/Data.php code you can see the function
public function getCustomer()
{
if (empty($this->_customer)) {
$this->_customer = Mage::getSingleton('customer/session')->getCustomer();
}
return $this->_customer;
}
That means that in one of the cases singleton is already implemented/called and in other one - not as the property is already set.
The correct way to work with quote/customer/cart in order to get always the correct data is always to use the singleton pattern.
So using this:
$customer = Mage::getSingleton('customer/session')->getCustomer();
always guarantee that you get the correct customer in that session. And as may be you know singleton pattern is based on registry pattern in app/Mage.php:
public static function getSingleton($modelClass='', array $arguments=array())
{
$registryKey = '_singleton/'.$modelClass;
if (!self::registry($registryKey)) {
self::register($registryKey, self::getModel($modelClass, $arguments));
}
return self::registry($registryKey);
}
and looking at app/Mage.php:
public static function register($key, $value, $graceful = false)
{
if (isset(self::$_registry[$key])) {
if ($graceful) {
return;
}
self::throwException('Mage registry key "'.$key.'" already exists');
}
self::$_registry[$key] = $value;
}
...
public static function registry($key)
{
if (isset(self::$_registry[$key])) {
return self::$_registry[$key];
}
return null;
}
you can see that Magento checks is it is already set. If so, Magento will either throw an Exception, which is the default behavior or return null.
Hope this will help you to understand the issue you face.
I have sorted this out. I have moved the code from footer.phtml to head.phtml and it's working fine now.Values are not changing anymore. If anyone know the logic behind please post and I will change my answer. So far this is working.

Magento Record Amount of Money Used on Coupon Code

I am well aware of finding out the number of times a coupon code was used (salesrule/coupon model). However, I would like to know how to intercept the use of a coupon and record its grand total in a table.
I have tried to do this by overriding the successAction() method of the Mage_Checkout_OnepageController, however if I try to get the coupon code with
$couponCode = (string) Mage::getSingleton('checkout/cart')->getQuote()->getCouponCode();
$couponCode turns out to be a blank string. It would seem that, by the time the successAction is called, the checkout/cart singleton has already been emptied. How can I intercept the 'place order' button and still be able to get the coupon code the customer used?
All help is greatly appreciated and I always accept an answer!
Upon entry of the successAction the _quote property of the checkout/cart object is already nullified.
However, you still can get your data upon entry of the successAction by using:
$oOrder = Mage::getModel('sales/order')
->load($this->getOnePage()->getCheckout()->getLastOrderId());
var_dump(
$oOrder->getCouponCode(),
$oOrder->getDiscountAmount(),
$oOrder->getGrandTotal()
);
But I'd recommend to create an observer for the checkout_onepage_controller_success_action event instead. This way you don't have to override anything at all. And usually nothing to maintain when it comes to Magento upgrades.
The code of such observer would look similiar like this:
/**
* checkout_onepage_controller_success_action event observer
*
* #param object $oObserver
* #return null
*/
public function checkoutOnepageControllerSuccessAction($oObserver)
{
$aOrderId = $oObserver->getOrderIds();
foreach ($aOrder as $iOrderId) {
$oOrder = Mage::getModel('sales/order')->load($iOrderId);
var_dump(
$oOrder->getCouponCode(),
$oOrder->getDiscountAmount(),
$oOrder->getGrandTotal()
);
}
}

Magento Programmatically Edit Order Payment

I need to make a change of payment method to an order after it is placed. I have the order ID ($orderID), the order object ($order), a proper payment object, etc.
$service->retrievePaymentType() Returns the payment in the form of Mage_Sales_Model_Order_Payment
All of this happens in an extension of Mage_Checkout_Model_Type_Onepage
Does anybody know how I would go about doing this?
$order = Mage::getModel('sales/order')->load($orderID);
$service = Mage::getModel('sales/service_quote', $this->getQuote());
// Update Saved Order Payment Method
// $order->getPaymentsCollection()->clear();
$order->setPayment($service->retrievePaymentType());
$order->getPaymentsCollection()->save();
$order->save();
Thanks in advance!
Unfortunately, I had to do a direct SQL query, which is not Magento spec, but it gets the job done. If someone want's the code, leave me a comment, and I will dig it up.
Thanks though!
EDIT:
I managed to in fact get this working with Magento API:
// The payment type I want to change the target order to
$service = Mage::getModel('sales/service_quote', $this->getQuote());
$payment = $service->retrievePaymentType();
$paymentData = $payment->getData();
$oldPayment = $order->getAllPayments();
$oldPayment = $oldPayment[0];
foreach ($paymentData as $n => $v) {
$oldPayment->setData($n,$v);
}
It is a little bit hackish, but pretty effective.

Resources