Programmatically Add multiple Products with Custom Options - php

I'm trying to develop a code in php which will take the order increment Id from an old order and will create a new order with same products along with the product custom options(if any).
Fetching par is fine even it was possible to add product via querystring but by that I can't add custom options. The cart page shows : Product Custom Options Required.
I think(not sure) I even succeeded in adding products with custom options via soap api but when I redirect to cart it shows an empty cart.
I'm a beginner, so please ignore any stupidity if it exists. :D
The code with the querystring is as below:
$form_key = Mage::getSingleton('core/session')->getFormKey();
$arrProducts = array(
/*array
(
"product" => "3",
"qty" => 7
),*/
array
(
"product" => "1",
"qty" => 3,
"options" => array
(
2 => array(
"date" => "11/12/13",
"date_internal" => "2013-12-11 00:00:00"
),
1 => "1"
)
header('Location: '.Mage::getUrl('checkout/cart/add/form_key/'.$form_key.'/', $arrProduct));
So, this directs to a page with the product but asks me to chose the product options.
and when i use the other product which is commented above, its a success.
Even i'm now able to add a product without custom(product with id='3') option in the cart. code is as follows:
<?php
require('../../../app/Mage.php'); //include mage.php
Mage::app();
Mage::getSingleton('core/session', array('name' => 'frontend'));
$form_key = Mage::getSingleton('core/session')->getFormKey();
//echo $form_key;
$cart = Mage::getSingleton('checkout/cart');
$product = new Mage_Catalog_Model_Product();
$product->load(2);
//$product->setProductOptions();
$params = array(
array
(
"product" => "3",
"qty" => 1
),
array
(
"product" => "2",
"qty" => 2,
"options" =>array
(
2 => array
(
"date" => "11/12/2013",
"date_internal"=> "2013-12-11 00:00:00"
),
1 => "1"
)
)
);
$cart->addProduct($product, $params);
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
header('Location:http://111.111.1.1/magento/checkout/cart');
?>
but it doesn't work for any product with custom options(product with id='2').
Error Message :
Fatal error: Uncaught exception 'Mage_Core_Exception' with message 'Please specify the product required option(s).' in C:\xampp\htdocs\magento\app\Mage.php:594 Stack trace: #0 C:\xampp\htdocs\magento\app\code\core\Mage\Checkout\Model\Cart.php(284): Mage::throwException('Please specify ...') #1 C:\xampp\htdocs\magento\pratmagento\panel\orders\try2addtocart.php(53): Mage_Checkout_Model_Cart->addProduct(Object(Mage_Catalog_Model_Product), Array) #2 {main} thrown in C:\xampp\htdocs\magento\app\Mage.php on line 594

It is required to set website_ids for the product.
$product->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId()));

Related

Create Product with custom option dropdown programatically

Im trying to create product with custom option dropdown programatically but it doesnt work and throw error. Maybe somebody know how to do it, I we be glad to hear it. In my opinion this script work well with single field option but not for dropdown.
PHP Warning: Invalid argument supplied for foreach()
My script file at root directory
<?php
use Magento\Framework\App\Bootstrap;
require 'app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // instance of object manager
$product = $objectManager->create('\Magento\Catalog\Model\Product');
$product->setSku('watermelon'); // Set your sku here
$product->setName('Watermelon'); // Name of Product
$product->setAttributeSetId(4); // Attribute set id
$product->setStatus(1); // Status on product enabled/ disabled 1/0
$product->setWeight(10); // weight of product
$product->setVisibility(4); // visibilty of product (catalog / search / catalog, search / Not visible individually)
$product->setTaxClassId(0); // Tax class id
$product->setTypeId('simple'); // type of product (simple/virtual/downloadable/configurable)
$product->setPrice(19); // price of product
$product->setStockData(
array(
'use_config_manage_stock' => 0,
'manage_stock' => 1,
'is_in_stock' => 1,
'qty' => 29
)
);
$product->save();
$options = array(
"title" => "Insurance",
"type" => "drop_down",
"is_require" => 0,
"sort_order" => 10,
"additional_fields" => array(
array(
"title" => "Not necessary",
"price" => 0,
"price_type" => "fixed",
"sku" => "not_necessary",
"sort_order" => 0
),
array(
"title" => "1 Year",
"price" => 0,
"price_type" => "fixed",
"sku" => "one_year",
"sort_order" => 1
),
array(
"title" => "2 Years",
"price" => 0,
"price_type" => "fixed",
"sku" => "two_years",
"sort_order" => 2
),
array(
"title" => "3 Years",
"price" => 0,
"price_type" => "fixed",
"sku" => "three_years",
"sort_order" => 3
),
)
);
foreach ($options as $arrayOption) {
$product->setHasOptions(1);
$product->getResource()->save($product);
$option = $objectManager->create('\Magento\Catalog\Model\Product\Option')
->setProductId($product->getId())
->setStoreId($product->getStoreId())
->addData($arrayOption);
$option->save();
$product->addOption($option);
}

