How to add a product into Magento shopping cart from an external site?

In: Feeling guru|Techie Daw

27 Apr 2009
Advertisement

Yes, I know. This topic has already been discussed here. But it seems the article isn’t really helpful for those people who would integrate Magento into a custom website because it will redirect the page to Magento’s default web store provided in the installation. The technique I’ll discuss here assumes that you know HTML and ofcourse familiar with Object Oriented Programming (OOP) in PHP.

Advertisement

Let’s start.

We begin our index.php page with a HTML form having one (1) textbox for quantity and a submit button.

<form action="process.php">
Product name: T-shirt <br>
Quantity: <input type="text" name="qty[<?=$productID?>]">
<input type="submit" value="Add to Cart">
</form>

where $productID is the ID of the product that you want to add into your shopping cart and process.php is the file that will do the processing of the form. Also upon submission of the form, the qty field will pass the value into an array format similar to one below:

"qty" = array(12345 => 1)

where

qty is the field name
12345 is the product ID and
1 is the qty value

This will be the content of process.php file:

Include the Mage.php file on top of the process.php. Click here to see how.
Then proceed with the php script below:

// continuation of process.php
$items = $_POST["qty"];

// get the current Magento cart
$cart = Mage::getSingleton('checkout/cart');

foreach($items as $key => $value)
{
   // call the Magento catalog/product model
   $product = Mage::getModel('catalog/product')
                     // set the current store ID
                     ->setStoreId(Mage::app()->getStore()->getId())
                     // load the product object
                     ->load($key);

   // start adding the product
   $cart->addProduct($product, array('qty' => $value));
   // save the cart
   $cart->save();

   // very straightforward, set the cart as updated
   Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
}

// redirect to index.php
header("Location: index.php");

That’s it! I didn’t add the end tag for php since it isn’t required for pure php file. I included alot of comments within the code to explain how each line works. If it causes you some problems, just remove the comments :)

Advertisement

About the author

Richard Feraro is a PHP Developer living in Manila, Philippines. He has been programming for nine (9) years and working on different open source application mostly done in PHP and MySQL.

23 Responses to How to add a product into Magento shopping cart from an external site?

Avatar

Vikas Kumar INDIA

July 22nd, 2009 at 5:00 am

Do you have any idea to open product detail page using product id?

Avatar

Richard Feraro PHILIPPINES

July 22nd, 2009 at 9:48 am

Yes. It is done using the code below:

$mage = Mage::getSingleton('catalog/product');
$product = $mage->load($product_id);

using $product you can now access the details of the specified id. For example, you can view all the details by running the code below:

$product->getData();

Avatar

aledujke

October 29th, 2009 at 4:31 am

And how would you remove the product :)

I tied:
$cart = Mage::getSingleton(‘checkout/cart’);
$cart->removeItem($item_id); //item_id not product_id
$cart->save();
Mage::getSingleton(‘checkout/session’)->setCartWasUpdated(true);

but it did not work :(

btw thanks for your article it already helped me a LOT!

cheers!

Avatar

Richard Feraro PHILIPPINES

October 29th, 2009 at 9:55 pm

It’s quite easy :)
Set the quantity to 0

Thanks :p

Avatar

Raph FRANCE

November 24th, 2009 at 5:14 am

Hi !

How to add bundle with option ?

Thanks

Avatar

molecule AUSTRALIA

November 29th, 2009 at 11:09 am

Any idea how to add a configurable product via URL?

I tried adding the configurable option IDs as in your methos but they seem to not catch.

Thanks

Avatar

alex UNITED STATES

December 21st, 2009 at 2:41 pm

I have the cookie location set for ‘/’ and it doesn’t work. I’m using latest version of Magento. I’ve tried countless variations of this script gleaned from the internet and it does not work. What location is the script running from? Does that matter? Did this functionality disappear in a recent upgrade?
I can not get into a Magento session from a script in a different folder on the same server for the life of me. Very frustrating.
I’m trying to bridge Magento and SMF and I have the Magento side down and done, but connecting TO Magento from SMF is just not working…
Anyone know how to accomplish this besides API?
thanks

Avatar

j UNITED STATES

March 3rd, 2010 at 10:17 pm

alex, are you making sure you have this being called on your page?

Avatar

ben CANADA

March 13th, 2010 at 7:56 am

Hi, great post.

I’m currently going through so that when a certain product is added to the cart and they are from such and such location then it adds a associated fee.

I’ve got it set up so when they checkout it’s adding the fee as a product kind of like what you’ve done above.


115,
'qty' => $qty,
);

$product = new Mage_Catalog_Model_Product();
$product->load(115);

$cart->addProduct($product, $params);
$cart->save();
?>

This works awesome, but my trouble is if they refresh the page or go away and come back to the page it adds the product again. Do you knowhow I could do some sort of product checking so if it’s been added it can’t be added again, or how to set the qty after the cart->save function?

Let me know, thanks.

Avatar

Richard Feraro

March 13th, 2010 at 2:51 pm

Thanks Ben!

I think it will behave that way unless you’ll do a couple of checking to your cart value. Refreshing the page will always add the product in the cart as long as your valid get/post values are still present which makes the $cart->addProduct() function to return TRUE. There are several ways you can prevent same data from being used more than once but I think these are the most common:

1. Creating a separate confirmation page for successful/failed add to cart request, or;
2. Do the validation on the same page.

