Exporting Invoices from Magento - php

I have been trying to export all of our invoices in a specific format for importing into Sage accounting. I have been unable to export via Dataflow as I need to export the customer ID (which strangely is unavailable) and also a couple of static fields to denote tax codes etc…
This has left me with the option of using the API to export the data and write it to a CSV. I have taken an example script I found (sorry can’t remember where in order to credit it...) and made some amendments and have come up with the following:
<?php
$website = 'www.example.com';
$api_login = 'user';
$api_key ='password';
function magento_soap_array($website,$api_login,$api_key,$list_type,$extra_info){
$proxy = new SoapClient('http://'.$website.'/api/soap/?wsdl');
$sessionId = $proxy->login($api_login, $api_key);
$results = $proxy->call($sessionId,$list_type,1);
if($list_type == 'order_invoice.list'){
/*** INVOICES CSV EXPORT START ***/
$filename = "invoices.csv";
$data = "Type,Account Reference,Nominal A/C Ref,Date,Invoice No,Net Amount,Tax Code,Tax Amount\n";
foreach($results as $invoice){
foreach($invoice as $entry => $value){
if ($entry == "order_id"){
$orders = $proxy->call($sessionId,'sales_order.list',$value);
}
}
$type = "SI";
$nominal = "4600";
$format = 'Y-m-d H:i:s';
$date = DateTime::createFromFormat($format, $invoice['created_at']);
$invoicedOn = $date->format('d/m/Y');
$invoiceNo = $invoice['increment_id'];
$subtotal = $invoice['base_subtotal'];
$shipping = $invoice['base_shipping_amount'];
$net = $subtotal+$shipping;
$taxCode = "T1";
$taxAmount = $invoice['tax_amount'];
$orderNumber = $invoice['order_id'];
foreach($orders as $order){
if ($order['order_id'] == $orderNumber){
$accRef = $order['customer_id'];
}
}
$data .= "$type,$accRef,$nominal,$invoicedOn,$invoiceNo,$net,$taxCode,$taxAmount\n";
}
file_put_contents($_SERVER['DOCUMENT_ROOT']."/var/export/" . $filename, "$header\n$data");
/*** INVOICES CSV EXPORT END ***/
}else{
echo "nothing to see here";
}/*** GENERIC PAGES END ***/
}/*** END function magento_soap_array ***/
if($_GET['p']=="1")
{
magento_soap_array($website,$api_login,$api_key,'customer.list','Customer List');
}
else if($_GET['p']=="2")
{
magento_soap_array($website,$api_login,$api_key,'order_creditmemo.list','Credit Note List');
}
else if($_GET['p']=="3")
{
magento_soap_array($website,$api_login,$api_key,'sales_order.list','Orders List');
}
else if($_GET['p']=="4")
{
magento_soap_array($website,$api_login,$api_key,'order_invoice.list','Invoice List');
}
?>
This seems to be working fine, however it is VERY slow and I can’t help but think there must be a better, more efficient way of doing it…
Has anybody got any ideas?
Thanks
Marc

i think on put break; would be okey. because only one key with order_id, no need to looping after found order_id key.
if ($entry == "order_id"){
$orders = $proxy->call($sessionId,'sales_order.list',$value);
break;
}
and you can gather all call(s) and call it with multicall as example:
$client = new SoapClient('http://magentohost/soap/api/?wsdl');
// If somestuff requires api authentification,
// then get a session token
$session = $client->login('apiUser', 'apiKey');
$result = $client->call($session, 'somestuff.method');
$result = $client->call($session, 'somestuff.method', 'arg1');
$result = $client->call($session, 'somestuff.method', array('arg1', 'arg2', 'arg3'));
$result = $client->multiCall($session, array(
array('somestuff.method'),
array('somestuff.method', 'arg1'),
array('somestuff.method', array('arg1', 'arg2'))
));
// If you don't need the session anymore
$client->endSession($session);
source

Related

php class function call single quote issue

