Magento current cart detail(Without login)with product data - magento

I have Magento online store with two types of products (configurable and simple) and now I am working on web services. Can someone explain me how to get cart detail without logging in? I have tried everything but I am unable to get cart details.

You can get the cart item
$cart = Mage::getModel('checkout/cart')->getQuote();
if($cart->getAllItems()):
foreach ($cart->getAllItems() as $item):
echo $item->getProduct()->getName()
endforeach;
endif;

You will not get visitor's cart item from another resource as its interlinked with browser session. For this you need to add product from that resource from which you want to get. API is the suitable way for this. Please look at the below code i guess it will helps you.
error_reporting(E_ALL);
ini_set('display_errors', '1');
include_once 'app/Mage.php';
umask(0);
$initializationCode = 'admin';
$initializationType = 'store';
Mage::app($initializationCode, $initializationType);
/**
* This is the path to the V2 wsdl of the magento api
**/
$wsdl = 'http://yoursite.com/api/v2_soap/?wsdl=1';
/**
* Create the soap client
**/
$client = new SoapClient($wsdl, array('trace' => false));
$username = 'mysoapuser';
$password = 'mysoapuserpassword';
/**
* For every magento api session, we first need to login.
* The returned value is you API session_id which you need to
* Pass to every API call you make.
**/
$session_id = $client->login($username, $password);
/**
* The first thing we do is create the Magento shopping cart, or quote
*
* Here is detailed information and more examples from Magento:
* http://www.magentocommerce.com/api/soap/checkout/cart/cart.create.html
*
* We pass it the session_id from our login call and the store id we want
* create the quote for. The returned value will be the quote_id
* if it was successful, or nothing with no faults if it fails
*
**/
$cart = $client->shoppingCartCreate($session_id, '1');
$addAddress = $client->shoppingCartCustomerAddresses(
$session_id,
$cart,
array(
array(
'mode' => 'shipping',
'firstname' => 'Paul',
'lastname' => 'Briscoe',
'street' => '117 N. 1st St.',
'city' => 'Ann Arbor',
'region' => 'MI',
'postcode' => '48104',
'country_id' => 'US',
'telephone' => '7345458017',
'is_default_shipping' => 1
)
)
);
/**
* Just make sure to check that the quoteId was returned from the API
* Next we are going to start adding products into the new quote. The format is below.
* Keep in mind that you could easily loop through an array of order products.
*
* Note: getExternalOrder() does not actually exist, but if you have an order object
* or array of products you can use to get the info you need.
**/
$externalOrderProducts = getExternalOrder();
$products = array();
foreach($externalOrderProducts as $product){
$products[] = array(
'product_id' => $product->getId(),
'sku' => $product->getSku(),
'qty' => $product->getQty(),
'options' => null,
'bundle_option' => null,
'bundle_option_qty' => null,
'links' => null
)
}
/**
* Here make the API call back to Magento to add the product array to the quote
*
* For more information on this call see:
* http://www.magentocommerce.com/api/soap/checkout/cartProduct/cart_product.add.html
*
* Returns True if the product successfully added to the quote
**/
if($addAddress) {
$addProduct = $client->shoppingCartProductAdd(
$session_id,
$cart,
array($products)
);
} else {
echo "Address did not add.";
}
/**
* Again, check that the product added successfully and then simply call the Shipping List API
* For a list of available shipping methods for this quote.
*
* For more information on this call see:
* http://www.magentocommerce.com/api/soap/checkout/cartShipping/cart_shipping.list.html
*
**/
if($addProduct) {
$shipping = $client->shoppingCartShippingList($session_id, $cart);
} else {
echo "Product did not add.";
}
echo "<pre>";
var_dump($shipping);
echo "</pre>";
//

Related

How to specify only methods for resource in array Laravel

