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

In: Feeling guru|Techie Daw

27 Apr 2009

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.

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 :)

About the author

Richard Feraro is a web programmer from Manila, Philippines with 13 years of solid open-source development experience using Linux, Apache, MySQL & PHP.

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

Avatar

Shital INDIA

August 1st, 2012 at 8:20 pm

Hi!

Great post, it help me a lot!

Avatar

Vishal sanwar AUSTRALIA

September 8th, 2012 at 9:24 pm

Hi,
If a customer want a product in large qty like:30qty.

We a have a product and the qty is 5. and we have same product(duplicate product) and qty is 50.

then i want to save products in shopping cart like : take first product qty i.e 5 and another product take 25 qty.

But when we select 30 qty and click on add to cart button then we can not go to shopping cart page.

Please solve the problem.

Thanks
Vishal

Avatar

Richard Feraro PHILIPPINES

September 11th, 2012 at 12:12 am

Is there an error page after clicking the add to cart button? Those two products are treated as two different items regardless if they are duplicate since they would have different IDs in the database.

Avatar

Manoj Kumar INDIA

November 16th, 2012 at 6:51 pm

Hi,

I am using magento 1.7.2 and I want to add some external products in magento cart and I am trying your code but not working. can u help me on this point?

Thanks in advance.
Manoj Kumar

Avatar

Gift PHILIPPINES

November 27th, 2012 at 3:34 pm

Hi Richard,

Thank you for the great post!

I understand that this post was made few years ago, so there might be some slight changes to the code now. I’m currently using the latest stable version of Magento (ver 1.7.0.2) and the code above is not anymore working. If it’s not too much too ask, it would be greatly appreciated if you can post some updates for the latest Magento version. :)

Best Regards,
Gift

Avatar

Richard Feraro

December 4th, 2012 at 3:16 am

Sorry for the late reply. I’ll try to update it over the weekend. Thanks :-)

Avatar

Richard Feraro

December 4th, 2012 at 3:18 am

How did you implement it?

Avatar

Gift PHILIPPINES

December 4th, 2012 at 11:29 am

Hi Richard,

Thank you for the update. I somehow managed to implement the add to cart button, but I understand the product is already set and predefined in Magento site right?

Here’s my case and what I’d like to achieve:

I currently have a Custom Product Builder (Gun Customization) where users can select customize parts of their choice and eventually add this to their cart. The custom builder is a separate file from Magento. Since it’s a customized product, it would be difficult to add them one by one thru Magento. So what I’d like to do everytime a user submits the customize product is to add this automatically to Magento. I mean not setting/creating the product thru Magento admin but creating the product externally. Is this possible?

Your positive response will be greatly appreciated.

Thank you.

Regards,
Gift

Avatar

riski INDIA

December 20th, 2012 at 4:04 pm

Hello sir I have to display direct my cart page open when user click on add to cart button pls help me

Avatar

Maria Carroll UNITED STATES

January 29th, 2013 at 2:11 am

I am using magento 1.7 on my local server for now, and when i insert this code nothing happens, can you please help me.

Thanks

Avatar

Richard Feraro

January 29th, 2013 at 7:35 pm

Post your code here

Avatar

Alex GERMANY

January 30th, 2013 at 8:58 pm

Hi Richard,

I’d have following problem: the magento site and external site are hosted on two different domains.
OK, so I can get access to magento site over SOAP-API. I want the user to be redirected from this external site to magento shopping cart page, as soon as the user presses “My cart” button.
With the help of SOAP-API I’ll get sessionID, and cartID.
Is it possible to open that specific shopping cart, by passing these two parameters over POST or GET method to magento server?

Thanks in advance.

Avatar

Richard Feraro AUSTRALIA

February 5th, 2013 at 2:26 pm

I haven’t tried that yet. You can, however, pass the session ID across two system but this is pretty much open to attack.

Avatar

Atty ROMANIA

April 1st, 2013 at 3:52 pm

you need to $cart->init() – before $cart->addProduct() – in order to be able to add multiple items to the cart

Avatar

Azhar Mobeen

May 15th, 2013 at 3:57 am

I am using Amazon CheckOut Button in my Magento Store but problem is that when i click the button it doesn’t contain cart products.

My code : (I place it in cart.phtml)

//

//

The Simple, Truseted way to Pay.

Avatar

peter

January 21st, 2014 at 9:54 pm

Thanks for the coding you provided for add product in shopping cart. It’s a helpful info for me.

Comment Form

About my blog

This blog is targeted towards all levels of developers and also designers. Various topics are discussed such as Magento, PHP & MySQL, jQuery, WordPress, CSS and HTML.

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 10 other subscribers

PayPal Donation

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.