I am wiring up the Authorize.net API for a web site and I have created a cart system where all is well so far. My issue is with the way I am using a parameter in one of the class function calls. It will only work if I use single quotes surrounding my string. I cannot use a variable at all it throws an error which is the reason I am here asking this question. For example:
$lineItem->setDescription('SOME TEXT GOES HERE'); // works perfectly
$foo = 'SOME TEXT GOES HERE';
$lineItem->setDescription($foo); // fails
$lineItem->setDescription("$foo"); // fails
// I tried all kinds of ways like:
$foo = "SOME TEXT GOES HERE"; // double quotes
$lineItem->setDescription($foo); // fails
// I tried this too and this works but In my case I am within a loop
define("FOO", $foo);
$lineItem->setDescription(FOO); // works but I need to loop all the items
// I tried this
$foo = json_encode($foo);
$lineItem->setDescription($foo); // fails?
// It seems like this would work but I know this is not realistic.
$lineItem->setDescription('$foo'); // this is just for illustrative purposes
So what am I doing wrong? If I could print a variable in single quotes it would seem to work but PHP doesn't work like that. Can anyone give me another way to get this to work?
Thanks in advance.
Let me show the full function so everyone can see whats happening...
use net\authorize\api\contract\v1 as AnetAPI;
use net\authorize\api\controller as AnetController;
function AuthorizeNet(){
require 'assets/authorizenet/vendor/autoload.php';
define("AUTHORIZENET_LOG_FILE", "phplog");
// Common setup for API credentials
$merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
$merchantAuthentication->setName($GLOBALS['authorizenet_api']);
$merchantAuthentication->setTransactionKey($GLOBALS['authorizenet_tx']);
// Create the payment data for a credit card
$creditCard = new AnetAPI\CreditCardType();
$creditCard->setCardNumber("4111111111111111");
$creditCard->setExpirationDate("2038-12");
$paymentOne = new AnetAPI\PaymentType();
$paymentOne->setCreditCard($creditCard);
// Create the Bill To info
$billto = new AnetAPI\CustomerAddressType();
$billto->setFirstName("Ellen");
$billto->setLastName("Johnson");
$billto->setCompany("Souveniropolis");
$billto->setAddress("14 Main Street");
$billto->setCity("Pecan Springs");
$billto->setState("TX");
$billto->setZip("44628");
$billto->setCountry("USA");
$billto->setPhoneNumber("310-867-5309");
$total = 0;
$tax=0;
$shipping=0;
$items_subtotal = 0;
$discount_total = 0;
$lineItem_Array = array();
$i=0;
// Create the items
foreach($_SESSION['ms_cart'] as $cart_item){
$desc = array();
if(!empty($cart_item["size"])){
$desc[] = "Size: " . $cart_item["size"];
}
if(!empty($cart_item["color"])){
$desc[] = "Color: " . $cart_item["color"];
}
$description = implode(", ", $desc);
if(!empty($cart_item["discount_total"])){
$discount_total = $discount_total+round($cart_item["discount_total"],2);
}
$name = $cart_item["name"];
$desc = $description;
$quantity = $cart_item["qty"];
$price = $cart_item["price"];
$sku = $cart_item["uiid"];
$items_subtotal = ($price*$quantity)+$items_subtotal;
$lineItem = new AnetAPI\LineItemType();
$lineItem->setItemId($sku);
$lineItem->setName($name); // <-- this is my issue
$lineItem->setDescription($desc); // <-- also here
$lineItem->setQuantity(1);
$lineItem->setUnitPrice(1);
$lineItem->setTaxable(0); // 1 Yes 0 for no
$lineItem_Array[$i] = $lineItem;
$i++;
}
$subtotal = round($items_subtotal, 2);
if(!empty($_SESSION['ms_cart_tax'])){
$tax = number_format(round($_SESSION['ms_cart_tax'], 2), 2, '.', '');
}
if(!empty($_SESSION['ms_ship_rate'])){
$shipping = round($_SESSION['ms_ship_rate'], 2);
}
$total = ($subtotal+$tax+$shipping)-$discount_total;
$total = round($total,2);
// Create a transaction
$transactionRequestType = new AnetAPI\TransactionRequestType();
$transactionRequestType->setTransactionType( "authCaptureTransaction");
$transactionRequestType->setBillTo($billto);
$transactionRequestType->setLineItems($lineItem_Array);
$transactionRequestType->setPayment($paymentOne);
$total=4; // there are 4 items in my cart loop for now I have hard coded the 4
$transactionRequestType->setAmount($total);
$request = new AnetAPI\CreateTransactionRequest();
$request->setMerchantAuthentication($merchantAuthentication);
$request->setTransactionRequest($transactionRequestType);
$controller = new AnetController\CreateTransactionController($request);
$response = $controller->executeWithApiResponse($GLOBALS['authorizenet_env']);
if ($response != null)
{
$tresponse = $response->getTransactionResponse();
if (($tresponse != null) && ($tresponse->getResponseCode()=="1") )
{
echo "Charge Credit Card AUTH CODE : " . $tresponse->getAuthCode() . "\n";
echo "Charge Credit Card TRANS ID : " . $tresponse->getTransId() . "\n";
}
else
{
echo "Charge Credit Card ERROR : Invalid response\n";
}
}
else
{
echo "Charge Credit card Null response returned";
}
}
This was not a good solution for me. I ended up removing the php-sdk and creating my own function to call Authorize.net's API. With some simple PHP JSON and cURL. I was up and running in an hour. Sometimes fussing around with API's can make you spend more time than just writing from scratch. I would like to thank everyone that took the time to take look and provide feedback.

