Get magento shipping amount from each ordered item - php

I am trying to get shipping and handling amount. I was trying the snippet code below but it's not working. I am successfully sending some data to third party API after the place order .
echo $item->getShippingAmount();
but if I tried with.
echo $order->getShippingAmount();
It works but it shows total of shipping amount of all orders, but conversely I want each single amount to be shown.
item ordered * quantity
Can anybody tell me how to do that?

Maybe you can use
$order->getShippingIncTax()

Try with below code :
for magento2 :
foreach ($order->getAllItems() as $item) {
echo $item->getShippingAmount();
}

Related

How to change woommerce shopping cart total amount using parameters?

I am currently starting an integration with Woocommerce, where I need to just use your payment gateway via an embedded website.
The total amount, name of the customer purchasing, and other data I send to you via URL:
https://www.example.com/shop/checkout/?p_amount=100&p_user=jonhy
The syntax to obtain the parameters within the web is:
if (! empty ($_GET["p_amount"]) and ! empty ($_GET["p_user"]) )
{
$v_amount = $_GET["p_amount"];
$v_user = $_GET["p_user"];
echo $v_amount . "<br>" ;
echo $v_user . "<br>" ;
}
else
{
echo "problem with variables";
}
The above works without problem, I manage to get the parameters and display them by the page in wordpress or woocommerce.
I need to pass the value of the "Amount" parameter to the Woocomerce shopping cart.
I also need the shopping cart to have a default product so that when opening it from the embedded web, Woocommerce does not return that the cart is empty.
I am only interested in processing the total that I send via parameters.
Is it possible to do this? how can I do it?
Thank you very much for your time, I will be attentive to your answers.
Regards.

Edit WC shipping method on orders

I want to simply change the shipping method of an order on Woocommerce.
I have seen a few posts on editing shipping methods on orders but I'm not 100% clear on the exact protocol of how it works, I have a rough idea but no success yet! If you can help me to get the order to update its shipping method that would be awesome! (this is the middle of a large project so I can't share the whole plugin, let me know if you need anymore details happy to provide anything that's necessary!)
I have this small bit of code that returns me a list of orders that need shipping method updated and the new shipping method rateID that it has to be changed to, that all works fine but i have included it so you can see where it comes from.
Once the array of orders to be updated has been constructed, it then needs to be processed using the set_shipping() method. One at a time working through the array items and updating the shipping method of each, from the original to the new one provided in the toUpdate array
UPDATED: i have tried using the WC_API_Orders() class as set_shipping is a method of that. still coming up with the unrecognised error.
'Class 'Inc\Api\Callbacks\WC_API_Orders' not found'
private function updateRound()
{
if (! empty($_POST['update'])) {
$updateorderID= $_POST['orderID']; //get list of orderID to change
$updateRound= $_POST['newRound']; //list of rounds new orders want swapped to
$updateList= $_POST['update']; //uses a check box to confirm user wants to update row (stops accidentally updating the whole list)
// print_r($_POST['update']); //shows an output to check results.
$toUpdate = []; //this is the array for all the shippingmmethods to update on set order etc.
//make list of order ID's to update and their new shipping method
foreach ($updateList as $key => $value) {
$toUpdate[] = [
'orderID' => $key,
'newRound' => $updateRound[$key]
];
}
}
$absOrder = new WC_API_Orders();
foreach ($toUpdate as $updateOrder) {
//echo "</br>OrderID: ".$updateOrder['orderID']." Round updated to ".$updateOrder['newRound'];
echo "order ".$updateOrder['orderID']."updating";
$absOrder->wc_get_order($updateOrder['orderID']);
echo " order retreived";
$absOrder->set_shipping($order, $updateOrder['newRound'], 'update' );
echo "updated </br>";
}
}
This is for a very local veg delivery scheme, people can only place an order if their postcode is in the set group, so that's not so important, this shipping method we use to change from 'wed round' to 'thurs round' etc. Simple really no concern for delivery companies etc, its all in house. Tax etc. doesn't matter, it's all done elsewhere, this is simply meant to be a way of editing orders onto delivery rounds.

