Magento create order programmatically with downloadable product - magento

I have been successful creating orders with a Custom controller and all works well. My issue is i need to add the ability to create orders with downloadable product. I would just like to be pointed on where to start.
Controller is handling all the set up and the order save. Is there a Action or something I need to hit for the customer to be able to access his/her downloads?

Try the below Code, please go threw comments.
<?php
require_once 'app/Mage.php';
Mage::app();
$customer = Mage::getModel("customer/customer")
->setWebsiteId(Mage::app()->getStore()->getWebsiteId())
->loadByEmail($data['email']);
if(!$customer->getId()) {
$customer->setEmail($email); //enter Email here
$customer->setFirstname($fname); //enter Lirstname here
$customer->setLastname($lname); //enter Lastnamre here
$customer->setPassword(password); //enter password here
$customer->save();
}
$storeId = $customer->getStoreId();
$quote = Mage::getModel('sales/quote')
->setStoreId($storeId);
$quote->assignCustomer($customer);
// add product(s)
$product = Mage::getModel('catalog/product')->load(186); //product id
/*$buyInfo = array(
'qty' => 1,
'price'=>0
// custom option id => value id
// or
// configurable attribute id => value id
);*/
$params = array();
$links = Mage::getModel('downloadable/product_type')->getLinks( $product );
$linkId = 0;
foreach ($links as $link) {
$linkId = $link->getId();
}
//$params['product'] = $product;
$params['qty'] = 1;
$params['links'] = array($linkId);
$request = new Varien_Object();
$request->setData($params);
//$quoteObj->addProduct($productObj , $request);
/* Bundled product options would look like this:
$buyInfo = array(
"qty" => 1,
"bundle_option" = array(
"123" => array(456), //optionid => array( selectionid )
"124" => array(235)
)
); */
//$class_name = get_class($quote);
//Zend_Debug::dump($class_name);
$quote->addProduct($product, $request);
$addressData = array(
'firstname' => 'Vagelis', //you can also give variables here
'lastname' => 'Bakas',
'street' => 'Sample Street 10',
'city' => 'Somewhere',
'postcode' => '123456',
'telephone' => '123456',
'country_id' => 'US',
'region_id' => 12, // id from directory_country_region table if it Country ID is IN (India) region id is not required
);
$billingAddress = $quote->getBillingAddress()->addData($addressData);
$shippingAddress = $quote->getShippingAddress()->addData($addressData);
/*$shippingAddress->setCollectShippingRates(true)->collectShippingRates()
->setShippingMethod('flatrate_flatrate')
->setPaymentMethod('checkmo');*/
/* Free shipping would look like this: */
$shippingAddress->setFreeShipping( true )
->setCollectShippingRates(true)->collectShippingRates()
->setShippingMethod('freeshipping_freeshipping')
->setPaymentMethod('checkmo'); /* shipping details is not required for downloadable product */
$quote->setCouponCode('ABCD'); // if required
/* Make Sure Your Check Money Order Method Is Enable */
/*if the product value is zero i mean free product then the payment method is free array('method' => 'free')*/
$quote->getPayment()->importData(array('method' => 'checkmo'));
$quote->collectTotals()->save();
$service = Mage::getModel('sales/service_quote', $quote);
$service->submitAll();
$order = $service->getOrder();
printf("Order Created Successfully %s\n", $order->getIncrementId());

Related

Magento - add product to cart with custom option using PHP

I am trying to add a product to the cart programmatically with some custom options. The item gets added to the cart correctly but none of the options ever get added. My code is:
require_once '../../app/Mage.php';
umask(0);
/* not Mage::run(); */
Mage::app('default');
Mage::getSingleton("core/session", array("name" => "frontend"));
$product_id = 2364;
$id_opt_value = 6072;
$final_opt_value = 6074;
$product = Mage::getModel('catalog/product')->load($product_id);
$cart = Mage::getModel('checkout/cart');
$cart->init();
$params = array(
'product' => $product_id,
'qty' => 1,
'options' => array(
$id_opt_value => '123456',
$final_opt_value => 'black gloss finish',
)
);
$cart->addProduct($product, $params);
$cart->save();
I have double checked and the option values are correct. I am using magento ce-1.9.0.0
Try to use Varien Object:
$request = new Varien_Object();
$request->setData($param);
$cart->addProduct($productInstance, $request);
Should work as well.

Magento: add configurable products to cart programmatically