In web.php i have this Route::resources method
Route::resources([
'products' => App\Http\Controllers\ProductsController::class,
'categories' => App\Http\Controllers\CategoriesController::class,
'page-info' => App\Http\Controllers\PageInfoController::class,
]);
How can I specify only index,edit and update for 'page-info' route? and how to add name to each route?
I know that I can do it like this
Route::resource('products', ProductsController::class);
Route::resource('page-info', PageInfoController::class)->only([
'index', 'edit', 'update'
]);
//itd...
but I like the array one resources and thought it is possible too
You can't do what you want, if the documentation does not explicitly say you can or not, you can always have a look at the source code.
So, source code for Laravel 8.x has:
/**
* Register an array of resource controllers.
*
* #param array $resources
* #param array $options
* #return void
*/
public function resources(array $resources, array $options = [])
{
foreach ($resources as $name => $controller) {
$this->resource($name, $controller, $options);
}
}
So, you can do
Route::resources([
'products' => App\Http\Controllers\ProductsController::class,
'categories' => App\Http\Controllers\CategoriesController::class,
'page-info' => App\Http\Controllers\PageInfoController::class,
], $options);
But the code shows that it will share the options for all the resources to be created, so the answer is a no, you can't (at least what I am looking at the source code).

Magento - add product to cart with custom option using PHP

I am trying to add a product to the cart programmatically with some custom options. The item gets added to the cart correctly but none of the options ever get added. My code is:
require_once '../../app/Mage.php';
umask(0);
/* not Mage::run(); */
Mage::app('default');
Mage::getSingleton("core/session", array("name" => "frontend"));
$product_id = 2364;
$id_opt_value = 6072;
$final_opt_value = 6074;
$product = Mage::getModel('catalog/product')->load($product_id);
$cart = Mage::getModel('checkout/cart');
$cart->init();
$params = array(
'product' => $product_id,
'qty' => 1,
'options' => array(
$id_opt_value => '123456',
$final_opt_value => 'black gloss finish',
)
);
$cart->addProduct($product, $params);
$cart->save();
I have double checked and the option values are correct. I am using magento ce-1.9.0.0
Try to use Varien Object:
$request = new Varien_Object();
$request->setData($param);
$cart->addProduct($productInstance, $request);
Should work as well.

Magento create order programmatically with downloadable product

I have been successful creating orders with a Custom controller and all works well. My issue is i need to add the ability to create orders with downloadable product. I would just like to be pointed on where to start.
Controller is handling all the set up and the order save. Is there a Action or something I need to hit for the customer to be able to access his/her downloads?
Try the below Code, please go threw comments.
<?php
require_once 'app/Mage.php';
Mage::app();
$customer = Mage::getModel("customer/customer")
->setWebsiteId(Mage::app()->getStore()->getWebsiteId())
->loadByEmail($data['email']);
if(!$customer->getId()) {
$customer->setEmail($email); //enter Email here
$customer->setFirstname($fname); //enter Lirstname here
$customer->setLastname($lname); //enter Lastnamre here
$customer->setPassword(password); //enter password here
$customer->save();
}
$storeId = $customer->getStoreId();
$quote = Mage::getModel('sales/quote')
->setStoreId($storeId);
$quote->assignCustomer($customer);
// add product(s)
$product = Mage::getModel('catalog/product')->load(186); //product id
/*$buyInfo = array(
'qty' => 1,
'price'=>0
// custom option id => value id
// or
// configurable attribute id => value id
);*/
$params = array();
$links = Mage::getModel('downloadable/product_type')->getLinks( $product );
$linkId = 0;
foreach ($links as $link) {
$linkId = $link->getId();
}
//$params['product'] = $product;
$params['qty'] = 1;
$params['links'] = array($linkId);
$request = new Varien_Object();
$request->setData($params);
//$quoteObj->addProduct($productObj , $request);
/* Bundled product options would look like this:
$buyInfo = array(
"qty" => 1,
"bundle_option" = array(
"123" => array(456), //optionid => array( selectionid )
"124" => array(235)
)
); */
//$class_name = get_class($quote);
//Zend_Debug::dump($class_name);
$quote->addProduct($product, $request);
$addressData = array(
'firstname' => 'Vagelis', //you can also give variables here
'lastname' => 'Bakas',
'street' => 'Sample Street 10',
'city' => 'Somewhere',
'postcode' => '123456',
'telephone' => '123456',
'country_id' => 'US',
'region_id' => 12, // id from directory_country_region table if it Country ID is IN (India) region id is not required
);
$billingAddress = $quote->getBillingAddress()->addData($addressData);
$shippingAddress = $quote->getShippingAddress()->addData($addressData);
/*$shippingAddress->setCollectShippingRates(true)->collectShippingRates()
->setShippingMethod('flatrate_flatrate')
->setPaymentMethod('checkmo');*/
/* Free shipping would look like this: */
$shippingAddress->setFreeShipping( true )
->setCollectShippingRates(true)->collectShippingRates()
->setShippingMethod('freeshipping_freeshipping')
->setPaymentMethod('checkmo'); /* shipping details is not required for downloadable product */
$quote->setCouponCode('ABCD'); // if required
/* Make Sure Your Check Money Order Method Is Enable */
/*if the product value is zero i mean free product then the payment method is free array('method' => 'free')*/
$quote->getPayment()->importData(array('method' => 'checkmo'));
$quote->collectTotals()->save();
$service = Mage::getModel('sales/service_quote', $quote);
$service->submitAll();
$order = $service->getOrder();
printf("Order Created Successfully %s\n", $order->getIncrementId());

