2013-11-18 2 views
2

У меня возникли проблемы с получением моего сценария для создания заказа на моем сайте, где используется Magento 1.7. Ошибка я получаю «пожалуйста, укажите способ доставки» более детальНевозможно установить способ доставки в Magento order create script

blockquote Fatal error: Uncaught exception 'Mage_Core_Exception' with message 'Please specify a shipping method.' in /home/mysite/public_html/app/Mage.php:594 Stack trace: #0 /home/mysite/public_html/app/code/core/Mage/Sales/Model/Service/Quote.php(303): Mage::throwException('Please specify ...') #1 /home/mysite/public_html/app/code/core/Mage/Sales/Model/Service/Quote.php(222): Mage_Sales_Model_Service_Quote->_validate() #2 /home/mysite/public_html/app/code/core/Mage/Sales/Model/Service/Quote.php(238): Mage_Sales_Model_Service_Quote->submitNominalItems() #3 /home/mysite/public_html/apitest/magento_order_create.php(82): Mage_Sales_Model_Service_Quote->submitAll() #4 {main} thrown in /home/mysite/public_html/app/Mage.php on line 594

Я пытаюсь использовать сценарий ниже, чтобы создать заказ и Я передаю артикулы и количество в должности с другой страницы. `

<?php 
// Link Mage Class 
require ('../app/Mage.php'); 


// Initialize Magento framework 
Mage::app('mysite'); 


//create a cart 
$quote = Mage::getModel('sales/quote') 
->setStoreId(Mage::app()->getStore('mysite')->getId()); 


//Get Customer by Id 
$customer = Mage::getModel('customer/customer')->load('1'); 

//attach customer to cart 
$quote->assignCustomer($customer); 

//attach products 
foreach ($_POST as $sku=>$qty) 
    { 

     $product =  Mage::helper('catalog/product')->getProduct($sku,Mage::app()->getStore()->getId(), 'sku'); 
    $buyInfo = array(
     'qty' => $qty, 
     // custom option id => value id 
     // or 
     // configurable attribute id => value id 
     ); 
    $quote->addProduct($product, new Varien_Object($buyInfo)); 

} 
//get and set customer billing address 
//need to work on this encase we use diffrent billing and shipping addresses 
$addressData = Mage::getModel('customer/address')->load('1'); 


$billingAddress = $quote->getBillingAddress()->addData($addressData); 
$shippingAddress = $quote->getShippingAddress()->addData($addressData); 

// set shipping and payment methods. assumes freeshipping and check payment 
// have been enabled. 
/* 
$shippingAddress->setCollectShippingRates(true)->collectShippingRates() 
     ->setShippingMethod('freeshipping_freeshipping') 
     ->setPaymentMethod('checkmo'); 
*/ 

// THIS IS WHERE THE ERROR SEEMS TO BE 
$quote->getShippingAddress()->setShippingMethod('freeshipping_freeshipping'); 
$quote->getShippingAddress()->setCollectShippingRates(true); 
$quote->getShippingAddress()->collectShippingRates(); 

//set payment method  
$quote->getPayment()->importData(array('method' => 'checkmo')); 


//save cart and check out 
$quote->collectTotals()->save(); 


$service = Mage::getModel('sales/service_quote', $quote); 
$service->submitAll(); 
$order = $service->getOrder(); 

printf("Created order %s\n", $order->getIncrementId()); 
` 

выше сценарий изначально пришли из http://pastebin.com/8cft4d8v и он работает как шарм на моей тестовой среде (также 1.7). Я прокомментировал оригинальный код метода доставки и сломался в отдельные строки. На сайте есть два сайта и два магазина, я убедился, что бесплатная доставка включена на бэкэнд и проверена, что она появляется при запуске этого скрипта.

<?php 

// Link Mage Class 
require ('../app/Mage.php'); 

// Initialize Magento framework 
Mage::app('mysite'); 

$methods = Mage::getSingleton('shipping/config')->getActiveCarriers(); 

var_dump($methods); 

Я уверен, что адрес установлен правильно, если я эхо выхожу на экран, на котором находится адрес.

Я пробовал читать документацию, глядя на другой пример кода и меняя его части, чтобы увидеть, могу ли я установить способ доставки, но не повезло.

ответ

6

Ну, главное решение похоже на то, что было решено во время перезагрузки сервера. Но я также опубликую окончательный сценарий, который мы будем использовать. По какой-то причине установка способа доставки на объект цитаты, похоже, не работает, поэтому я также вернулся к «оригинальному» сценарию, который я нашел на http://pastebin.com/8cft4d8v. Я также избавился от некоторых строк, которые, похоже, не имели никакого значения, если они существуют или нет. Надеюсь, что это может помочь кому-то вниз по линии

<?php 

// Link Mage Class 
require ('..\app\Mage.php'); 


// Initialize Magento framework 
Mage::app('my'); 

//create a cart 
$quote = Mage::getModel('sales/quote') 
    ->setStoreId(Mage::app()->getStore('default')->getId()); 


//Get Customer by Id 
$customer = Mage::getModel('customer/customer')->load('1'); 

//attach customer to cart 
$quote->assignCustomer($customer); 

//attach products 
foreach ($_POST as $sku=>$qty) 
{ 

    $product = Mage::helper('catalog/product')->getProduct($sku, Mage::app()->getStore()->getId(), 'sku'); 
    $buyInfo = array(
     'qty' => $qty, 
     // custom option id => value id 
     // or 
     // configurable attribute id => value id 
    ); 
    $quote->addProduct($product, new Varien_Object($buyInfo)); 

} 


$billingAddress = $quote->getBillingAddress()->addData(); 
$shippingAddress = $quote->getShippingAddress()->addData(); 

// set shipping and payment methods. assumes freeshipping and check payment 
// have been enabled. 
$shippingAddress->setCollectShippingRates(true)->collectShippingRates() 
     ->setShippingMethod('flatrate_flatrate'); 


$quote->getPayment()->importData(array('method' => 'checkmo')); 


//save cart and check out 
$quote->collectTotals()->save(); 



$service = Mage::getModel('sales/service_quote', $quote); 
$service->submitAll(); 
$order = $service->getOrder(); 

printf("Created order %s\n", $order->getIncrementId()); 
+0

я получаю: Uncaught ArgumentCountError: Слишком мало аргументов функционировать Varien_Object :: AddData(), 0 прошло –

Смежные вопросы