How to add the child product to cart programmatically?
I've a child product SKU, I want to
Fetch the supper attributes like size and color id and values from the products,
Then fetch the parent product id,
Pass the super attributes on param with quantity, to add to function cart.
//$cart->addProduct($product1, $options);
Here, how to pass the supper attributes on the $option variable? Please help me!!!!
Try this. I think it may need some improvements but it works good in simple cases.
$_product = $this->getProduct();
$parentIds = Mage::getResourceSingleton('catalog/product_type_configurable')->getParentIdsByChild($_product->getId());
// check if something is returned
if (!empty(array_filter($parentIds))) {
$pid = $parentIds[0];
// Collect options applicable to the configurable product
$configurableProduct = Mage::getModel('catalog/product')->load($pid);
$productAttributeOptions = $configurableProduct->getTypeInstance(true)->getConfigurableAttributesAsArray($configurableProduct);
$options = array();
foreach ($productAttributeOptions as $productAttribute) {
$allValues = array_column($productAttribute['values'], 'value_index');
$currentProductValue = $_product->getData($productAttribute['attribute_code']);
if (in_array($currentProductValue, $allValues)) {
$options[$productAttribute['attribute_id']] = $currentProductValue;
}
}
// Get cart instance
$cart = Mage::getSingleton('checkout/cart');
$cart->init();
// Add a product with custom options
$params = array(
'product' => $configurableProduct->getId(),
'qty' => 1,
'super_attribute' => $options
);
$request = new Varien_Object();
$request->setData($params);
$cart->addProduct($configurableProduct, $request);
$session = Mage::getSingleton('customer/session');
$session->setCartWasUpdated(true);
$cart->save();
}
U can try.
$cart = Mage::getModel('checkout/cart');
$cart->init();
$productCollection = Mage::getModel('catalog/product')->load($productId);
$cart->addProduct($productCollection ,
array( 'product_id' => $productId,
'qty' => 1,
'options' => array( $optionId => $optionValue));
$cart->save();

Integrity constraint violation for key 'UNQ_CATALOG_PRODUCT_SUPER_ATTRIBUTE_PRODUCT_ID_ATTRIBUTE_ID'

I am creating simple products and then configurable product followed by associating simple products with configurable product. When I run the code for the first time, it works smoothly creating all simple products, configurable product and also an association. But, when I run that code again it says constraint violation. The ID that shows duplicated is the same product ID that was created the last time, when all process were ok.
My code is the following one.
$product_collection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('*');
$toinsertId = $product_collection->getLastItem()->getId() + 1;
$configurable_attribute = "art_print_sizes";
$attr_id = 133;
$simpleProducts = array();
$lowestPrice = 999999;
$attributes = Mage::getModel('catalogsearch/advanced')->getAttributes();
$attributeArray = array();
foreach ($attributes as $a) {
if ($a->getAttributeCode() == 'art_print_sizes') {
$count = 0;
foreach ($a->getSource()->getAllOptions(false) as $option) {
$option_id = $this->getOptionId("art_print_sizes", $option['label']);
$sku = 'SK_' . '500' . '_' . strval($count);
$sProduct = Mage::getModel('catalog/product');
$sProduct
->setTypeId(Mage_Catalog_Model_Product_Type::TYPE_SIMPLE)
->setWebsiteIds(array(1))
->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE)
->setTaxClassId(5)
->setAttributeSetId(9)
->setSku($sku)
// $main_product_data is an array created as part of a wider foreach loop, which this code is inside of
->setName($wholedata['name'] . " - " . $option['label'])
->setShortDescription($wholedata['short_description'])
->setDescription($wholedata['description'])
->setPrice(sprintf("%0.2f", $wholedata['attr_val'][$count]))
->setData($configurable_attribute, $option_id);
$sProduct->save();
array_push(
$simpleProducts,
array(
"id" => $sProduct->getId(),
"price" => $sProduct->getPrice(),
"attr_code" => 'art_print_sizes',
"attr_id" => $attr_id,
"value" => $option_id,
"label" => $option['label']
)
);
$count++;
}
}
}
$cProduct = Mage::getModel('catalog/product');
$productData = array(
'name' => 'Main configurable Tshirt',
'sku' => 'tshirt_sku',
'description' => 'Clear description about your Tshirt that explains its features',
'short_description' => 'One liner',
'weight' => 1,
'status' => '1',
'visibility' => '4',
'attribute_set_id' => 9,
'type_id' => 'configurable',
'price' => 1200,
'tax_class_id' => 0
);
foreach ($productData as $key => $value) {
$cProduct->setData($key, $value);
}
$cProduct->setStockData(
array(
'manage_stock' => 1,
'is_in_stock' => 1,
'qty' => 0,
'use_config_manage_stock' => 0
)
);
$cProductTypeInstance = $cProduct->getTypeInstance();
$attribute_ids = array(133);
$cProductTypeInstance->setUsedProductAttributeIds($attribute_ids);
$attributes_array = $cProductTypeInstance->getConfigurableAttributesAsArray();
foreach ($attributes_array as $key => $attribute_array) {
$attributes_array[$key]['use_default'] = 1;
$attributes_array[$key]['position'] = 0;
if (isset($attribute_array['frontend_label'])) {
$attributes_array[$key]['label'] = $attribute_array['frontend_label'];
} else {
$attributes_array[$key]['label'] = $attribute_array['attribute_code'];
}
}
$cProduct->setConfigurableAttributesData($attributes_array);
$dataArray = array();
foreach ($simpleProducts as $simpleArray) {
$dataArray[$simpleArray['id']] = array();
foreach ($attributes_array as $key => $attrArray) {
array_push(
$dataArray[$simpleArray['id']],
array(
"attribute_id" => $simpleArray['attr_id'][$key],
"label" => $simpleArray['label'][$key],
"is_percent" => 0,
"pricing_value" => $simpleArray['pricing_value'][$key]
)
);
}
}
$cProduct->setConfigurableProductsData($dataArray);
$cProduct->setCanSaveConfigurableAttributes(true);
$cProduct->setCanSaveCustomOptions(true);
$cProduct->save();
The Error is like this
Product ID 126 is already added in database in previous session. And previous session went well adding all necessary products.
Magento will not allow you to update configurable products. So for resolve it just add below code
if($productId){
$resource = Mage::getSingleton('core/resource');
$write = $resource->getConnection('core_write');
$table = $resource->getTableName('catalog/product_super_attribute');
$write->delete($table,"product_id = " . $productId);
}
before
$cProduct->setConfigurableAttributesData($attributes_array);
So your final code will be
if($productId){
$resource = Mage::getSingleton('core/resource');
$write = $resource->getConnection('core_write');
$table = $resource->getTableName('catalog/product_super_attribute');
$write->delete($table,"product_id = " . $productId);
}
$cProduct->setConfigurableAttributesData($attributes_array);
Note: Change $productId variable according to your code. You have to pass product id here.