Adding item to Square via SquareConnect PHP API -- 'category' and 'fees' defs being excluded

SquareConnect API newbie here.
I am attempting to add an item to Square using the PHP method:
$api_instance = new SquareConnect\Api\V1ItemsApi();
$body = new \SquareConnect\Model\V1Item($request_body);
$result = $api_instance->createItem($location_id, $body);
My request_body definition:
$request_body = array(
"name" => "**ITEM NAME**",
"description" => "**ITEM DESCRIPTION**",
"category" => array(
"id" => "**CATEGORY ID**",
"name" => "**CATEGORY NAME**"
),
"variations" => array(
array(
"name" => "**VARIATION NAME**",
"sku" => "**SKU**",
"pricing_type" => "FIXED_PRICING",
"price_money" => array(
"currency_code" => "USD",
"amount" => "**AMOUNT**"
)
)
),
"fees" => array(
"enabled" => "1",
"name" => "Sales Tax",
"rate" => "0.0775",
"calculation_phase" => "FEE_SUBTOTAL_PHASE",
"adjustment_type" => "TAX",
"inclusion_type" => "ADDITIVE",
"type" => "US_SALES_TAX"
)
);
The item and variation data are being added to Square, but the "category" and "fees" definitions are not being included. As a result the item is ending up in flat space, which requires me to log into the main Square interface, add the item to the appropriate category AND set its tax information. I do not want to have to take these additional steps if they can be avoided.
The tax information in the "fees" section is taken verbatim from the definitions found in items added via the Square interface. I have confirmed and re-confirmed that the category id and category name match those of the desired category. I also tried replacing the "category" array with a simple "category_id" => "CATEGORY ID" definition. Same result.
Can anyone assist? Also, if there is a better method for adding an item to Square via the API, please let me know!
Thank you in advance.
Part one, categories
If you look at the docs about specifying a item category during item creation:
You are specifing an array:
"category" => array(
"id" => "**CATEGORY ID**",
"name" => "**CATEGORY NAME**"
),
you should instead be using a string:
"category" => "**CATEGORY ID**",
Part two, fees
If you look again at the docs, you won't see any reference to fees in V1 items create. That is because you cannot create a fee with that endpoint. Instead you should create a new fee. You can see some sample code here: https://github.com/square/connect-php-sdk/blob/master/docs/Api/V1ItemsApi.md#createfee
I'm going to focus on the category_id since you seemed to have figured out the "fees" issue based on the comments.
I just used this as test code, and the category was set successfully:
$items_api = new \SquareConnect\Api\V1ItemsApi();
$body = array(
"name" => "Test Item",
"category_id" => "YFIHMKYXNFJ7TE5FRBWQAGU6",
"variations" => array(
array(
"name" => "Small",
"pricing_type" => "FIXED_PRICING",
"price_money" => array(
"amount" => 100,
"currency_code" => "USD"
)
))
);
$result = $items_api->createItem($location_id, $body);
echo $result;
Location_id was created earlier, but everything else is there.

Update quantity in MongoDB based on 2 conditions in PHP