How to get "metric" and "element" names for PHP - Adobe Analytics

I am pulling a report using the Adobe API from Omniture.
Here is the full script :
<?php
include_once('/path/SimpleRestClient.php');
// Date
$end_date = date("Y-m-d",strtotime("-1 days"));
$start_date = date("Y-m-d",strtotime("-8 days"));
// Location of the files exported
$adobe_file = '/path/Adobe_'.$end_date.'.csv';
// List creation that will be updated with the fields and be put into my CSV file
$list = array
(
array('lasttouchchannel', 'product','visits','CTR(Clicks/PageViews)') // headers // ADD or DELETE metrics #
);
function GetAPIData($method, $data)
{
$username = "XXXX";
$shared_secret = "XXXX";
$postURL = "https://api3.omniture.com/admin/1.4/rest/?method=";
// Nonce is a simple unique id to each call to prevent MITM attacks.
$nonce = md5(uniqid(php_uname('n'), true));
// The current timestamp in ISO-8601 format
$nonce_ts = date('c');
/* The Password digest is a concatenation of the nonce, it is timestamp and your password
(from the same location as your username) which runs through SHA1 and then through a base64 encoding */
$digest = base64_encode(sha1($nonce . $nonce_ts . $shared_secret));
$rc = new SimpleRestClient();
$rc -> setOption(CURLOPT_HTTPHEADER, array("X-WSSE: UsernameToken Username=\"$username\", PasswordDigest=\"$digest\", Nonce=\"$nonce\", Created=\"$nonce_ts\""));
//var_dump($o);
$rc -> postWebRequest($postURL .$method, $data);
return $rc;
}
$method = 'Report.Queue';
$data ='
{
"reportDescription":
{
"reportSuiteID":"XXXX",
"dateFrom":"'.$start_date.'",
"dateTo":"'.$end_date.'",
"metrics":[{"id":"visits"},{"id":"instances"},{"id":"pageviews"}],
"elements":[{"id":"lasttouchchannel","top":"50000"}]
}
}';
/*
"date":"'.$date.'",
"dateTo":"'.$date.'",
"dateFrom":"'.$start_date.'",
"dateTo":"'.$end_date.'",
*/
$rc=GetAPIData($method, $data);
if($rc -> getStatusCode() == 200) // status code 200 is for 'ok'
{
$counter = 0;
do
{
if($counter>0){sleep($sleep = 120);}
$return = GetAPIData('Report.Get', $rc->getWebResponse());
$counter++;
}while($return -> getStatusCode() == 400 && json_decode($return->getWebResponse())->error == 'report_not_ready'); // status code 400 is for 'bad request'
//
$json=json_decode($return->getWebResponse());
foreach ($json->report->data as $el)
{
echo $el->name.":".$el->counts[0].":".$el->counts[1]."\n";
// Adding the data in the CSV file without overwriting the previous data
array_push($list, array($el->name, $el->name, $el->counts[0], ($el->counts[1])/($el->counts[2])));
}
}
else
{
echo "Wrong";
}
$fp = fopen($adobe_file, 'w');
foreach ($list as $fields)
{
// Save the data into a CSV file
fputcsv($fp, $fields);
}
fclose($fp);
?>
How can I get the names of the metrics and elements in order to use them in this script? There is no way. I searched with all the possible tags on google and nothing worked !
I need the metrics and elements for this part of the code :
$data ='
{
"reportDescription":
{
"reportSuiteID":"XXXX",
"dateFrom":"'.$start_date.'",
"dateTo":"'.$end_date.'",
"metrics":[{"id":"visits"},{"id":"instances"},{"id":"pageviews"}],
"elements":[{"id":"lasttouchchannel","top":"50000"}]
}
}';
I cannot find 'date' as an element which is crucial. I cannot find all the other metrics as well. In Google Analytics we had this link :
Google Analytics Query
but in Adobe there is not any. I want something like that :
"metrics":[{"id":"instances"},{"id":"impressions"}],
"elements":[{"id":"date","top":"50000"}]
You would json_decode() as $data contains a JSON string. For example:
$data ='
{
"reportDescription":
{
"reportSuiteID":"XXXX",
"dateFrom":"'.$start_date.'",
"dateTo":"'.$end_date.'",
"metrics":[{"id":"visits"},{"id":"instances"},{"id":"pageviews"}],
"elements":[{"id":"lasttouchchannel","top":"50000"}]
}
}';
$json = json_decode($data, true);
echo $json['reportDescription']['dateFrom'];
print_r($json['reportDescription']['metrics']);