Attach Image to Product with Drupal Api

I am trying to programatically add products to my drupal commerce store. So far I have been able to add products that contain basic information ( such as sku, title, and price ). How would I be able to add field data, such as images and other field types, using drupal's api.
The code I used to add the products is derived from the commerce_examples/product_example module.
<?php
/**
* #file product_example.module
* Demonstrates pricing hooks, etc.
*/
/**
* Implements hook_menu().
*
* Simply presents a page that will explain what this module is for.
* hook_menu() has nothing to do with the checkout page functionality.
*/
function product_example_menu() {
$items['commerce_examples/product_example'] = array(
'title' => 'Product Example',
'page callback' => 'drupal_get_form',
'page arguments' => array('product_example_info_page'),
'access callback' => TRUE,
);
return $items;
}
/**
* This form provides a way to interact with some of the example functions
* provided here.
*/
function product_example_info_page($form, &$form_state) {
$form['explanation'] = array(
'#type' => 'item',
'#markup' => t('This example demonstrates product creation and manipulation.'),
);
$form['product_creation'] = array(
'#type' => 'fieldset',
'#title' => t('Please create a product for use with this example'),
);
$types = commerce_product_types();
$form['product_creation']['product_type'] = array(
'#type' => 'select',
'#title' => t('Product type for product to be created'),
'#options' => drupal_map_assoc(array_keys($types)),
);
$form['product_creation']['title'] = array(
'#title' => t('Product title'),
'#type' => 'textfield',
'#default_value' => t('A dummy product for use with product_example'),
);
$form['product_creation']['price'] = array(
'#title' => t('Product price'),
'#type' => 'textfield',
'#description' => t('A price in decimal format, without a currency symbol'),
'#default_value' => '100.00',
);
$form['product_creation']['product_creation_submit'] = array(
'#type' => 'submit',
'#value' => t('Create product'),
'#submit' => array('product_example_product_creation_submit')
);
return $form;
}
/**
* Submit handler for creating a product.
*/
function product_example_product_creation_submit($form, &$form_state) {
$extras = array(
'sku' => 'product_example_' . drupal_hash_base64(microtime()),
'status' => TRUE,
'uid' => $GLOBALS['user']->uid,
'title' => $form_state['values']['title'],
);
// Use the product example's creation function to create a product.
$product_id = product_example_create_product($form_state['values']['product_type'], $form_state['values']['price'], $extras);
drupal_set_message(t('Created sample product with title !title and sku !sku', array('!title' => l($extras['title'], 'admin/commerce/products/' . $product_id), '!sku' => $extras['sku'])));
}
/**
* Create a product programmatically.
*
* This is stolen shamelessly from commerce_bpc. Thanks for the help here!
*
* #param $product_type
* (string) The name of the product type for which products should be created.
* #param $price
* Decimal amount of price. If additional fields need to be populated they
* can be populated in exactly the same way as the commerce_price field.
* #param $extras
* An array for the values of 'extra fields' defined for the product type
* entity, or patterns for these. Recognized keys are:
* - status
* - uid
* - sku
* - title
* Note that the values do NOT come in the form of complex arrays (as they
* are not translatable, and can only have single values).
* #return
* The ID of the created product.
*/
function product_example_create_product($product_type, $price, $extras) {
$form_state = array();
$form_state['values'] = array();
$form = array();
$form['#parents'] = array();
// Generate a new product object
$new_product = commerce_product_new($product_type);
$new_product->status = $extras['status'];
$new_product->uid = $extras['uid'];
$new_product->sku = $extras['sku'];
$new_product->title = $extras['title'];
$new_product->created = $new_product->changed = time();
//commerce_price[und][0][amount]
$price = array(LANGUAGE_NONE => array(0 => array(
'amount' => $price * 100,
'currency_code' => commerce_default_currency(),
)));
$form_state['values']['commerce_price'] = $price;
// Notify field widgets to save their field data
field_attach_submit('commerce_product', $new_product, $form, $form_state);
commerce_product_save($new_product);
return $new_product->product_id;
}
Using the same format the examples uses to add price data:
//commerce_price[und][0][amount]
$price = array(LANGUAGE_NONE => array(0 => array(
'amount' => $price * 100,
'currency_code' => commerce_default_currency(),
)));
I was able to add other field data, however I am still having trouble adding data to the field_productimage field that all commerce products come with by default.
I can suggest you about other fields data such as extra info related to product. You can add these fields to the product type from the UI or if you are creating product type programmatically then also you can do the same.
Add fields in your form to collect the data e.g -
$form['product_creation']['values'] = array(
'#title' => t('Some data'),
'#type' => 'textfield',
'#description' => t('Dummy data'),
);
Get those data in your function product_example_create_product() by $form_state().
Add them to $new_product object like
$new_product->field_name['und'][0]['value'] = $extras['values'];
Save the product, just like you are doing.
For the image, you will have to follow the method of file attachment. Like -
$file_path = drupal_realpath('image/product_image.png');
$file = (object) array(
'uid' => 1,
'uri' => $file_path,
'filemime' => file_get_mimetype($file_path),
'status' => 1,
);
// We save the file to the root of the files directory.
$file = file_copy($file, 'public://');
$new_product->product_image[LANGUAGE_NONE][0] = (array)$file;

