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

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.

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 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.

How to edit Magento current logged user details via php code

$session = Mage::getSingleton('customer/session');
$customer_id = $session->getId();
$customer_data = Mage::getModel('customer/customer')->load($customer_id);
print_r($customer_data);
Through this code ican get user details
I need to know How to edit the user details like address,password ..etc in the same Way using Php codes
Thanks all
for Password you can set using $customer_id
$password = 'Any Things'
$customer = Mage::getModel('customer/customer')->load($customer_id);
$customer->setPassword($password);
$customer->save();
For Edit address you have to load address model
For Example if you want to edit billing Address :
$customer = Mage::getModel('customer/customer')->load($customer_id);
$address = $customer->getDefaultBilling();
$address->setFirstname("Test");
$address->save();
OR :
using address id get from customer object :
$address = Mage::getModel('customer/address')->load($customerAddressId);
$address->setFirstname("Test");
$address->save();
You can use php magic get and set methods
Suppose to set password you can use $customer_data->setPassword('1234567');
$customer_data->save();
For customer address
$_custom_address = array (
'firstname' => 'firstname',
'lastname' => 'lastname',
'street' => array (
'0' => 'Sample address part1',
'1' => 'Sample address part2',
),
'city' => 'city',
'region_id' => '',
'region' => '',
'postcode' => '31000',
'country_id' => 'US',
'telephone' => '0038531555444',
);
$customAddress = Mage::getModel('customer/address')
$customAddress->setData($_custom_address)
->setCustomerId($customer->getId())
->setIsDefaultBilling('1')
->setIsDefaultShipping('1')
->setSaveInAddressBook('1');
try {
$customAddress->save();
}
catch (Exception $ex) {
//Zend_Debug::dump($ex->getMessage());
}
For more info http://inchoo.net/ecommerce/magento/programming-magento/programatically-create-customer-and-order-in-magento-with-full-blown-one-page-checkout-process-under-the-hood/
You can use methods of Mage_Customer_Model_Customer class:
$customerSession = Mage::getSingleton('customer/session');
$customerModel = Mage::getModel('customer/customer')->load($customerSession->getId());
$customerModel->changePassword('new_password');

Magento: Problems in creating order programatically

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

Categories