If you choose the last option, you can check if the productid is already present in the cart. If it is, then you can get the current qty and add your new qty value to it. Removing a product in the cart also works this way because setting the qty to zero deletes the item from the cart.

You can experiment using the functions getProductIds and updateItems found in the Magento Documentation

Avatar

John NETHERLANDS

March 24th, 2010 at 1:58 am

Removing an item with qty to 0 does not work. instead use this:

$items = $cart->getItems();
foreach ($items as $item) {
if ($product->getId() == $product_id) {
$itemId = $item->getItemId();
$cart->removeItem($itemId);
Mage::getSingleton(‘checkout/session’)->setCartWasUpdated(true);
break;
}
}

Avatar

john NETHERLANDS

March 24th, 2010 at 2:02 am

Sorry, more information for above:

The product id for adding a product is not the same as the id for removing.
- Iterate through the cart items
- Get the product id and compare with the product id you want to remove.
- Remove the product
- Break out of the loop when product is found and deleted.

Missing a $cart->save(); in the above code.

Best regards,
John.

Avatar

Gauthier FRANCE

June 4th, 2010 at 3:10 pm

Hi!

Great post, it help me a lot!

However, I have a question! How do I add a product with customs options?
For exemple a t-shirt with different color and size?

Thanks in advance for your answer
Gauthier

Avatar

How to add a product with custom options into Magento shopping cart from an external site? PHILIPPINES

June 4th, 2010 at 5:50 pm

[...] is a follow up post to a previous article I wrote on how to add products into Magento but this time the script includes custom options [...]

Avatar

Richard Feraro UNITED STATES

June 4th, 2010 at 5:54 pm

Hello Gauthier,

Thanks for reading my blog. Regarding your question, please check my follow up post regarding the matter here

Keep on reading!

Richard

Avatar

Nehal INDIA

January 31st, 2011 at 4:54 pm

Hi!!!!
thanks for this script…. :)
but I want to save a product as new product by submitting a form in a script
what will be the code???????
please help me
again thanx in advance

Avatar

sunil

April 27th, 2011 at 1:37 pm

In made auction module,when auction over i want to add product of winner user only in that how set customer id of winner user add to cart……..

Avatar

Richard Feraro UNITED STATES

April 29th, 2011 at 8:30 am

You can use setCustomer() to indicate which user you want to use for that session.

Avatar

will UNITED KINGDOM

May 19th, 2011 at 11:32 pm

Hi, Great post. I have dug around everywhere on a way to do this… Do you know how I can do what you have above and have it alter the line total, sku, title etc etc?

I have managed to do this by placing an order without any trouble but I need it to sit in the basket so that the customer can place the order.

Many thanks!

Avatar

Leigh AUSTRALIA

June 1st, 2011 at 7:37 am

Great tut thanks Richard. How would I add a custom option which is a checkbox?

Avatar

Jodi UNITED STATES

August 18th, 2011 at 3:35 pm

I would like to link the products in my Magento to my main website popnovels do you know how I could write in the redirect from the product image to the product on my main site. http://www.popnovels.com. Currently I have a dummy site set up at http://www.popgnovels.com with one book in it and am trying to get it to link to the product. I have the address to the products on popnovels I just am lost on how to get the code to respond the way I want.

Avatar

Merk INDIA

September 18th, 2011 at 11:58 pm

I want to add products from prestashop to magento shopping cart is this possible ?

Avatar

Richard Feraro PHILIPPINES

September 19th, 2011 at 5:24 pm

Yeah. Just follow the post.

Comment Form

About my blog

This is a programmer's blog. Whenever I encounter a difficult coding task, I make sure that I'll be able to share it here in the hope that others may find it useful. It's my way of giving back to the open source community who have been a great help to me as well.

Share This Post

or bookmark to your mobile

Bookmark: http://mysillypointofview.richardferaro.com/2009/04/27/how-to-add-a-product-into-magento-from-an-external-site/

Advertisement

WordPress + Magento

Proudly Pinoy!

Proudly Pinoy!

Recent Trackbacks

Archives

Disclaimer

All entries in this blog are my opinion and don't necessarily reflect the opinion of my employer or my mom.

Viewers by Country

in India 3274 (21 %) 3781 (19 %)
us United States 2739 (17 %) 3560 (18 %)
gb United Kingdom 926 (6 %) 1176 (6 %)
de Germany 767 (5 %) 989 (5 %)
nl Netherlands 586 (4 %) 743 (4 %)
fr France 483 (3 %) 606 (3 %)
ph Philippines 468 (3 %) 763 (4 %)
br Brazil 443 (3 %) 547 (3 %)
au Australia 334 (2 %) 402 (2 %)
ca Canada 330 (2 %) 408 (2 %)
es Spain 323 (2 %) 429 (2 %)
it Italy 318 (2 %) 400 (2 %)
vn Vietnam 285 (2 %) 357 (2 %)
pk Pakistan 278 (2 %) 307 (2 %)
ro Romania 261 (2 %) 319 (2 %)
cn China 246 (2 %) 351 (2 %)
ua Ukraine 240 (2 %) 297 (2 %)
pl Poland 138 (1 %) 167 (1 %)
ru Russia 134 (1 %) 171 (1 %)
id Indonesia 132 (1 %) 159 (1 %)
Total Countries: 139
Total Visits: 15686
Total Pageviews: 19735