I've been working with the PHP api for google Calendar, and have been getting quite frustrated.
I downloaded the zend package with all the libraries from google's page, and have been working off the provided code to make sure it can meet my requirements.
The issue I'm running into involves getting an event back from the system. The provided code includes a demo with function getEvent($clientId, $eventId), which based on the documentation and reading the code, i would expect to return an event that is in my calendar that matches the provided Id.
So in my tests, I create a new event, and then I try to retrieve it. However, whenever I retrieve the event, Zend_data_Gdata_App_HttpException is:
function processPageLoad()
{
global $_SESSION, $_GET;
if (!isset($_SESSION['sessionToken']) && !isset($_GET['token'])) {
requestUserLogin('Please login to your Google Account.');
} else {
$client = getAuthSubHttpClient();
$id = createEvent ($client, 'Tennis with Beth',
'Meet for a quick lesson', 'On the courts',
'2010-10-20', '10:00',
'2010-10-20', '11:00', '-08');
$newEvent = getEvent($client, $id);
}
}
the code for createEvent( ) is :
function createEvent ($client, $title = 'Tennis with Beth',
$desc='Meet for a quick lesson', $where = 'On the courts',
$startDate = '2008-01-20', $startTime = '10:00',
$endDate = '2008-01-20', $endTime = '11:00', $tzOffset = '-08')
{
$gc = new Zend_Gdata_Calendar($client);
$newEntry = $gc->newEventEntry();
$newEntry->title = $gc->newTitle(trim($title));
$newEntry->where = array($gc->newWhere($where));
$newEntry->content = $gc->newContent($desc);
$newEntry->content->type = 'text';
$when = $gc->newWhen();
$when->startTime = "{$startDate}T{$startTime}:00.000{$tzOffset}:00";
$when->endTime = "{$endDate}T{$endTime}:00.000{$tzOffset}:00";
$newEntry->when = array($when);
$createdEntry = $gc->insertEvent($newEntry);
return $createdEntry->id->text;
}
And finally the code for getEvent() is:
function getEvent($client, $eventId)
{
$gdataCal = new Zend_Gdata_Calendar($client);
$query = $gdataCal->newEventQuery();
$query->setUser('default');
$query->setVisibility('private');
$query->setProjection('full');
$query->setEvent($eventId);
try {
$eventEntry = $gdataCal->getCalendarEventEntry($query);
return $eventEntry;
} catch (Zend_Gdata_App_Exception $e) {
var_dump($e);
return null;
}
}
we have the same problem, just share my solution. since you assign $id = createEvent()
$id will have a URL values. then you use $id getEvent($client, $id);
the solution is that getCalendarEventEntry() can have a $query or just a URL.
function getEvent($client, $eventId)
{
$gdataCal = new Zend_Gdata_Calendar($client);
try {
$eventEntry = $gdataCal->getCalendarEventEntry($eventId);
return $eventEntry;
} catch (Zend_Gdata_App_Exception $e) {
var_dump($e);
return null;
}
Hope it helps!!
Related
I'm working (for fun), with an API (Riot API), and I made something to retrieve match histories (it's in the game). And I've a problem, everything works really fine, but I don't know how to optimize it, what I mean is : I do the call every time the user refresh the page, and it takes loooong looong time. I tried to call it with AJAX, but didn't find a good way, AJAX dont find my objects.
Here is the code :
$match_history = [];
$api = "";
if (!empty($region)) {
try {
$api = new App\Library\RiotAPI\RiotAPI([
App\Library\RiotAPI\RiotAPI::SET_KEY =>
App\Config::API_KEY,
App\Library\RiotAPI\RiotAPI::SET_CACHE_RATELIMIT => true,
App\Library\RiotAPI\RiotAPI::SET_CACHE_CALLS => true,
App\Library\RiotAPI\RiotAPI::SET_REGION =>
App\Library\RiotAPI\Definitions\Region::getRegion($region),
]);
} catch (\Exception $e) {
// die($e->getMessage());
}
}
if ($api) {
// Insert current rank etc...
try {
$summoner = $api-
>getSummonerByName(App\Repository\UserRepository::getInstance()-
>getUserDetail($_SESSION['user']['id'], 'summoner_name'));
} catch (\Exception $e) {
$summoner = null;
}
// Match history
if (!empty($summoner)) {
try {
$matches = $api->getRecentMatchlistByAccount($summoner->accountId);
// For every matches
foreach ($matches as $match) {
$a_match = $api->getMatch($match->gameId);
if ($a_match->gameType === "MATCHED_GAME") {
$gameCreation = date("d-M-Y H:i:s", substr($a_match-
>gameCreation, 0, 10));
if ($gameCreation >= date("d-M-Y",
strtotime($user['created_at']))) {
// Get the participant ID of the customer
foreach ($a_match->participantIdentities as
$participantIdentity) {
if ($participantIdentity->player->currentAccountId
=== $summoner->accountId) {
$participantId = $participantIdentity-
>participantId;
}
}
// Get stats of the participant
foreach ($a_match->participants as $participant) {
if ($participant->participantId === $participantId)
{
$match_history[$match->gameId]['gameCreation'] =
$gameCreation;
$match_history[$match->gameId]['championId'] =
$participant->championId;
$match_history[$match->gameId]['spells']
['spell1'] = $participant->spell1Id;
$match_history[$match->gameId]['spells']
['spell2'] = $participant->spell2Id;
$match_history[$match->gameId]['win'] =
$participant->stats->win;
$match_history[$match->gameId]['kills'] =
$participant->stats->kills;
$match_history[$match->gameId]['deaths'] =
$participant->stats->deaths;
$match_history[$match->gameId]['assists'] =
$participant->stats->assists;
$match_history[$match->gameId]['goldEarned'] =
$participant->stats->goldEarned;
$match_history[$match->gameId]
['totalMinionsKilled'] = $participant->stats->totalMinionsKilled;
$match_history[$match->gameId]['items']['item0']
= $participant->stats->item0;
$match_history[$match->gameId]['items']['item1']
= $participant->stats->item1;
$match_history[$match->gameId]['items']['item2']
= $participant->stats->item2;
$match_history[$match->gameId]['items']['item3']
= $participant->stats->item3;
$match_history[$match->gameId]['items']['item4']
= $participant->stats->item4;
$match_history[$match->gameId]['items']['item5']
= $participant->stats->item5;
$match_history[$match->gameId]['items']['item6']
= $participant->stats->item6;
}
}
}
}
}
} catch (\Exception $e) {
// die($e->getMessage());
}
}
}
I would like to know if there's a way to : - Run it in background, without AJAX or something like : Keep in mind the match_history for X time, and then after X time, do the call again when the user refresh the page.
Thanks for your help!
Best Regards.
Basically, im trying to make a finance section on magento, I have looked into how to place an order as part of the finance submission, everywhere I look uses the code below (Not exact):
$order = Mage::getModel('sales/order');
$store = Mage::app()->getStore();
$website_id = Mage::app()->getWebsite()->getStoreId();
$quote = Mage::getModel('sales/order')->setStoreId($store->getId());
$customer = Mage::getSingleton('customer/session')->getCustomer();
$quote->assignCustomer($customer);
$quote->setSendCconfirmation(1);
$product_ids = array();
$cart = Mage::getModel('checkout/cart')->getQuote();
foreach($cart->getAllVisibleItems() as $item) {
$quote->addProduct($item->getProduct() , $item->getQty());
}
$shipping = $quote->getShippingAddress();
$shipping->setCollectShippingRates(true)->collectShippingRates()->setShippingMethod('flatrate_flatrate')->setPaymentMethod(array(
'method' => 'checkmo'
));
try {
$service = Mage::getModel('sales/service_quote', $quote);
$service->submitAll();
$increment_id = $service->getOrder()->getRealOrderId();
}
catch(Exception $e) {
die($e->getMessage());
}
catch(Mage_Core_Exception $d) {
die($d->getMessage());
}
And for some reason i keep getting this error:
I was loading the customer from session, and not supplying the correct model as an argument , for anyone also looking for this answer;
$customer = Mage::getModel('customer/customer')->loadByEmail(Mage::getSingleton('customer/session')->getCustomer()->getEmail());
I am trying to test Paypals batch payout:
My code:
// ...
public function sendBatchPayment(array $payoutItems, $senderBatchId, $type= 'Email', $currency = 'CAD', $note = '') {
$payouts = new \PayPal\Api\Payout();
$senderBatchHeader = new \PayPal\Api\PayoutSenderBatchHeader();
$senderBatchHeader->setSenderBatchId($senderBatchId)
->setEmailSubject("You have a Payout!");
foreach ($payoutItems as $payoutItem) {
$emailExists = (isset($payoutItem['email']) && !empty($payoutItem['email']));
$amountExists = (isset($payoutItem['amount']) && !empty($payoutItem['amount']));
$senderItemIdExists = (isset($payoutItem['sender_item_id']) && !empty($payoutItem['sender_item_id']));
if(!$emailExists || !$amountExists || !$senderItemIdExists) continue;
$receiver = $payoutItem['email'];
$item_id = $payoutItem['sender_item_id'];
$value = (float) $payoutItem['amount'];
$senderItem = new \PayPal\Api\PayoutItem();
$senderItem->setRecipientType('Email')
->setNote('Your Payment')
->setReceiver($receiver)
->setSenderItemId($item_id)
->setAmount(new \PayPal\Api\Currency('{
"value":$value,
"currency":"CAD"
}'));
$payouts->setSenderBatchHeader($senderBatchHeader)
->addItem($senderItem);
} // EO foreach
$request = clone $payouts;
try {
$output = $payouts->create(null, $this->apiContext);
} catch (Exception $e) {
return $e->getMessage;
}
return $output;
}
But I keep getting a 400.
I suspect its due to this being inside the loop:
$payouts->setSenderBatchHeader($senderBatchHeader)
->addItem($senderItem);
when Paypals examples are like this:
$payouts->setSenderBatchHeader($senderBatchHeader)
->addItem($senderItem1)
->addItem($senderItem2);
;
How do I add items inside the loop?
EDIT:
Error:
PayPalConnectionException in PayPalHttpConnection.php line 180:
Got Http response code 400 when accessing https://api.sandbox.paypal.com/v1/payments/payouts?.
Thankyou.
I managed to fix the issue by changing the $senderBatchId value to just:
uniqid()
instead of:
uniqid() . microtime(true)
Paypal REST API does not like it that way for some reason. If a better programmer than I can explain this I will mark his/her answer are correct.
I have a internal site which uses php to look through my msql customer database. Find any customers which do not have lat and lng fields filled in. Grab the postcodes and geocode them posting the lat and lng back to my database and plot the customers on the map. This is done by a cron job once a day. This worked fine using v.2 of google api. Since march or april its stopped. Im guessing because of v.3.
Jist my jl_jobscoordinates.cron.php file searches through the database picking up all the postcodes for empty lat and lng fields. Then calls a function from my geocode.class.php called doGeocode which uses xml to put togther and find results and save the lat and lng. Inside the geocodeclass it refers to a m_url which is the googleapi url which is saved inside my config file. I have updated this url to the new v.3 url which is http://maps.googleapis.com/maps/api/geocode/xml?address=%s&sensor=false. My map is back up and running, just nothing will geocode.
I will paste the two files jl_jobscooedinates.cron.php and geocode.class.php. I have commented out the old xml in the geocode which used to work with the old url.
The results of my cron is that it is not getting coordinates. e.g. -- [3-2013] Google could not find this Postcode: [COO041] Test Company Name, Oxfordshire OX26 4SS
jl_jobcoordinates.cron.php
require_once("../includes/config.php");
require_once(_PATH_JMS."/classes/session.class.php");
require_once(_PATH_JMS."/classes/db.class.php");
require_once(_PATH_JMS."/classes/lib.class.php");
require_once(_PATH_JMS."/classes/security.class.php");
require_once(_PATH_JMS."/classes/emails.class.php");
require_once(_PATH_JMS."/classes/geocode.class.php");
require_once(_PATH_JMS."/services/actiontrail.ds.php");
require_once(_PATH_JMS."/services/jobsdue.ds.php");
//-----------------------------------------------------
// Main Object Instances - Initialize what we require
//-----------------------------------------------------
$DB = new DB();
$Security = new Security($DB->i_db_conn);
$Lib = new Lib();
$Session = new Session();
$ActionTrail = new ActionTrail($DB, $Session, $Security);
$JobsDue = new JobsDue($DB, $Session, $Security, $ActionTrail);
$Geocode = new Geocode($Session, $Security);
$Emails = new Emails($DB, $Session, $Security);
//-----------------------------------------------------
// Save as a valid system user
//-----------------------------------------------------
$Session->save('USR_AUTH',_CRON_USER_NAME);
$Session->save('USR_PASS',_CRON_USER_PASS);
$Session->save('USR_IS_EMPLOYED', '1');
$Session->save('CONS',$Session->get('USR_AUTH'));
//-----------------------------------------------------
// Postcodes to Ignore - we cannot geocode these
//-----------------------------------------------------
$m_ignore = array("IRL","IRELAND","IRE","ITA","USA","BEL","EGY","GER","FR","FRA","HOL","POL");
//-----------------------------------------------------
// Get Jobs Due for all consultants for this year and next
//-----------------------------------------------------
$mY = (int) date("Y");
//-----------------------------------------------------
// Find t-cards without lat & lng
//-----------------------------------------------------
$m_errors = array();
for ($y=$mY;$y<=$mY+1;$y++)
{
for ($i=1;$i<=12;$i++)
{
$mM = (int) $i;
//echo "<br> mM =".$mM ." i =".$i;
$mJobs = $JobsDue->getAllJobsDue('%',$mM,$y,'%',NULL,NULL,FALSE); /* DON'T GET MISSED JOBS AS WE WILL START FROM JAN */
//echo "<br>mJobs =".$mJobs;
foreach ($mJobs as $row)
{
$m_postcode = $Lib->lib_str_clean(trim($row->postcode)); //this loops through each of the records and gets the post codes. m_postcodes are the postcodes found
echo "<br>m_postcode =".$m_postcode;
if (($row->latlngexists == 1)||(in_array($m_postcode,$m_ignore))||(in_array($row->card_id,$m_ignore))||(strlen($m_postcode)<=0)) continue;
if ($Lib->lib_ispostcode($m_postcode)) {
$m_coordinates = $Geocode->doGeocode($m_postcode);
echo "<br>m_coords =".$m_coordinates;//nothing displayed
if ($m_coordinates != NULL) {
$DB->setGeoTCard($row->card_id,$m_coordinates['lat'],$m_coordinates['lng']);
} else {
$m_err_desc = sprintf("[%s-%s] Google could not find this Postcode",$mM,$y);
$m_error = array(
"err_desc" => $m_err_desc,
"err_code" => $row->client_code,
"err_comp" => $row->title,
"err_depo" => $row->description,
"err_post" => $m_postcode
);
$m_errors[] = $m_error;
$m_ignore[] = $row->card_id;
}
sleep(_GEOCODE_PAUSE);
} else {
$m_err_desc = sprintf("[%s-%s] Postcode is invalid please check",$mM,$y);
$m_error = array(
"err_desc" => $m_err_desc,
"err_code" => $row->client_code,
"err_comp" => $row->title,
"err_depo" => $row->description,
"err_post" => $m_postcode
);
$m_errors[] = $m_error;
$m_ignore[] = $row->card_id;
}
}
}
}
if (count($m_errors) > 0) {
$Emails->doGeocodeErrNotify($m_errors);
}
geocode.class.php
class Geocode {
private $m_session = NULL;
private $m_security = NULL;
private $m_session_user;
private $m_session_pass;
private $m_key = _GMAP_KEY;
private $m_url = _GMAP_URL;
private $m_res = Array();
public function __construct($p_session,$p_security)
{
$this->m_session = $p_session;
$this->m_security = $p_security;
$this->m_session_user = $this->m_session->get('USR_AUTH');
$this->m_session_pass = $this->m_session->get('USR_PASS');
if ($this->m_security->doLogin($this->m_session_user,$this->m_session_pass) <= 0)
{
return NULL;
die;
}
}
public function doGeocode($p_postcode)
{
try {
// //$xml = new SimpleXMLElement(sprintf($this->m_url,$p_postcode,$this->m_key),0,TRUE); //OLD FOR V.2
$xml = new SimpleXMLElement(sprintf($this->m_url,$p_postcode),0,TRUE);
} catch (Exception $e) {
echo sprintf('Caught exception: %s', $e->getMessage());
return NULL;
die;
}
$st = $xml->Response->Status->code;
if (strcmp($st, "200") == 0)
{
$co = $xml->Response->Placemark->Point->coordinates;
$cs = preg_split("/[\s]*[,][\s]*/", $co);
$this->m_res = Array(
"lng" => $cs[0],
"lat" => $cs[1],
"alt" => $cs[2]
);
return $this->m_res;
} else {
return NULL;
}
}
}
I would really appriciate if someone could help me please. Im guessing its something to do with the new url in my config file and the current xml not set properly for the sensor??
My geocode stuff is still working fine just like this don't forget to use your own personal API key!
/**
* Geocode postcode to get long/lat used when adding suppliers and sites
* #param - $postcode - string - Input post code to geocode
* #return - $lat,$long - array - array containing latitude coords
*/
function geocode($postcode) {
$postcode = urlencode(trim($postcode)); // post code to look up in this case status however can easily be retrieved from a database or a form post
//$request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$postcode."&sensor=false"; // the request URL you'll send to google to get back your XML feed
define("MAPS_HOST", "maps.google.co.uk");
define("KEY", "YOUR API KEY HERE");
$base_url = "http://" . MAPS_HOST . "/maps/geo?output=xml" . "&key=" . KEY;
$request_url = $base_url . "&q=" . $postcode;
$xml = simplexml_load_file($request_url);
$status = $xml->Response->Status->code;
if (strcmp($status, "200") == 0) {
// Successful geocode
$geocode_pending = false;
$coordinates = $xml->Response->Placemark->Point->coordinates;
$coordinatesSplit = explode(",", $coordinates);
// Format: Longitude, Latitude, Altitude
return array("lat"=>$coordinatesSplit[1],"long"=>$coordinatesSplit[0]);
} else {
return array("lat"=>0,"long"=>0);
}
}
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 ;)