Magento: Problems in creating order programatically - php

I am creating a magento extension, in which i need to create the orders programatically from the cart. I am using the following code for this purpose. But i can't get it to work. Any help would be appreciated.
// Check whether the product could be loaded
if(isset($_POST['create_order'])){
// Get the customer model
$customer = Mage::getModel('customer/customer');
// Set the website id associated with the customer
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
if($_POST['customer'] == 'exist')
$email = $_POST['mageUser']['email'];
else
$email = $_POST['mageUser']['email_id'];
// Try to load the customer by email
$customer->loadByEmail($email);
// Check whether the customer not exists
if(!$customer->getId())
{
// Create the customer
$customer->setEmail($email);
$customer->setFirstname($_POST['mageUser']['first_name']);
$customer->setLastname($_POST['mageUser']['last_name']);
$customer->save();
$fname = $_POST['mageUser']['first_name'];
$lname = $_POST['mageUser']['last_name'];
}
else {
$fname = $customer->getFirstname();
$lname = $customer->getLastname();
}
// Set the esstial order data
$orderData = array(
'currency' => 'USD',
'account' => array(
'group_id' => Mage_Customer_Model_Group::NOT_LOGGED_IN_ID,
'email' => $email
),
'billing_address' => array(
'firstname' => $fname,
'lastname' => $lname,
'street' => 'pos',
'city' => 'Pos',
'country_id' => '54',
'region_id' => 'BW',
'postcode' => 'pos',
'telephone' => 'pos',
),
'comment' => array(
'customer_note' => "Order placed by point of sales\n"
),
'send_confirmation' => false
);
// Set the shipping address to the billing address
$orderData['shipping_address'] = $orderData['billing_address'];
// Set the payment method
$paymentMethod = 'pay';
// Set the shipping method
$shippingMethod = 'freeshipping_freeshipping';
// Get the backend quote session
$quoteSession = Mage::getSingleton('adminhtml/session_quote');
// Set the session store id
$quoteSession->setStoreId(Mage::app()->getStore('default')->getId());
// Set the session customer id
$quoteSession->setCustomerId($customer->getId());
// Get the backend order create model
$orderCreate = Mage::getSingleton('adminhtml/sales_order_create');
// Import the data
$orderCreate->importPostData($orderData);
// Calculate the shipping rates
$orderCreate->collectShippingRates();
// Set the shipping method
$orderCreate->setPaymentMethod($paymentMethod);
// Set the payment method to the payment instance
$orderCreate->getQuote()->getPayment()->addData(array('method' => $paymentMethod));
// Set the shipping method
$orderCreate->setShippingMethod($shippingMethod);
// Set the quote shipping address shipping method
$orderCreate->getQuote()->getShippingAddress()->setShippingMethod($shippingMethod);
// Add the product
$quote = Mage::getSingleton('checkout/session')->getQuote();
$cartItems = $quote->getAllVisibleItems();
$prd = array();
foreach ($cartItems as $item) {
$prd[$item->getId()] = array('qty' => $item->getQty());
}
$orderCreate->addProducts($prd);
//print_r($orderCreate); exit();
// Initialize data for price rules
$orderCreate->initRuleData();
// Save the quote
$orderCreate->saveQuote();
// Create the order
$order = $orderCreate->createOrder();
$order->setData('state', "complete");
$order->setStatus("complete");
$history = $order->addStatusHistoryComment('Order marked as complete automatically.', false);
$history->setIsCustomerNotified(false);
$order->save();
}
It shows this error message when i turn on the developer mode
#0 /home/seat2/public_html/Projects/MagentoPos/Repo/WebApp/app/code/core/Mage/Adminhtml/Model/Sales/Order/Create.php(1614): Mage::throwException('')
#1 /home/seat2/public_html/Projects/MagentoPos/Repo/WebApp/app/code/core/Mage/Adminhtml/Model/Sales/Order/Create.php(1508): Mage_Adminhtml_Model_Sales_Order_Create->_validate()
#2 /home/seat2/public_html/Projects/MagentoPos/Repo/WebApp/app/code/local/Nettantra/Pos/controllers/IndexController.php(210): Mage_Adminhtml_Model_Sales_Order_Create->createOrder()
#3 /home/seat2/public_html/Projects/MagentoPos/Repo/WebApp/app/code/core/Mage/Core/Controller/Varien/Action.php(419): Nettantra_Pos_IndexController->createorderAction()
#4 /home/seat2/public_html/Projects/MagentoPos/Repo/WebApp/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(250): Mage_Core_Controller_Varien_Action->dispatch('createorder')
#5 /home/seat2/public_html/Projects/MagentoPos/Repo/WebApp/app/code/core/Mage/Core/Controller/Varien/Front.php(176): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
#6 /home/seat2/public_html/Projects/MagentoPos/Repo/WebApp/app/code/core/Mage/Core/Model/App.php(354): Mage_Core_Controller_Varien_Front->dispatch()
#7 /home/seat2/public_html/Projects/MagentoPos/Repo/WebApp/app/Mage.php(683): Mage_Core_Model_App->run(Array)
#8 /home/seat2/public_html/Projects/MagentoPos/Repo/WebApp/index.php(87): Mage::run('', 'store')
#9 {main}