Attach Image to Product with Drupal Api

I am trying to programatically add products to my drupal commerce store. So far I have been able to add products that contain basic information ( such as sku, title, and price ). How would I be able to add field data, such as images and other field types, using drupal's api.
The code I used to add the products is derived from the commerce_examples/product_example module.
<?php
/**
* #file product_example.module
* Demonstrates pricing hooks, etc.
*/
/**
* Implements hook_menu().
*
* Simply presents a page that will explain what this module is for.
* hook_menu() has nothing to do with the checkout page functionality.
*/
function product_example_menu() {
$items['commerce_examples/product_example'] = array(
'title' => 'Product Example',
'page callback' => 'drupal_get_form',
'page arguments' => array('product_example_info_page'),
'access callback' => TRUE,
);
return $items;
}
/**
* This form provides a way to interact with some of the example functions
* provided here.
*/
function product_example_info_page($form, &$form_state) {
$form['explanation'] = array(
'#type' => 'item',
'#markup' => t('This example demonstrates product creation and manipulation.'),
);
$form['product_creation'] = array(
'#type' => 'fieldset',
'#title' => t('Please create a product for use with this example'),
);
$types = commerce_product_types();
$form['product_creation']['product_type'] = array(
'#type' => 'select',
'#title' => t('Product type for product to be created'),
'#options' => drupal_map_assoc(array_keys($types)),
);
$form['product_creation']['title'] = array(
'#title' => t('Product title'),
'#type' => 'textfield',
'#default_value' => t('A dummy product for use with product_example'),
);
$form['product_creation']['price'] = array(
'#title' => t('Product price'),
'#type' => 'textfield',
'#description' => t('A price in decimal format, without a currency symbol'),
'#default_value' => '100.00',
);
$form['product_creation']['product_creation_submit'] = array(
'#type' => 'submit',
'#value' => t('Create product'),
'#submit' => array('product_example_product_creation_submit')
);
return $form;
}
/**
* Submit handler for creating a product.
*/
function product_example_product_creation_submit($form, &$form_state) {
$extras = array(
'sku' => 'product_example_' . drupal_hash_base64(microtime()),
'status' => TRUE,
'uid' => $GLOBALS['user']->uid,
'title' => $form_state['values']['title'],
);
// Use the product example's creation function to create a product.
$product_id = product_example_create_product($form_state['values']['product_type'], $form_state['values']['price'], $extras);
drupal_set_message(t('Created sample product with title !title and sku !sku', array('!title' => l($extras['title'], 'admin/commerce/products/' . $product_id), '!sku' => $extras['sku'])));
}
/**
* Create a product programmatically.
*
* This is stolen shamelessly from commerce_bpc. Thanks for the help here!
*
* #param $product_type
* (string) The name of the product type for which products should be created.
* #param $price
* Decimal amount of price. If additional fields need to be populated they
* can be populated in exactly the same way as the commerce_price field.
* #param $extras
* An array for the values of 'extra fields' defined for the product type
* entity, or patterns for these. Recognized keys are:
* - status
* - uid
* - sku
* - title
* Note that the values do NOT come in the form of complex arrays (as they
* are not translatable, and can only have single values).
* #return
* The ID of the created product.
*/
function product_example_create_product($product_type, $price, $extras) {
$form_state = array();
$form_state['values'] = array();
$form = array();
$form['#parents'] = array();
// Generate a new product object
$new_product = commerce_product_new($product_type);
$new_product->status = $extras['status'];
$new_product->uid = $extras['uid'];
$new_product->sku = $extras['sku'];
$new_product->title = $extras['title'];
$new_product->created = $new_product->changed = time();
//commerce_price[und][0][amount]
$price = array(LANGUAGE_NONE => array(0 => array(
'amount' => $price * 100,
'currency_code' => commerce_default_currency(),
)));
$form_state['values']['commerce_price'] = $price;
// Notify field widgets to save their field data
field_attach_submit('commerce_product', $new_product, $form, $form_state);
commerce_product_save($new_product);
return $new_product->product_id;
}
Using the same format the examples uses to add price data:
//commerce_price[und][0][amount]
$price = array(LANGUAGE_NONE => array(0 => array(
'amount' => $price * 100,
'currency_code' => commerce_default_currency(),
)));
I was able to add other field data, however I am still having trouble adding data to the field_productimage field that all commerce products come with by default.
I can suggest you about other fields data such as extra info related to product. You can add these fields to the product type from the UI or if you are creating product type programmatically then also you can do the same.
Add fields in your form to collect the data e.g -
$form['product_creation']['values'] = array(
'#title' => t('Some data'),
'#type' => 'textfield',
'#description' => t('Dummy data'),
);
Get those data in your function product_example_create_product() by $form_state().
Add them to $new_product object like
$new_product->field_name['und'][0]['value'] = $extras['values'];
Save the product, just like you are doing.
For the image, you will have to follow the method of file attachment. Like -
$file_path = drupal_realpath('image/product_image.png');
$file = (object) array(
'uid' => 1,
'uri' => $file_path,
'filemime' => file_get_mimetype($file_path),
'status' => 1,
);
// We save the file to the root of the files directory.
$file = file_copy($file, 'public://');
$new_product->product_image[LANGUAGE_NONE][0] = (array)$file;

