Quantcast
Channel: Webkul Blog
Viewing all articles
Browse latest Browse all 5490

How to use cart api in Opencart

$
0
0

In our previous blog : http://webkul.com/blog/use-customer-api-opencart/  , we learnt how to use customer api in opencart . Today we will learn , how use cart api in opencart  .

Opencart uses the cart api in the product section while adding or editing the order from the admin end . After adding the customer from the  sales->orders then add/edit  when we click the continue button , then it goes to the product section .

After selecting the product when , we click on add product button , Two methods of the cart api will be called  .First is ‘add’ . The add method is used to add the product into the cart . The code is given below:

/**
 * Webkul Software.
 *
 * @category Webkul
 * @package api
 * @author Webkul
 * @copyright Copyright (c) 2010-2017 Webkul Software Private Limited (https://webkul.com)
 * @license https://store.webkul.com/license.html
 */
public function add() {
	$this->load->language('api/cart');

	$json = array();

	//Check for api login
	if (!isset($this->session->data['api_id'])) {
		$json['error']['warning'] = $this->language->get('error_permission');
	} else {
		//Condition is true when when we edit the order from the admin end
		if (isset($this->request->post['product'])) {
			$this->cart->clear();

			foreach ($this->request->post['product'] as $product) {
				if (isset($product['option'])) {
					$option = $product['option'];
				} else {
					$option = array();
				}

				$this->cart->add($product['product_id'], $product['quantity'], $option);
			}

			$json['success'] = $this->language->get('text_success');

			unset($this->session->data['shipping_method']);
			unset($this->session->data['shipping_methods']);
			unset($this->session->data['payment_method']);
			unset($this->session->data['payment_methods']);
		//Condition is true when we add the product in the order from the admin end
		} elseif (isset($this->request->post['product_id'])) {
			$this->load->model('catalog/product');

			//Get the product information
			$product_info = $this->model_catalog_product->getProduct($this->request->post['product_id']);

			if ($product_info) {
				if (isset($this->request->post['quantity'])) {
					$quantity = $this->request->post['quantity'];
				} else {
					$quantity = 1;
				}

				if (isset($this->request->post['option'])) {
					$option = array_filter($this->request->post['option']);
				} else {
					$option = array();
				}

				$product_options = $this->model_catalog_product->getProductOptions($this->request->post['product_id']);

				foreach ($product_options as $product_option) {
					if ($product_option['required'] && empty($option[$product_option['product_option_id']])) {
						$json['error']['option'][$product_option['product_option_id']] = sprintf($this->language->get('error_required'), $product_option['name']);
					}
				}

				if (!isset($json['error']['option'])) {
					$this->cart->add($this->request->post['product_id'], $quantity, $option);

					$json['success'] = $this->language->get('text_success');

					unset($this->session->data['shipping_method']);
					unset($this->session->data['shipping_methods']);
					unset($this->session->data['payment_method']);
					unset($this->session->data['payment_methods']);
				}
			} else {
				$json['error']['store'] = $this->language->get('error_store');
			}
		}
	}

	//Response in json format
	$this->response->addHeader('Content-Type: application/json');
	$this->response->setOutput(json_encode($json));
}

If product is added successfully then add method will return the success message.

After adding the product , ‘products’ method will be called . The ‘products’ method is used to fetch the cart products .The code is given below:

/**
 * Webkul Software.
 *
 * @category Webkul
 * @package api
 * @author Webkul
 * @copyright Copyright (c) 2010-2017 Webkul Software Private Limited (https://webkul.com)
 * @license https://store.webkul.com/license.html
 */
