I have to add a product through an external page into the cart under the same URL.
The difference between these pages is that e.g. test.de
is running TYPO3 and test.de/Shop
is running Magento and test.de/productpage
is running an external script through TYPO3.
From the product page, I have to add a product to the Magento cart to proceed the checkout.
The key problem is to start the session outside of Magento.
If I call test.de/Shop/checkout/cart
before I go totest.de/productpage
and add a product to the cart, it works flawlessly.
But if I go the normal way (site -> productpage -> cart) I cant get Magento to listen to the session on the product page.
I have something like this to call
function addToBasket()
{
require_once('../app/Mage.php');
ob_start();
session_start();
umask(0);
session_write_close();
Mage::app()->setCurrentStore(33);
$session = Mage::getSingleton('core/session', array('name'=>'frontend'));
$productId = !isset($_GET['activeProdId']) ? '' : $_GET['activeProdId'];
$qty = !isset($_GET['qty']) ? '1' : $_GET['qty'];
if(empty($productId)) {
return "no product-id found";
}
$request = Mage::app()->getRequest();
$product = Mage::getModel('catalog/product')->load($productId);
$cart = Mage::helper('checkout/cart')->getCart();
$cart->addProduct($product, array('qty' => $qty));
$session->setLastAddedProductId($product->getId());
$session->setCartWasUpdated(true);
$cart->save();
return true;
}
The addToBasket is called through ajax.
So the question is: How do I start the session outside of the Magento-scope and put products into the cart?
2
Answers
Add first (like @samsonovits suggested) I had to add the store code in mage app and the store id (didn't test if the store-id is necessary after adding the store code).
Afterwards I called the frontend on
Mage::app
I switched the
Mage::helper('checkout/cart')
to the singletonMage::getSingleton('checkout/cart')
.Since
Magento 1.8
we have to add aform_key
to add products through an external script.This was accomplished by the following code:
Now we could proceed with a
$cart->addProduct($product, $request)
and$cart->save()
to save the cart.There is one more important part to change (since the external script is not in the same scope like magento) - the cookie url and path.
There we have to customize two fields:
Cookie-Path: /Shop
(where/Shop
is the destination of magento)Cookie-Domain: .test.de
(where.test.de
is the URL of the project)After this the
/Shop/checkout/cart
was able to inherit thefrontend-Cookie
of the external script (productpage
)Full code:
once you include Mage.php you will need to initialize Magento with
(first param is store code)
after that…
…will work as it should.