How to add limit option in Magento API call

I am creating web service for my store. I am using magento API to collect product list from store. But it display all the 500 records. And i want it 25 records per page. What to add in API call? Or What filter will be apply for this?
//create soap object
$proxy = new SoapClient('http://localhsot/magento/api/soap/?wsdl');
// create authorized session id using api user name and api key
// $sessionId = $proxy->login('apiUser', 'apiKey');
$sessionId = $proxy->login('test_admin', '12345678');
$filters = array(
);
// Get list of product
$productlist = $proxy->call($sessionId, 'product.list', array($filters));
print_r($productlist );
that didn't work, can you limit it by id like:
$filters = array('id'=>array("gteq"=>1), 'id'=>array("lteq"=>1000));
that way you could add some paging?
I know this is an old question but I struggled with this. I've created my own SOAP API endpoint which does exactly the same as the default catalogProductList function but has an extra param. See the code below:
$collection = Mage::getModel('catalog/product')->getCollection()
->addStoreFilter($this->_getStoreId($store))
->addAttributeToSelect('name');
if($limit) {
$collection->setOrder('updated_at', 'ASC');
$collection->setPageSize($limit);
}
/** #var $apiHelper Mage_Api_Helper_Data */
$apiHelper = Mage::helper('api');
$filters = $apiHelper->parseFilters($filters, $this->_filtersMap);
try {
foreach ($filters as $field => $value) {
$collection->addFieldToFilter($field, $value);
}
} catch (Mage_Core_Exception $e) {
$this->_fault('filters_invalid', $e->getMessage());
}
$result = array();
foreach ($collection as $product) {
$result[] = array(
'product_id' => $product->getId(),
'sku' => $product->getSku(),
'name' => $product->getName(),
'set' => $product->getAttributeSetId(),
'type' => $product->getTypeId(),
'category_ids' => $product->getCategoryIds(),
'website_ids' => $product->getWebsiteIds(),
'updated_at' => $product->getUpdatedAt(),
'created_at' => $product->getCreatedAt()
);
}
return $result;
And from there we keep track of the last updated_at value and use that as a filter to get the next [LIMIT] items. By default updated_at and created_at are not in the response and the list is not orderred by updated_at so I've added this.
I am not sure of this but you could try this, as the API is working with collections and this is the way to limit a collection size
$filters = array(
'setPageSize' => 10
);

Resources