I am trying to add conversion tracking to my magento store. I know I need to add the following code and customize it so magento will share info with CA.
<script type="text/javascript">
var _caq = _caq || [];
var products = [];
products.push({Sku: 'ProductID', UnitPrice: 'item price here', Quantity: 'quantity here'});
products.push({Sku: 'ProductID', UnitPrice: 'item price here', Quantity: 'quantity here'});
_caq.push(["Order", {OrderId: 'OrderID', Revenue: 'oVal', CurrencyCode: '3 letter currency code here', Products: products}]);
so far i have been trying to get the data from the order with the following code:
<?php $orderId = $this->getOrderId();
$order = Mage::getModel('sales/order')->load($orderId);
$items = $order->getAllItems();
$_grand = $order->getGrandTotal();
$custname = $order->getCustomerName();
$itemcount=count($items);
foreach ($items as $itemId => $item)
{
$sObject2->Item_name__c = $item->getName();
$sObject2->Unit_price__c = $item->getPrice();
$sObject2->Sku__c = $item->getSku();
$sObject2->Quantity__c = $item->getQtyToInvoice();
}
echo $_grand;
echo $custname;
?>
When i try to echo the customers name and grand total, i get a blank for the total and Guest for the customer name. Even if i make the $orderId a number of an order this happens.
When you're passing in the number of an order are you passing the entity_id or the increment_id? Usually the number you see in admin will be the increment_id. Look in the address bar of the browser to pick out the entity_id.
$order = Mage::getModel('sales/order')->load($orderId); // $orderId should be the entity_id.
Try this method of retrieving the order instead (Works on the success page):
$orderId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order = Mage::getModel("sales/order")->loadByIncrementId($orderId);
Also, make sure to call the correct method for getting the grand total:
$_grand = $order->getGrandTotal(); // Gets the grand total in the store currency.
$_grand = $order->getBaseGrandTotal(); // Gets the grand total in the base currency.
It's probably more useful for your tracking purposes to use the base currency. If you only have one store, or use one currency, it probably won't make any difference. But, if you ever use multiple currencies you'll need to get this right.
i am using these functions please take a look :
function get_all_orders($fromdate,$todate)
{
$getsales = mysql_query("SELECT * FROM `sales_flat_order` WHERE `created_at`>='$fromdate' AND `created_at`<='$todate'");
if(mysql_num_rows($getsales)> 0)
return $getsales;
else
return FALSE;
}
function num_items_under_order($order_entity_id)
{
$getorder_num = mysql_query("SELECT * FROM `sales_flat_order_item` WHERE `order_id`='$order_entity_id'");
if(mysql_num_rows($getorder_num) == 1)
return TRUE;
elseif(mysql_num_rows($getorder_num) > 1 )
return FALSE;
}
function get_order_item_details($order_entity_id)
{
$getsales = mysql_query("SELECT * FROM `sales_flat_order_item` WHERE `order_id`='$order_entity_id'");
if(mysql_num_rows($getsales) == 1)
{
return mysql_fetch_object($getsales);
}
elseif(mysql_num_rows($getsales) > 1)
{
return $getsales;
}
else
return FALSE;
}
Thanks
Related
I'm trying to do a onchange event with ajax and php according to country selected from a dropdown. My problem is that the response set the last price in the array on every item and I can't figure out a way to solve this.
Here is my code so far:
$("#field-organization-country-iso").on('change', (e) => {
e.preventDefault();
e.stopPropagation();
const CountryIso = $('#field-organization-country-iso').val();
Request.get(`/myrequested_file`, {
data: { CountryIso },
})
.done((response) => {
for (let i = 0; i < response.data.itemPrice.length; i++) {
const price = response.data.itemPrice[i];
$('.checkout-table tr').find('.hide-if-odd-or-sub').eq(i).html(price);
}
});
});
And the php-function:
public function change_currencyIso(Request $request, $summaryService): JSONResponse
{
$countryIso = $request->query->get('CountryIso');
$response = new JSONResponse();
$orderSummary = $summaryService->Summary(Cart::getCurrentCart(), User::currentUserOrNull(), $countryIso, null, null);
$items = $orderSummary->getItems();
$currencies = new ISOCurrencies();
$numberFormatter = new NumberFormatter(Environ::getLocale(), NumberFormatter::CURRENCY);
$moneyFormatter = new IntlMoneyFormatter($numberFormatter, $currencies);
$prices = [];
foreach ($items as $item) {
$price = $moneyFormatter->format($item->getLocalPrice());
$prices[] = $price;
}
$response->setVar('itemPrice', $prices);
return $response;
}
$prices returns the array with item prices but I know response writes over it. Can I loop through the array and add the response to each price?
My response with 'itemPrice' is only returning one of the existing prices.
{itemPrice: Array(2)}
itemPrice: Array(2)
0: "245,00 US$"
1: "32,90 US$"
length: 2
Now itemPrice returns the array but still puts everything on the same row. Tried a each but that didn't help.
You should add more details about the html structure, however I suppose you have a table with a row for each item, and the cells with the price have the class "hide-if-odd-or-sub". Also table rows are in the same order of the prices returned by the server. So, you have to assign each price to the correspondig table row:
foreach (var i in response.data.itemPrice) {
var price = response.data.itemPrice[i];
$('.checkout-table tr').eq(i).find('.hide-if-odd-or-sub').html(price);
}
This is not mush robust, because if the user change the items in the cart in another browser's tab and goes back to previous tab and updates the country, then the prices returned by the server won't correspond to items in the table, however it should work under normal usage.
Today I am working on the shopping cart for a users website script. When they add an item to the cart, it is stored in a $_SESSION variable called cartitems. I am storing arrays within the array of $_SESSION['cartitems'] that contain the item's itemid and the quantity of the items they are trying to add to the cart. Simply adding the items works awesome using the code I list below this, but I need them to increase the value of the items in the array assuming they try and add more of the same item instead of simply adding a new array into the SESSION. Heres an example:
-> User 1 visits the website.
- Add 5 melons to cart.
- Add 3 lemons to cart.
- Add 2 more melons to cart.
My array would print something like:
array(
array{0 => 1, 1 => 5},
array{0 => 2, 1 => 3},
array{0 => 1, 1 => 2}
)
.. while the goal of adding them would be something instead like the following:
array(
array{0 => 1, 1 => 7},
array{0 => 2, 1 => 3}
)
So that the value on the itemid of 1 would be increased to 7. I also need to know what its at, before adding the extra 2, incase there is only 6 melons in stock. Wouldn't want someone finding a way to add more melons then there are left in the stock field now would we!
I am already passing the stock field amount, along with weather it has unlimited stock support, or buy limits on an item, so I have all the information I need to limit stuff (which I already do when adding the items), just need a way to change the array if its already in there to increase the number is all. Here's the code I use to add items:
if(isset($_POST['quantity'])) {
// Cast quantity to an int for protection
$quantity = (int) $_POST['quantity'];
if(!empty($quantity) && $quantity > 0) {
$errors = 0;
// It doesn't support unlimited stock so we check stock level
if($unlimstock == "0") {
if($quantity > $stock) {
$quantity = $stock;
}
if($buylimit > 0) {
if($quantity > $buylimit) {
$errors = "1";
}
}
}
if($errors == 0) {
$_SESSION['cartitems'][] = array($itemid, $quantity);
header("Location: cart.php");
die();
}
}
}
What is the best approach to check if it's in the array, if it is increase the value, if not I can add it like I am already, and if it is, what is the value so I know how much it can be increased by. Thanks guys!
To simplify code your $_SESSION['cartitems'] should store data as:
$_SESSION['cartitems'] = [
'product_id1' => 'quantity1',
'product_id2' => 'quantity2',
];
Then updating a quantity is:
if (isset($_SESSION['cartitems'][$product_id])) {
$_SESSION['cartitems'][$product_id] += $quantity;
} else {
$_SESSION['cartitems'][$product_id] = $quantity;
}
If changing $_SESSION['cartitems'] structure is not possible, then you have to iterate over it:
$found = false;
foreach ($_SESSION['cartitems'] as $key => $item) {
// I suppose that 0-indexed element stores id
if ($item[0] == $product_id) {
// I suppose that 1-indexed element stores quantity
$_SESSION['cartitems'][$key][1] += $quantity;
$found = true;
// break as certain element found
break;
}
}
if (!$found) {
$_SESSION['cartitems'][] = array($product_id, $quantity);
}
Heres what I did including final fact check thanks to #u_mulder:
// Set that we dont't see it by default
$found = false;
foreach($_SESSION['cartitems'] as $key => $item) {
if($item[0] == $itemid) {
// If it has unlimited stock, who cares, otherwise fact check it
if($unlimstock == "1") {
$_SESSION['cartitems'][$key][1] += $quantity;
$found = true;
break;
} else {
// If it's less than or equal to stock, we can try and add it
if(($_SESSION['cartitems'][$key][1] + $quantity) <= $stock) {
// If it has a buy limit, we set max to buy limit and check it
if($buylimit > 0) {
if(($_SESSION['cartitems'][$key][1] + $quantity) <= $buylimit) {
$_SESSION['cartitems'][$key][1] += $quantity;
}
} else {
$_SESSION['cartitems'][$key][1] += $quantity;
}
}
// Woot, we found it, so we can update it
$found = true;
break;
}
}
}
// If it wasn't found, we can add it as a new item. This has been fact checked already
if(!$found) {
$_SESSION['cartitems'][] = array($itemid, $quantity);
}
I'm trying to total a bill balance with a program I'm working on in PHP.
The code I use to pull the pricing is as such.
public function PackagePricing($arg) {
$query = <<<SQL
SELECT packageID
FROM customer_packages
WHERE active = :true
AND customerID = :arg
SQL;
$resource = $this->db->db->prepare( $query );
$resource->execute( array (
":true" => 1,
":arg" => 1,
));
foreach($resource as $row) {
self::GetPricing($row['packageID']);
}
}
public function GetPricing($arg) {
$query = <<<SQL
SELECT price
FROM products
WHERE id = :arg
SQL;
$resource = $this->db->db->prepare( $query );
$resource->execute( array (
":arg" => $arg,
));
$totalBill = 0;
foreach($resource as $row) {
$totalBill+= $row['price'];
}
echo $totalBill;
}
Now by my understanding this should work, but what I'm getting in turn is:
On the right you can see the billing total and rather than totaling out it's giving me each individually.
The error seems quite obvious. Here's your sequence in different words :
Get all packages ID.
Foreach package ID, get the price of the item (only one result is returned)
For that single result, add up all the prices (you only get one). Print it and go back to 2.
What you see is not 2 prices that have been added as strings in some sort of way. You simply prints subsequently 2 different prices. 10 & 30
GetPricing should return a price, and the foreach loop that calls it should make the sum.
$total = 0;
foreach($resource as $row)
{
$total += self::GetPricing($row['packageID']);
}
Hope this helps.
I want to create invoice in to magento store using magento api in php.For that I want to create invoice for particular quantity and item means If anyone wants to invoice one item in paricular quantity then It shoud be done.My code is working for array() or all quantity.
Below is pseudo code for creating invoice
$client = new Zend_XmlRpc_Client('http://127.0.0.1:8080/AndroidMagento/api/xmlrpc')
$session = $client->call('login', array('tester','tester'));
$saleorderno = '100000007';
Mage::init();
$order = Mage::getModel('sales/order')->load($saleorderno);
$orderItems = $order->getAllItems();
$invoiceItems = array();
foreach ($orderItems as $_eachItem) {
$invoiceItems[$_eachItem->getItemId()] = $_eachItem->getQtyOrdered();
}
$result = $client->call('call',array($session,'sales_order_invoice.create',array($saleorderno,array('order_item_id' => 9474, 'qty' => 1),'Invoice Created by Test',false,false)));
I have seen this link where i found somewhat idea but i can't understand exactly.I can't understand how to get value of order_item_id.???
Any idea??? Please suggest me Thanks in advance...
item_id and product_id are different id.
order or quote has item_id and product_id.
You can try this:
$order = Mage::getModel('sales/order')->load($saleorderno);
$orderItems = $order->getAllItems();
foreach ($orderItems as $item){
print_r($item->getData());
print_r($item->getItemId()); //magic function to get ['item_id']
}
You can do it in 'sales/quote' Model.
Cheers ^^
Try this,
echo "<pre>";
$result = $client->call($session, 'sales_order.info', 'orderIncrementId');
print_r($result['item_id']);
print_r($result['product_id']);
and the $result will return all info of order including item_id and product_id,
with $result['item_id'] you can pass it to call
sales_order_invoice.create
then do
$result = $client->call(
$session,
'sales_order_invoice.create',
array('orderIncrementId' => '200000008',
array('order_item_id' => $result['item_id'],
'qty' => $result['total_qty_ordered'])
)
);
and the qty, You have to get it from $result['total_qty_ordered']
First, try to print_r[$result]; then You'll get some hints from it.
^^
I have order object and I need to get all shipped package tracking numbers. I tried following code, but it returns nothing even orders I tried had packages sent with tracking numbers.
$order = Mage::getModel('sales/order')->loadByIncrementId($orderid);
$trackingNumbers = $order->getTrackingNumbers();
Order object is not null, because it returns data for other methods like getShippingMethod etc.
If I click from "Shipping & Handling" link "Information Track Order", then popup shows all tracking numbers.
Try this..
$shipmentCollection = Mage::getResourceModel('sales/order_shipment_collection')
->setOrderFilter($order)
->load();
foreach ($shipmentCollection as $shipment){
$shipment->getAllTracks();
}
Edit:-
foreach ($shipmentCollection as $shipment){
foreach($shipment->getAllTracks() as $tracknum)
{
$tracknums[]=$tracknum->getNumber();
}
}
Now $tracknums will have the array of tracking numbers.
You can simply do this:
$orderIncrementId = 100000016; // YOUR ORDER INCREMENT ID;
$order = Mage::getModel('sales/order')->loadByIncrementId($orderIncrementId);
$trackNumber = array();
foreach ($order->getTracksCollection() as $track){
$trackNumber[] = $track->getNumber();
}