Import product review CSV in magento

I am working on importing a csv of product reviews to my magento.
The csv is in my magento shell folder. I created a product_review.php script inside my shell directory
<?php
require '../app/Mage.php';
umask(0);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
ini_set('max_execution_time', 84000);
ini_set('memory_limit', '5120M');
$fp = fopen('final_available_dup.csv', 'r');
//Mage::app()->setCurrentStore(4); //desired store id
while($line = fgetcsv($fp)) {
$review = Mage::getModel('review/review');
$review->setEntityPkValue($line[0]);//previews1.csv
$review->setCreatedAt($line[1]);//previews1.csv
$review->setStatusId($line[2]); //approved
$review->setTitle($line[3]);
$review->setNickname($line[4]);
$review->setDetail($line[5]);
$review->setEntityId($line[6]);
$review->setStoreId(Mage::app()->getStore()->getId());
//$review->setStatusId($line[5]);
$review->setCustomerId($line[7]);//null is for administrator
$review->setReviewsCount($line[8]);//null is for administrator
$review->setReviewId($review->getId());
$review->setStores(array(Mage::app()->getStore()->getId()));
$review->save();
$review->aggregate();
}
?>
and when i run the shell folder and run product_review.php a blank page came which i guess is the correct way.
But when i go into my back end and check i cannot see any reviews.I am not able to which product the review is getting updated.
I don't know is there anything more I should do?
You can use following code for importing product reviews.
My CSV is as following format :
"created_at","Sku","status_id","title","detail","nickname","customer_id","option_id","entity_id"
"2016-04-01 19:42:09","1991474","2","Top","Blij van!!","claes wassenaar","","1:4#3:15#2:9","24582"
So make sure your edit your CSV path in following code and assign proper values to variables.
require_once 'app/Mage.php';
Mage::app();
$fileLocation = "var/import/import_review.csv"; // Set your CSV path here
$fp = fopen($fileLocation, 'r');
$count = 1;
while($data = fgetcsv($fp)){
if($count > 1){
//initiate required variables
$_createdAt = $data[0];
$_sku = $data[1];
$_catalog = Mage::getModel('catalog/product');
$_productId = $_catalog->getIdBySku($_sku);
$_statusId = $data[2];
$_title = $data[3];
$_detail = $data[4];
$_customerId = NULL;
$_nickname = $data[5];
//load magento review model and assign values
$review = Mage::getModel('review/review');
$review->setCreatedAt($_createdAt); //created date and time
$review->setEntityPkValue($_productId);//product id
$review->setStatusId($_statusId); // status id
$review->setTitle($_title); // review title
$review->setDetail($_detail); // review detail
$review->setEntityId(1); // leave it 1
$review->setStoreId(Mage::app()->getStore()->getId()); // store id
$review->setCustomerId($_customerId); //null is for administrator
$review->setNickname($_nickname); //customer nickname
$review->setReviewId($review->getId());//set current review id
$review->setStores(array(Mage::app()->getStore()->getId()));//store id's
$review->save();
$review->aggregate();
//set review ratings
if($data[7]){
$arr_data = explode("#",$data[7]);
if(!empty($arr_data)) {
foreach($arr_data as $each_data) {
$arr_rating = explode(":",$each_data);
if($arr_rating[1] != 0) {
Mage::getModel('rating/rating')
->setRatingId($arr_rating[0])
->setReviewId($review->getId())
->setCustomerId($_customerId)
->addOptionVote($arr_rating[1], $_productId);
}
}
}
$review->aggregate();
}
}
// if($count == 5){
// die("total $count reviews are imported!");
// }
$count++;
}
echo "total $count reviews are imported!";
?>