public function products() {
	$this->load->language('api/cart');

	$json = array();

	//Check for api login
	if (!isset($this->session->data['api_id'])) {
		$json['error']['warning'] = $this->language->get('error_permission');
	} else {
		// Stock
		if (!$this->cart->hasStock() && (!$this->config->get('config_stock_checkout') || $this->config->get('config_stock_warning'))) {
			$json['error']['stock'] = $this->language->get('error_stock');
		}

		// Products
		$json['products'] = array();

		$products = $this->cart->getProducts();

		foreach ($products as $product) {
			$product_total = 0;

			foreach ($products as $product_2) {
				if ($product_2['product_id'] == $product['product_id']) {
					$product_total += $product_2['quantity'];
				}
			}

			if ($product['minimum'] > $product_total) {
				$json['error']['minimum'][] = sprintf($this->language->get('error_minimum'), $product['name'], $product['minimum']);
			}

			$option_data = array();

			foreach ($product['option'] as $option) {
				$option_data[] = array(
					'product_option_id'       => $option['product_option_id'],
					'product_option_value_id' => $option['product_option_value_id'],
					'name'                    => $option['name'],
					'value'                   => $option['value'],
					'type'                    => $option['type']
				);
			}

			$json['products'][] = array(
				'cart_id'    => $product['cart_id'],
				'product_id' => $product['product_id'],
				'name'       => $product['name'],
				'model'      => $product['model'],
				'option'     => $option_data,
				'quantity'   => $product['quantity'],
				'stock'      => $product['stock'] ? true : !(!$this->config->get('config_stock_checkout') || $this->config->get('config_stock_warning')),
				'shipping'   => $product['shipping'],
				'price'      => $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']),
				'total'      => $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')) * $product['quantity'], $this->session->data['currency']),
				'reward'     => $product['reward']
			);
		}

		// Voucher
		$json['vouchers'] = array();

		if (!empty($this->session->data['vouchers'])) {
			foreach ($this->session->data['vouchers'] as $key => $voucher) {
				$json['vouchers'][] = array(
					'code'             => $voucher['code'],
					'description'      => $voucher['description'],
					'from_name'        => $voucher['from_name'],
					'from_email'       => $voucher['from_email'],
					'to_name'          => $voucher['to_name'],
					'to_email'         => $voucher['to_email'],
					'voucher_theme_id' => $voucher['voucher_theme_id'],
					'message'          => $voucher['message'],
					'price'            => $this->currency->format($voucher['amount'], $this->session->data['currency']),			
					'amount'           => $voucher['amount']
				);
			}
		}

		// Totals
		$this->load->model('extension/extension');

		$totals = array();
		$taxes = $this->cart->getTaxes();
		$total = 0;

		// Because __call can not keep var references so we put them into an array. 
		$total_data = array(
			'totals' => &$totals,
			'taxes'  => &$taxes,
			'total'  => &$total
		);
		
		$sort_order = array();

		$results = $this->model_extension_extension->getExtensions('total');

		foreach ($results as $key => $value) {
			$sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
		}

		array_multisort($sort_order, SORT_ASC, $results);

		foreach ($results as $result) {
			if ($this->config->get($result['code'] . '_status')) {
				$this->load->model('total/' . $result['code']);
				
				// We have to put the totals in an array so that they pass by reference.
				$this->{'model_total_' . $result['code']}->getTotal($total_data);
			}
		}

		$sort_order = array();

		foreach ($totals as $key => $value) {
			$sort_order[$key] = $value['sort_order'];
		}

		array_multisort($sort_order, SORT_ASC, $totals);

		$json['totals'] = array();

		foreach ($totals as $total) {
			$json['totals'][] = array(
				'title' => $total['title'],
				'text'  => $this->currency->format($total['value'], $this->session->data['currency'])
			);
		}
	}

	//Response in json format
	$this->response->addHeader('Content-Type: application/json');
	$this->response->setOutput(json_encode($json));
}

If products fetched successfully , then it will return the details of the product that are currently in the cart . The response will look like as follows :

We can also remove the added product by clicking the remove button placed in the action column of product table . When we click the remove button , remove method of cart api will be called . The code for remove method is :

/**
 * Webkul Software.
 *
 * @category Webkul
 * @package api
 * @author Webkul
 * @copyright Copyright (c) 2010-2017 Webkul Software Private Limited (https://webkul.com)
 * @license https://store.webkul.com/license.html
 */
public function remove() {
	$this->load->language('api/cart');

	$json = array();

	if (!isset($this->session->data['api_id'])) {
		$json['error'] = $this->language->get('error_permission');
	} else {
		// Remove
		if (isset($this->request->post['key'])) {
			$this->cart->remove($this->request->post['key']);

			unset($this->session->data['vouchers'][$this->request->post['key']]);

			$json['success'] = $this->language->get('text_success');

			unset($this->session->data['shipping_method']);
			unset($this->session->data['shipping_methods']);
			unset($this->session->data['payment_method']);
			unset($this->session->data['payment_methods']);
			unset($this->session->data['reward']);
		}
	}

	//Resonse in json format
	$this->response->addHeader('Content-Type: application/json');
	$this->response->setOutput(json_encode($json));
}

If product successfully removed , then it will return the success method as given below :

 


Viewing all articles
Browse latest Browse all 5490

Trending Articles