How to get WooCommerce cart subtotal value?

I am currently trying to make an if else check in the checkout of a WooCommerce site.
I need to know if the total is greater or less than 100, so that it will say "You need to call to negotiate a shipping fee".
The code:
$woocommerce->cart->get_cart_total()
shows the value, but adds HTML content.
I need only the value itself.
I kind of found out how to do this the hard way.
I searched google for over 2 hours and found this page: https://woocommerce.wp-a2z.org/oik_api/wc_cartget_cart_subtotal/
global $woocommerce;
$subtotal = $woocommerce->cart->get_subtotal();
$subtax = $woocommerce->cart->get_subtotal_tax();
$subtotaltax = $subtotal+$subtax;
echo with $subtotaltax shows the value with the tax added.

Magento Multi Store Price Update Script - Mage Eav Model Entity Attribute Exception

We are running Magento with 2 stores, 1 store is retail, the other is wholesale. They share a single catalog, with split pricing between the two stores.
The script I am writing simply takes all of the pricing from the wholesaler site and is supposed to update the current price to the current price reflecting a 10% discount. My script is throwing the following error:
Total Products: 51937
PHP Fatal error: Uncaught exception 'Mage_Eav_Model_Entity_Attribute_Exception' in >/var/www/vhosts/mediagiantdesign.com/httpdocs/app/code/core/Mage/Core/Model/Config.php:1353
I have been wrestling with this for a little while. I know magento pretty well and for something trivial like this to stop me in my tracks is a bit aggravating.
Since there is no exception message attached to the stack trace, figuring out what it is has been difficult. It has something to do with setting the storeid on the load. if I take that out, or change it to setWebsiteId it works. However, it updates BOTH sites pricing not just the wholesale side.
Two Additional Notes:
Currently both sites prices in the catalog are the same. That is why you see me simply taking the same price from the same product. This script is supposed to apply the initial reduction in the wholesale side of the store.
Since I am debugging I have the break condition at the end. I do plan on removing it for a full run - also anyone who finds this post and finds the code useful (after its fixed of course) can remove it to have it run for the full catalog.
Here is my code:
<?php
ini_set("display_errors", 1);
error_reporting(E_ALL);
require_once 'app/Mage.php';
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
try {
//get the magento product collection for the Vendors website products
$vendorproducts = Mage::getModel('catalog/product')->getCollection();
} catch (Exception $ex) {
echo "Exception thrown.";
echo $ex->getTraceAsString();
echo $ex->getMessage(); //no output - weird.
}
echo "Total Products: " . $vendorproducts->count() . "\r\n";
$count = 0;
foreach($vendorproducts as $product)
{
$priceupdate = Mage::getModel('catalog/product')->setStoreId(2)->load($product->getId());
$retailprice = $priceupdate->getPrice();
echo $product->getId() . " - " . ($retailprice - ($retailprice *.10)) . "\r\n";
$priceupdate->setPrice(($retailprice - ($retailprice *.10)));
$priceupdate->setUrlKey(false);
$priceupdate->save();
$count++;
if ($count > 0)
break;
}
echo $count . " products updated.\r\n";
Solved. After some double checking I realized I had specified the wrong StoreID. An invalid store id is a real good way to trip magento up - devil is in the details.
Enjoy the script.

Magento - Insufficient Stock Notification on Product Page