Getting Data from MYSQL DB

I'm facing problems when trying to get data from a MySQL Database in an Android application
The output is:
06-29 11:40:42.123: E/JSON(1426): {"tag":"getroute","success":1,"error":0,"products":[]}
I think the problem I’m facing is in my PHP file (this is the code of the tag):
if( . . . )
{
. . .
}
else if ($tag == 'getroute')
{
$endloc = $_POST['end'];
$op = $db->getRoutes($endloc);
if ($op)
{
$response["products"] = array();
while($data= mysql_fetch_assoc($op))
{
$product = array();
$product ["uname"] = $data["uname"];
$product ["start"] = $data["start"];
$product ["end"] = $data["end"];
$product ["meet1"] = $data["meet1"];
$product ["meet1time"] = $data["meet1time"];
$product ["meet2"] = $data["meet2"];
$product ["meet2time"] = $data["meet2time"];
$product ["meet3"] = $data["meet3"];
$product ["meet3time"] = $data["meet3time"];
$product ["ismoke"] = $data["ismoke"];
$product ["iwomen"] = $data["iwomen"];
$product ["ctime"] = $data["ctime"];
$product ["seats"] = $data["seats"];
// push single product into final response array
array_push($response["products"], $product);
}
$response["success"] = 1;
echo json_encode($response);
// user stored successfully
}
else
{
// user failed to store
$response["error"] = 1;
$response["error_msg"] = "Error occured in Making Route";
echo json_encode($response);
}
}
I don’t know where the problem is. I searched over the internet and I found some tutorials but they always give me this error.
Function getroute :
public function getRoutes($endlocation)
{
$result = mysql_query("SELECT * FROM routes WHERE end = '$endlocation'");
return $result;
}
Try checking the number of results with mysql_num_rows() before you begin your while.
Additionally, immediately after your while, try using print_r($data) to verify that there is stuff in your record.
It seems to me that you're just having issues with your data source.

Create order programmatically in Magento