I'm making a shopping cart in MongoDB and I want to update the quantity field if the user adds a product that's already added.
This is my document:
{
"_id" : "mzipdNS2Xyw-IqV085KrBe5RZucp9M_KqDSYjPinq20",
"products" : [
{
"productId" : "27122",
"quantity" : NumberLong(1),
"displayPrice" : "€ 599.00",
"price" : NumberLong(599),
"name" : "APPLE IPHONE 5S 16GB SPACE GRAY"
}
]
}
I'm running the following code to update my document, but it's not working, can anyone assist me?
$collection->update(array("_id" => $userId, array("products" => array("productId" => $productId))),
array('$set' => array("quantity" => $newQuantity
))
);
In order to update the correct item in the products array you'll have to use the positional $ operator.
$collection->update(
array(
"_id" => $userId,
"products.productId" => $productId,
),
array('$set' => array("products.$.quantity" => $newQuantity))
);

cannot add configurable product to cart in magento

i want to add a product to cart in magento , product details is :
type = configurable
product id = 1300
product sku = FCC100
Attribute Code= color
Attribute Label= color
Attribute Id= 152
options value = 28,43
options label = blue,red
this configurable product have two color option red and blue, there is two simple product atached to this configurable product.
i try with this code :
$product = array(
"product_id" =>"1300",
"qty" => 2,
"super_attribute" => array(152 => 28));
$result = $proxy->shoppingCartProductAdd($sessionID, $cartID, array($product));
but this code return me this message :
please specify product option(s)
i use this code to add simple product and it`s work fine :
$result = $proxy->shoppingCartProductAdd($sessionID, $cartID, array(array(
'product_id' => $productID ,
'sku' => $sku ,
'qty' => $qty,
'options' =>array(0 =>array('key' => $option1id ,'value' => $option1value),1 =>array('key' => $option2id ,'value' => $option2value)),
'bundle_option' => null,
'bundle_option_qty' => null,
'links' => null
)));
my problem is with configurable product. i try to add with simple child products but problem of this way is often child products have not price and price is setted to parent product.
what is the problem in my code ? is there any way to add configurable product to cart with out using API ?
this is what i found in product page source:
Product.Config({"attributes":{"152":{"id":"152","code":"color","label":"\u0631\u0646\u06af","options":[{"id":"28","label":"\u0622\u0628\u06cc","price":"0","oldPrice":"0","products":["1301"]},{"id":"47","label":"\u0632\u0631\u0634\u06a9\u06cc","price":"0","oldPrice":"0","products":["1302"]}]}},"template":"#{price}\u00a0\u0631\u06cc\u0627\u0644","basePrice":"550000","oldPrice":"550000","productId":"1300","chooseText":"\u0627\u0646\u062a\u062e\u0627\u0628 \u06cc\u06a9 \u06af\u0632\u06cc\u0646\u0647...","taxConfig":{"includeTax":false,"showIncludeTax":false,"showBothPrices":false,"defaultTax":0,"currentTax":0,"inclTaxTitle":"\u0634\u0627\u0645\u0644 \u0645\u0627\u0644\u06cc\u0627\u062a"}});
Your array must be like below
$arrProducts = array(
array(
"product_id" =>"21",
"qty" => 2,
"super_attribute" => array(
92 => 162
)
));
Your $product array is missing the options key values.
You need to add options which should be An array in the form of option_id => content per the documentation.
$product = array(
"product_id" => "1300",
"qty" => 2,
"options" => array(
152 => 28
)
);
Documentation: http://www.magentocommerce.com/api/soap/checkout/cartProduct/cart_product.add.html

How do I set the quantity of the option in my bundle product?

I have this code, which would add one bundle product with the ID of 171 to the cart, given the option of a product with the color(23) Magenta(63). Is there any way to set a quantity to the option, like say we want to set the quantity to 2 of those items with that color?
Thanks for the help.
$params = array(
'product' => 171,
'bundle_option' => array(
23 => array(
0 => 63
),
),
'qty' => 1,
);
$cart = Mage::getSingleton('checkout/cart');
$product = Mage::getModel('catalog/product');
$product->load(171);
$cart->addProduct($product, $params);
$cart->save();
Have you tried intercepting the request to addtocart and seeing what a normal post array for that bundle would look like? That should give you the structure that you need.

Categories