I am using Magento 1.7.0.2. Whilst on the product page, if a customer attempts to add a quantity greater than we have in stock they receive a message stating ".. the requested quantity is not available".
Is there any way for magento to either email or log when this occurs? I.e. I receive an automatic email stating a customer has attempted to add X number of item X? This would allow me to identify lost sales due to us not having enough stock of a particular item?
Has anyone come across anything like this before or is this even possible?
Thank you in advance
Mike Prentice
yes this is possible
You have to code for this.
I came across this problem one time and what i have do like this below.
I have make one observer event to check if customer is requesting quantity more then available if so i sent email to admin.
What you can do is create one observer for chekout_cart_add_before event in this event you can put your logic.
Or otherwise you can use magento feature Backorders you can find this in inventory tab,if you enable this then customer can order even requested quantity > available quantity, customer can see one message in cart page about backorder.
There is no standart functionality to notify about low quantity products by email.
But there is RSS notification http://www.magentocommerce.com/wiki/modules_reference/english/mage_adminhtml/system_config/edit/cataloginventory
Extend this functionality to match your needs.
You could write some script which would parse RSS, and send email etc.
EDIT
Here is some extension you may like http://www.magentocommerce.com/magento-connect/low-stock-email-notification.html
But is is not free.
Here's how I've done it so that it sends a google analytics tracking event whenever a customer tries to order more than the available stock level.
First copy: app/code/core/Mage/CatalogInventory/Model/Stock/Item.php
To: app/code/local/Mage/CatalogInventory/Model/Stock/Item.php
so that you're not modifying a core file.
In app/code/local/Mage/CatalogInventory/Model/Stock/Item.php add this function
public function notifyOutOfStock($productId){
$session = Mage::getSingleton('checkout/session');
//Initialise as empty array, or use existing session data
$outOfStockItems = array();
if ($session->getOutOfStock()){
$outOfStockItems = $session->getOutOfStock();
}
try {
$product = Mage::getModel('catalog/product')->load($productId);
$sku = $product->getSKu();
if($sku){
//Add the current sku to our out of stock items (if not already there)
if(! isset($outOfStockItems[$sku]) ) {
$outOfStockItems[$sku] = 0;
}
}
} catch (Exception $e){
//Log your error
}
Mage::getSingleton('checkout/session')->setOutOfStock($outOfStockItems);
}
In that same file is another function called checkQuoteItemQty.
Inside that function you need to call your new function using $this->notifyOutOfStock($this->getProductId()); right after it sets each of the error messages and before the return statement.
So:
public function checkQuoteItemQty($qty, $summaryQty, $origQty = 0)
{
....
if ($this->getMinSaleQty() && ($qty) < $this->getMinSaleQty()) {
$result->setHasError(true)
->setMessage(
$_helper->__('The minimum quantity allowed for purchase is %s.', $this->getMinSaleQty() * 1)
)
->setQuoteMessage($_helper->__('Some of the products cannot be ordered in requested quantity.'))
->setQuoteMessageIndex('qty');
//** Call to new function **
$this->notifyOutOfStock($this->getProductId());
return $result;
}
.....
->setQuoteMessageIndex('qty');
//** Call to new function **
$this->notifyOutOfStock($this->getProductId());
return $result;
.....
What this does is add your product sku to an array in the checkout session.
This means you will have access to that info in the template file right after your page loads displaying the "Insufficient stock" notification.
So in one of your template files you can add some code to render the necessary JavaScript.
I've chosen header.phtml since it loads on every page. (Users can add quantities of items to the cart in the cart page as well as the product view page).
app/design/frontend/CUSTOMNAME/default/template/page/html/header.phtml
Somewhere down the bottom of the code add this:
<!-- GA tracking for out of stock items -->
<script>
try {
<?php
$session = Mage::getSingleton('checkout/session');
if ($session->getOutOfStock()){
$outOfStockItems = $session->getOutOfStock();
foreach($outOfStockItems as $sku=>$value) {
if($value==0){
//Render the GA tracking code
echo "_gaq.push(['_trackEvent', 'AddToCart', 'ProductQtyNotAvailable', '".$sku."']); \r\n";
//Set it to 1 so we know not to track it again this session
$outOfStockItems[$sku] = 1;
}
}
//Update the main session
Mage::getSingleton('checkout/session')->setOutOfStock($outOfStockItems);
}
?>
}
catch(err) {
//console.log(err.message);
}
</script>
Can confirm this works well and in my opinion is better than an email or RSS feed as you can analyse it along with the rest of your analytics.

Categories