$productModel = Mage::getModel('catalog/product');
$productId = $productModel->getIdBySku($sku);
$product = $productModel->load($productId);
$cart = Mage::getModel('checkout/cart');
$cart->init();
$cart->addProduct($product, array('qty' => $quantity));
$cart->save();
**You will need to define $sku and $quantity
This will create a cart and add a product too it; hopefully this points you in the right directions

Related

Rest API - Import JSON file with products to Drupal 8 and create product nodes with that data

For a website I have to import products with a Rest API to a Drupal 8 webshop. Here is the documentation of the API: https://www.floraathome.nl/api-documentatie/v1/
I succesfully got the data from all products using:
https://api.floraathome.nl/v1/products/get?apitoken=[MY_TOKE]&type=json
I also succeeded printing out some data from it in a PHP file:
<?php
$url = 'https://api.floraathome.nl/v1/products/get?apitoken=[MY_TOKE]&type=json';
$json = file_get_contents($url);
$retVal = json_decode($json, TRUE);
foreach($retVal['data'] as $retV){
echo $retV['dutchname']."<br>";
echo $retV['purchaseprice']."<br>";
echo $retV['promotionaltext']."<br><br>";
}
I have no experience with API's or anything like it. But now I would like to be able to import the data from the API into Drupal 8, as products.
What would be my best solution to approach this?
Thanks in advance,
Mike
This is how I would do it, I hope it works for you.
For store creation:
<?php
// The store type. Default is 'online'.
$type = 'online';
// The user id the store belongs to.
$uid = 1;
// The store's name.
$name = 'My Store';
// Store's email address.
$mail = 'admin#example.com';
// The country code.
$country = 'US';
// The store's address.
$address = [
'country_code' => $country,
'address_line1' => '123 Street Drive',
'locality' => 'Beverly Hills',
'administrative_area' => 'CA',
'postal_code' => '90210',
];
// The currency code.
$currency = 'USD';
// If needed, this will import the currency.
$currency_importer = \Drupal::service('commerce_price.currency_importer');
$currency_importer->import($currency);
$store = \Drupal\commerce_store\Entity\Store::create([
'type' => $type,
'uid' => $uid,
'name' => $name,
'mail' => $mail,
'address' => $address,
'default_currency' => $currency,
'billing_countries' => [
$country,
],
]);
// If needed, this sets the store as the default store.
$store_storage = \Drupal::service('entity_type.manager')->getStorage('commerce_store');
$store_storage->markAsDefault($store);
// Finally, save the store.
$store->save();
For variation (indicated by $variation do something like
<?php
$price = new \Drupal\commerce_price\Price('24.99', 'USD');
$variation = ProductVariation::create([
'type' => 'default', // The default variation type is 'default'.
'sku' => 'test-product-01', // The variation sku.
'status' => 1, // The product status. 0 for disabled, 1 for enabled.
'price' => $price,
]);
$variation->save();
Finally, for the product:
<?php
use \Drupal\commerce_product\Entity\Product;
use \Drupal\commerce_product\Entity\ProductVariation;
$req=\Drupal::httpClient()->get("https://api.floraathome.nl/v1/products/get?apitoken=[MY_TOKE]&type=json");
$res=json_decode($req);
foreach($res['data'] as $r) {
$product = Product::create(['type' => 'default', 'variations' => $variation, 'stores' => $sid]);
$product->set('title', $r['dutchname'];
...
...
...
$product->save();
}
I hope you get the idea.
Note: Needless to say, I had to make variables/values up as I don't have access to the API.

How to set Tax and Shipping fees in Laravel Paypal package

Recently i'm working on a laravel project which i choose to use srmklive/laravel-paypal as my paypal payment gateway plugin, but i found that i cannot add Tax and shipping fees, i have read the readme.doc multiple time and also check the paypal documentation, but i still confused on how to add the tax and shipping fees.
Did any one know how to add these data when setExpresssCheckout?
here is my code:
$provider = new ExpressCheckout;
$provider = PayPal::setProvider('express_checkout');
$itemsArr = $data = [];
// add items
foreach ($order->orderProduct as $order_product) {
array_push($itemsArr, [
'name' => $order_product->product->name,
'price' => $order_product->price,
'qty' => $order_product->quantity
]);
}
// add shipping fees
array_push($itemsArr, [
'name' => "Shipping Method : ".$order->shipping_method,
'price' => $order->shipping_fees,
'qty' => 1
]);
$data["items"] = $itemsArr;
$data['invoice_id'] = 1;
$data['invoice_description'] = "Order #1 Invoice";
$data['return_url'] = url('/payment/success');
$data['cancel_url'] = url('/cart');
$total = 0;
foreach($data['items'] as $item) {
$total += $item['price']*$item['qty'];
}
$data['total'] = $total;
$options = [
'BRANDNAME' => 'Ulife',
'LOGOIMG' => asset("images\ulifelanding.png"),
'CHANNELTYPE' => 'Merchant'
];
$response = $provider->setCurrency('MYR')->addOptions($options)->setExpressCheckout($data);
Ps: i also asked on the github, but still confused.
I don't know who still needs an answer for this question, but I share ("srmklive/paypal": "~1.0").
go to ExpressCheckout.php and go to setExpressCheckout add this :
'PAYMENTREQUEST_0_AMT' => $data['total']+$data['tax'],
'PAYMENTREQUEST_0_TAXAMT' => $data['tax'],
and you checkoutData put now:
'tax'=>xx
call your provider with addOptions:
example:
$options = [
'BRANDNAME' => 'MyBrand',
'LOGOIMG' => 'https://example.com/mylogo.png',
'CHANNELTYPE' => 'Merchant',
];
$provider->addOptions($options)->setExpressCheckout($checkoutData)

Magento1.8 - What is the best script for creating order?

Iam new in magento , i want to create script for creating orders
i have searched for scripts alot and i get this:
<?php
require_once 'app/Mage.php';
Mage::app();
$quote = Mage::getModel('sales/quote')
->setStoreId(Mage::app()->getStore('default')->getId());
// for guesr orders only:
$quote->setCustomerEmail('customer#example.com');
// add product(s)
$product = Mage::getModel('catalog/product')->load(431);
$buyInfo = array(
'qty' => 1,
// custom option id => value id
// or
// configurable attribute id => value id
);
$quote->addProduct($product, new Varien_Object($buyInfo));
$addressData = array(
'firstname' => 'Test',
'lastname' => 'Test',
'street' => 'Sample Street 10',
'city' => 'Somewhere',
'postcode' => '123456',
'telephone' => '123456',
'country_id' => 'SA',
);
$billingAddress = $quote->getBillingAddress()->addData($addressData);
$shippingAddress = $quote->getShippingAddress()->addData($addressData);
$shippingAddress->setCollectShippingRates(true)->collectShippingRates()
->setShippingMethod('freeshipping_freeshipping')
->setPaymentMethod('cashondelivery');
$quote->getPayment()->importData(array('method' => 'cashondelivery'));
$quote->collectTotals()->save();
$service = Mage::getModel('sales/service_quote', $quote);
$service->submitAll();
$order = $service->getOrder();
printf("Created order %s\n", $order->getIncrementId());
?>
But when i run this script it give me error "page isn’t working".
Can you please helping me fixing this or give me script that create orders.
Note "i run this script through "www.site.com/createorder.php"
Thanks
I tried this once and it works :
<?php
include '../app/Mage.php';
Mage::app();
// Need for start the session
Mage::getSingleton('core/session', array('name' => 'frontend'));
try {
$product_ids = array(
$_GET['product_id_1'],
$_GET['product_id_2'],
$_GET['product_id_3'],
$_GET['product_id_4']
);
for($i=0;$i<4;$i++)
{
addToCart($product_ids[$i]);
}
/*addToCart($product_id_1); */
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
Mage::getSingleton('core/session')->addSuccess('Product added successfully');
header('Location: ' .Mage::getBaseURl(). 'checkout/cart/');
} catch (Exception $e) {
echo $e->getMessage();
}
function addToCart($product_id)
{
$qty = '1';
$product = Mage::getModel('catalog/product')->load($product_id);
$cart = Mage::getModel('checkout/cart');
$cart->init();
$cart->addProduct($product, array('qty' => $qty));
$cart->save();
return true;
}
?>
The link should be given four parameters in the form of product_id_1 and so on. You can change that accordingly.

How to create order programmatically logged in customer?

Currently I make php script to generate order not logged in customer but i want to use this script for logged in customer dynamically for logged in customer my code is
$quote = Mage::getModel('sales/quote')
->setStoreId(Mage::app()->getStore('default')->getId());
// for guest orders only:
$quote->setCustomerEmail('customer#email.com');
//}
// add product(s)
$product = Mage::getModel('catalog/product')->load(1307,1305);
$buyInfo = array(
'qty' => 1,
// custom option id => value id
// or
// configurable attribute id => value id
);
$quote->addProduct($product, new Varien_Object($buyInfo));
//$quote->addProduct($product2, new Varien_Object($buyInfo));
$addressData = array(
'firstname' => 'Test',
'lastname' => 'Test',
'street' => 'Sample Street 10',
'city' => 'Somewhere',
'postcode' => '123456',
'telephone' => '123456',
'country_id' => 'US',
'region_id' => 12, // id from directory_country_region table
);
$billingAddress = $quote->getBillingAddress()->addData($addressData);
$shippingAddress = $quote->getShippingAddress()->addData($addressData);
$shippingAddress->setCollectShippingRates(true)->collectShippingRates()
->setShippingMethod('flatrate_flatrate')
->setPaymentMethod('checkmo');
$quote->getPayment()->importData(array('method' => 'checkmo'));
$quote->collectTotals()->save();
echo "quote save";
$service = Mage::getModel('sales/service_quote', $quote);
$service->submitAll();
echo "order save";
$order = $service->getOrder();
printf("Created order %s\n", $order->getIncrementId());
}catch(Exception $e){
print_r($e->getMessage());
}
this script is create order programmatically for not loggedin customer
Arvind,
Follow the same quote object. Use below methods in quote object to create an order for logged in customer.
$quote->setCustomerId()->setCustomerIsGuest(false)->setCustomerFirstname()->setCustomerLastname()->setCustomerGroupId();
This will create the order for the provided customer information. Hope this will help.

Magento add product to cart from a external file doesn't work

i have a problem with Magento's addProduct() function. I have the following code:
<?php
// Mage init
include_once '../app/Mage.php';
umask(0);
Mage::init('default');
Mage::getSingleton('core/session', array('name' => 'frontend'));
// Get customer session
$session = Mage::getSingleton('customer/session');
// Get cart instance
$cart = Mage::getSingleton('checkout/cart');
$cart->init();
// Add a product with custom options
$productId = 11348;
$productInstance = Mage::getModel('catalog/product')->load($productId);
$param = array(
'product' => $productInstance->getId(),
'qty' => 1,
'options' => array(
528 => '1756', // Custom option with id: 528
527 => '1753', // Custom option with id: 527
526 => '1751' // Custom option with id: 526
)
);
$request = new Varien_Object();
$request->setData($param);
$cart->addProduct($productInstance, $request);
// update session
$session->setCartWasUpdated(true);
// save the cart
$cart->save();
?>
It worked yesterday so include and $param are rigth but now it doesn't work.
You also can add this product to cart inside the shop so the product exist and it's in stock.
This code doesn't seems to have any error but it doesn't add product to cart.
Thanks for help.
<?php
require_once('app/Mage.php');
umask(0);
Mage::app('admin');
$product_model = Mage::getModel('catalog/product');
$my_product_sku = 'test';
$my_product_id = $product_model->getIdBySku($my_product_sku);
$my_product = $product_model->load($my_product_id);
$qty_value = 13;
$cart = Mage::getModel('checkout/cart');
$cart->init();
$cart->addProduct($my_product, array('qty' => $qty_value));
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
?>
try with adding form key and uenc field
$param = array(
'product' => $productInstance->getId(),
'form_key'=>$form_key_put_here,
'uenc' =>Mage::app()->getRequest()->getParam('uenc', 1),
'qty' => 1,
'options' => array(
528 => '1756', // Custom option with id: 528
527 => '1753', // Custom option with id: 527
526 => '1751' // Custom option with id: 526
));
hope this will help.

Categories