How to add limit option in Magento API call

I am creating web service for my store. I am using magento API to collect product list from store. But it display all the 500 records. And i want it 25 records per page. What to add in API call? Or What filter will be apply for this?
//create soap object
$proxy = new SoapClient('http://localhsot/magento/api/soap/?wsdl');
// create authorized session id using api user name and api key
// $sessionId = $proxy->login('apiUser', 'apiKey');
$sessionId = $proxy->login('test_admin', '12345678');
$filters = array(
);
// Get list of product
$productlist = $proxy->call($sessionId, 'product.list', array($filters));
print_r($productlist );
that didn't work, can you limit it by id like:
$filters = array('id'=>array("gteq"=>1), 'id'=>array("lteq"=>1000));
that way you could add some paging?
I know this is an old question but I struggled with this. I've created my own SOAP API endpoint which does exactly the same as the default catalogProductList function but has an extra param. See the code below:
$collection = Mage::getModel('catalog/product')->getCollection()
->addStoreFilter($this->_getStoreId($store))
->addAttributeToSelect('name');
if($limit) {
$collection->setOrder('updated_at', 'ASC');
$collection->setPageSize($limit);
}
/** #var $apiHelper Mage_Api_Helper_Data */
$apiHelper = Mage::helper('api');
$filters = $apiHelper->parseFilters($filters, $this->_filtersMap);
try {
foreach ($filters as $field => $value) {
$collection->addFieldToFilter($field, $value);
}
} catch (Mage_Core_Exception $e) {
$this->_fault('filters_invalid', $e->getMessage());
}
$result = array();
foreach ($collection as $product) {
$result[] = array(
'product_id' => $product->getId(),
'sku' => $product->getSku(),
'name' => $product->getName(),
'set' => $product->getAttributeSetId(),
'type' => $product->getTypeId(),
'category_ids' => $product->getCategoryIds(),
'website_ids' => $product->getWebsiteIds(),
'updated_at' => $product->getUpdatedAt(),
'created_at' => $product->getCreatedAt()
);
}
return $result;
And from there we keep track of the last updated_at value and use that as a filter to get the next [LIMIT] items. By default updated_at and created_at are not in the response and the list is not orderred by updated_at so I've added this.
I am not sure of this but you could try this, as the API is working with collections and this is the way to limit a collection size
$filters = array(
'setPageSize' => 10
);

Resources