How to create order programmatically logged in customer? - php

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.

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.

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.

Create a customer address to already exist customer - Magento

I'm trying create programmatically a new address to customers that was imported a some time ago for me.
My Code:
//All variables about customer address info are filled
$customerModel = Mage::getModel('customer/customer');
$customer = $customerModel->setWebsiteId(1)->loadByEmail($_email);
if($customer->getId()) {
$addressData = array (
'firstname' => $customer->getFirstname(),
'lastname' => $customer->getLastname(),
'street' => "$_s1
$_s2
$_s3
$_s4",
'city' => $_city,
'country_id' => 'BR',
'region_id' => $_regionid,
'postcode' => $_cep,
'telephone' => $_tel,
'celular' => $_cel,
'is_default_billing' => 1,
'is_default_shipping' => 1
);
$address = Mage::getModel('customer/address');
$address->addData($addressData);
$customer->addAddress($address);
try {
print_r($addressData);
$customer->save();
}
catch (Exception $e) {
}
}
Object loaded '$customer' isnt what I need: a full customer object.
Any Idea?
You have to save customer address in different way, following is address saving code.
$customerAddress = Mage::getModel('customer/address');
$customerAddress->setData($addressData)
->setCustomerId($customer->getId())
->setSaveInAddressBook('1');
$customerAddress->save();
The full code will look like:
$customerModel = Mage::getModel('customer/customer');
$customer = $customerModel->setWebsiteId(1)->loadByEmail($_email);
if($customer->getId()) {
$addressData = array (
'firstname' => $customer->getFirstname(),
'lastname' => $customer->getLastname(),
'street' => "$_s1
$_s2
$_s3
$_s4",
'city' => $_city,
'country_id' => 'BR',
'region_id' => $_regionid,
'postcode' => $_cep,
'telephone' => $_tel,
'celular' => $_cel,
'is_default_billing' => 1,
'is_default_shipping' => 1
);
$customerAddress = Mage::getModel('customer/address');
$customerAddress->setData($addressData)
->setCustomerId($customer->getId())
->setSaveInAddressBook('1');
$customerAddress->save();
//And reload customer object
$customer = Mage::getModel('customer/customer')->load($customer->getId());
//Check customer data
print_r($customer->getData());
//Check addresses
foreach($customer->getAddresses() as $address)
{
print_r($address);
}
}

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 : Add customer default billing address

I am trying to import the customers into my new magento installation from an old site and want to set customer address as magento customer default billing address i hvae tried
$customer = $this->getCustomerModel();
$address = Mage::getModel('customer/address');
$customer->addAddress($results[0]['address']); //this says trying to save invalide object
$address ->addAddress($results[0]['address']); //this says undefined method
$results[0]['address'] this field contains the street address i have also the city,state, zip,postcode
Any idea about how can i set my customer address as its default billing or shipping address..
Well I have found it with help of Anoop sir.
$_custom_address = array (
'firstname' => 'Branko',
'lastname' => 'Ajzele',
'street' => array (
'0' => 'Sample address part1',
'1' => 'Sample address part2',
),
'city' => 'Osijek',
'region_id' => '',
'region' => '',
'postcode' => '31000',
'country_id' => 'HR', /* Croatia */
'telephone' => '0038531555444',
);
$customAddress = Mage::getModel('customer/address');
//$customAddress = new Mage_Customer_Model_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());
}

Categories