I've created code necessary to add a custom item to every cart, and all seems to be ALMOST working as intended. The code gets the items in the cart, and formulates XML that is sent over to a 3rd party in a request, and parses the response back to my code into an array. The response array is then added to the cart as a unique item with a specific, preordained SKU.
The only trouble that I'm facing is that when I do this, it doesn't seem to update the subtotal in the cart. For example:
I put in an order in the cart for one item costing $421. This one item is put into an XML statement that is sent over to the 3rd party to get a certain price for a "bond" that is based on the cost of all items in the cart. The response sends the cost of the bond back as $12.63 and the subtotal of the two items in the cart is $433.63 as intended. Then, after playing with the quantity of the $421 item, I'm starting to see some odd things...
I change the number of the item to 5, and click "UPDATE CART". I get a return value of $63.15 on the bond, but the subtotal shows that I'm adding $2,105 (the price of 5 items) with $12.63 (the price of the original bond) for a total of $2,117.63. I click "UPDATE CART" again, and it then shows the total of $2,168.15.
This happens every time I change the quantity. I get the previous "bond" price added to the current subtotal, and it takes me two clicks of "UPDATE CART" to get the price caught up.
So, I was thinking if there was a way to add the code I've created BEFORE it runs anything else, I'd be able to close that gap. Am I doing this correctly? What is the best way to add my code previous to any other code that has been put in the XML to call forth this page?
EDIT
To explain further, this is the code block I'm using:
$cartHelper = Mage::helper('checkout/cart');
if ($buySAFEcost > 0) {
$product = Mage::getModel('catalog/product');
$bs_cart = Mage::getModel('checkout/cart');
$items = $cartHelper->getCart()->getItems();
$bs_my_product_id = $product->getIdBySku($bs_sku);
$bs_my_product = $product->load($bs_my_product_id);
$params = array( 'qty' => 1, 'price' => $buySAFEcost );
$bs_cart->addProduct($bs_my_product,$params);
$bs_cart->save();
Mage::app()->setCurrentStore(0); // ADMIN_STORE_ID
$bs_my_product->setPrice($buySAFEcost);
$bs_my_product->save();
// Redo the totals?
$cartModel->getQuote()->getBillingAddress();
$cartModel->getQuote()->getShippingAddress()->setCollectShippingRates(true);
$cartModel->getQuote()->collectTotals();
$cartModel->getQuote()->save();
// $cartModel->getQuote()->setTotalsCollectedFlag(false)->collectTotals()->save();
Mage::app()->setCurrentStore(1); // DISTRO_STORE_ID
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
}
I feel like I'm killing an ant with a sledgehammer here, but the subtotals remain constantly one step behind my actions. Am I putting this in the wrong section of code, perhaps?