I'm using these two methods to create orders programmatically in Magento.
The first one creates a Quote:
public function prepareCustomerOrder($customerId, array $shoppingCart, array $shippingAddress, array $billingAddress,
$shippingMethod, $couponCode = null)
{
$customerObj = Mage::getModel('customer/customer')->load($customerId);
$storeId = $customerObj->getStoreId();
$quoteObj = Mage::getModel('sales/quote')->assignCustomer($customerObj);
$storeObj = $quoteObj->getStore()->load($storeId);
$quoteObj->setStore($storeObj);
// add products to quote
foreach($shoppingCart as $part) {
$productModel = Mage::getModel('catalog/product');
$productObj = $productModel->setStore($storeId)->setStoreId($storeId)->load($part['PartId']);
$productObj->setSkipCheckRequiredOption(true);
try{
$quoteItem = $quoteObj->addProduct($productObj);
$quoteItem->setPrice(20);
$quoteItem->setQty(3);
$quoteItem->setQuote($quoteObj);
$quoteObj->addItem($quoteItem);
} catch (exception $e) {
return false;
}
$productObj->unsSkipCheckRequiredOption();
$quoteItem->checkData();
}
// addresses
$quoteShippingAddress = new Mage_Sales_Model_Quote_Address();
$quoteShippingAddress->setData($shippingAddress);
$quoteBillingAddress = new Mage_Sales_Model_Quote_Address();
$quoteBillingAddress->setData($billingAddress);
$quoteObj->setShippingAddress($quoteShippingAddress);
$quoteObj->setBillingAddress($quoteBillingAddress);
// coupon code
if(!empty($couponCode)) $quoteObj->setCouponCode($couponCode);
// shipping method an collect
$quoteObj->getShippingAddress()->setShippingMethod($shippingMethod);
$quoteObj->getShippingAddress()->setCollectShippingRates(true);
$quoteObj->getShippingAddress()->collectShippingRates();
$quoteObj->collectTotals(); // calls $address->collectTotals();
$quoteObj->setIsActive(0);
$quoteObj->save();
return $quoteObj->getId();
}
And the second one uses that Quote to create Order:
public function createOrder($quoteId, $paymentMethod, $paymentData)
{
$quoteObj = Mage::getModel('sales/quote')->load($quoteId); // Mage_Sales_Model_Quote
$items = $quoteObj->getAllItems();
$quoteObj->reserveOrderId();
// set payment method
$quotePaymentObj = $quoteObj->getPayment(); // Mage_Sales_Model_Quote_Payment
$quotePaymentObj->setMethod($paymentMethod);
$quoteObj->setPayment($quotePaymentObj);
// convert quote to order
$convertQuoteObj = Mage::getSingleton('sales/convert_quote');
$orderObj = $convertQuoteObj->addressToOrder($quoteObj->getShippingAddress());
$orderPaymentObj = $convertQuoteObj->paymentToOrderPayment($quotePaymentObj);
// convert quote addresses
$orderObj->setBillingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getBillingAddress()));
$orderObj->setShippingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getShippingAddress()));
// set payment options
$orderObj->setPayment($convertQuoteObj->paymentToOrderPayment($quoteObj->getPayment()));
if ($paymentData) {
$orderObj->getPayment()->setCcNumber($paymentData->ccNumber);
$orderObj->getPayment()->setCcType($paymentData->ccType);
$orderObj->getPayment()->setCcExpMonth($paymentData->ccExpMonth);
$orderObj->getPayment()->setCcExpYear($paymentData->ccExpYear);
$orderObj->getPayment()->setCcLast4(substr($paymentData->ccNumber,-4));
}
// convert quote items
foreach ($items as $item) {
// #var $item Mage_Sales_Model_Quote_Item
$orderItem = $convertQuoteObj->itemToOrderItem($item);
$options = array();
if ($productOptions = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct())) {
$options = $productOptions;
}
if ($addOptions = $item->getOptionByCode('additional_options')) {
$options['additional_options'] = unserialize($addOptions->getValue());
}
if ($options) {
$orderItem->setProductOptions($options);
}
if ($item->getParentItem()) {
$orderItem->setParentItem($orderObj->getItemByQuoteItemId($item->getParentItem()->getId()));
}
$orderObj->addItem($orderItem);
}
$orderObj->setCanShipPartiallyItem(false);
try {
$orderObj->place();
} catch (Exception $e){
Mage::log($e->getMessage());
Mage::log($e->getTraceAsString());
}
$orderObj->save();
//$orderObj->sendNewOrderEmail();
return $orderObj->getId();
}
The process works fine, no errors, and the order is created. But the total is 0 and there are no products in it no matter what I put.
I've traced it and I can confirm that the rows are added to the sales_flat_quote and sales_flat_quote_item tables, so that is ok. But when running the createOrder and calling
$items = $quoteObj->getAllItems();
an empty array is always returned, and I have no idea why. I have configurable and simple products in my shop. This happens when I add simple, when I add configurable the error appears as the method
$quoteItem = $quoteObj->addProduct($productObj);
returns null.
It seems to me, you didn't load product collection, therefore, the cart always return empty. Try this link, it will give you more clear help. Create order programmatically
// this is get only one product, you can refactor the code
$this->_product = Mage::getModel('catalog/product')->getCollection()
->addAttributeToFilter('sku', 'Some value here...')
->addAttributeToSelect('*')
->getFirstItem();
// load product data
$this->_product->load($this->_product->getId());
This code worked for me,
public function createorder(array $orderdata)
{
$quoteId = $orderdata['quoteId'];
$paymentMethod = $orderdata['paymentMethod'];
$paymentData = $orderdata['paymentData'];
$quoteObj = Mage::getModel('sales/quote')->load($quoteId);
$items = $quoteObj->getAllItems();
$quoteObj->reserveOrderId();
$quotePaymentObj = $quoteObj->getPayment();
$quotePaymentObj->setMethod($paymentMethod);
$quoteObj->setPayment($quotePaymentObj);
$convertQuoteObj = Mage::getSingleton('sales/convert_quote');
$orderObj = $convertQuoteObj->addressToOrder($quoteObj->getShippingAddress());
$orderPaymentObj = $convertQuoteObj->paymentToOrderPayment($quotePaymentObj);
$orderObj->setBillingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getBillingAddress()));
$orderObj->setShippingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getShippingAddress()));
$orderObj->setPayment($convertQuoteObj->paymentToOrderPayment($quoteObj->getPayment()));
foreach ($items as $item)
{
$orderItem = $convertQuoteObj->itemToOrderItem($item);
$options = array();
if ($productOptions = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct()))
{
$options = $productOptions;
}
if ($addOptions = $item->getOptionByCode('additional_options'))
{
$options['additional_options'] = unserialize($addOptions->getValue());
}
if ($options)
{
$orderItem->setProductOptions($options);
}
if ($item->getParentItem())
{
$orderItem->setParentItem($orderObj->getItemByQuoteItemId($item->getParentItem()->getId()));
}
$orderObj->addItem($orderItem);
}
$quoteObj->collectTotals();
$service = Mage::getModel('sales/service_quote', $quoteObj);
$service->submitAll();
$orderObj->setCanShipPartiallyItem(false);
try
{
$last_order_increment_id = Mage::getModel("sales/order")->getCollection()->getLastItem()->getIncrementId();
return $last_order_increment_id;
}
catch (Exception $e)
{
Mage::log($e->getMessage());
Mage::log($e->getTraceAsString());
return "Exception:".$e;
} }
I had the same problem and delved into the API to find a solution. I changed the way that I loaded a product by using :
$productEntityId = '123456';
$store_code = 'my_store_code';
$product = Mage::helper('catalog/product')->getProduct($productEntityId,Mage::app()->getStore($store_code)->getId());
I found this tutorial to be very useful too :
http://www.classyllama.com/content/unravelling-magentos-collecttotals
If you are looking for a script on order creation this is a very good start :
http://pastebin.com/8cft4d8v
Hope that this helps someone ;)

Categories