Back to Top

How To Use Shipping Api In Opencart

Updated 26 July 2023

Today we will learn, how to use shipping API in an open cart and where the open cart uses this shipping API.

Opencart uses the shipping API in the shipping details section while adding or editing the order from the admin end. After adding the payment details from the sales->orders when we click the continue button, then it goes to the shipping details section.

Images

After selecting or adding the shipping address from the shipping details section when we click the continue button. Two methods of payment API will be called: address and methods.

The address method is used to set the shipping address of the order.

Searching for an experienced
Opencart Company ?
Find out More

The method validates the address values and if all values are following the norms then, it sets the address values into the session. The code of the address method is given below :

/**
 * Webkul Software.
 *
 * @category Webkul
 * @package api
 * @author Webkul
 * @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
 * @license https://store.webkul.com/license.html
 */

public function address() {
	$this->load->language('api/shipping');

	// Delete old shipping address, shipping methods and method so not to cause any issues if there is an error
	unset($this->session->data['shipping_address']);
	unset($this->session->data['shipping_methods']);
	unset($this->session->data['shipping_method']);

	$json = array();

	if ($this->cart->hasShipping()) {
		// Check for api login
		if (!isset($this->session->data['api_id'])) {
			$json['error']['warning'] = $this->language->get('error_permission');
		} else {
			// Add keys for missing post vars
			$keys = array(
				'firstname',
				'lastname',
				'company',
				'address_1',
				'address_2',
				'postcode',
				'city',
				'zone_id',
				'country_id'
			);

			foreach ($keys as $key) {
				if (!isset($this->request->post[$key])) {
					$this->request->post[$key] = '';
				}
			}

			// Shipping address fields validation
			if ((utf8_strlen(trim($this->request->post['firstname'])) < 1) || (utf8_strlen(trim($this->request->post['firstname'])) > 32)) {
				$json['error']['firstname'] = $this->language->get('error_firstname');
			}

			if ((utf8_strlen(trim($this->request->post['lastname'])) < 1) || (utf8_strlen(trim($this->request->post['lastname'])) > 32)) {
				$json['error']['lastname'] = $this->language->get('error_lastname');
			}

			if ((utf8_strlen(trim($this->request->post['address_1'])) < 3) || (utf8_strlen(trim($this->request->post['address_1'])) > 128)) {
				$json['error']['address_1'] = $this->language->get('error_address_1');
			}

			if ((utf8_strlen($this->request->post['city']) < 2) || (utf8_strlen($this->request->post['city']) > 32)) {
				$json['error']['city'] = $this->language->get('error_city');
			}

			$this->load->model('localisation/country');

			$country_info = $this->model_localisation_country->getCountry($this->request->post['country_id']);

			if ($country_info && $country_info['postcode_required'] && (utf8_strlen(trim($this->request->post['postcode'])) < 2 || utf8_strlen(trim($this->request->post['postcode'])) > 10)) {
				$json['error']['postcode'] = $this->language->get('error_postcode');
			}

			if ($this->request->post['country_id'] == '') {
				$json['error']['country'] = $this->language->get('error_country');
			}

			if (!isset($this->request->post['zone_id']) || $this->request->post['zone_id'] == '') {
				$json['error']['zone'] = $this->language->get('error_zone');
			}

			// Custom field validation
			$this->load->model('account/custom_field');

			$custom_fields = $this->model_account_custom_field->getCustomFields($this->config->get('config_customer_group_id'));

			foreach ($custom_fields as $custom_field) {
				if (($custom_field['location'] == 'address') && $custom_field['required'] && empty($this->request->post['custom_field'][$custom_field['custom_field_id']])) {
					$json['error']['custom_field' . $custom_field['custom_field_id']] = sprintf($this->language->get('error_custom_field'), $custom_field['name']);
				}
			}

			if (!$json) {
				$this->load->model('localisation/country');

				$country_info = $this->model_localisation_country->getCountry($this->request->post['country_id']);

				if ($country_info) {
					$country = $country_info['name'];
					$iso_code_2 = $country_info['iso_code_2'];
					$iso_code_3 = $country_info['iso_code_3'];
					$address_format = $country_info['address_format'];
				} else {
					$country = '';
					$iso_code_2 = '';
					$iso_code_3 = '';
					$address_format = '';
				}

				$this->load->model('localisation/zone');

				$zone_info = $this->model_localisation_zone->getZone($this->request->post['zone_id']);

				if ($zone_info) {
					$zone = $zone_info['name'];
					$zone_code = $zone_info['code'];
				} else {
					$zone = '';
					$zone_code = '';
				}
				//If all fields are valid then set the shipping address in the session
				$this->session->data['shipping_address'] = array(
					'firstname'      => $this->request->post['firstname'],
					'lastname'       => $this->request->post['lastname'],
					'company'        => $this->request->post['company'],
					'address_1'      => $this->request->post['address_1'],
					'address_2'      => $this->request->post['address_2'],
					'postcode'       => $this->request->post['postcode'],
					'city'           => $this->request->post['city'],
					'zone_id'        => $this->request->post['zone_id'],
					'zone'           => $zone,
					'zone_code'      => $zone_code,
					'country_id'     => $this->request->post['country_id'],
					'country'        => $country,
					'iso_code_2'     => $iso_code_2,
					'iso_code_3'     => $iso_code_3,
					'address_format' => $address_format,
					'custom_field'   => isset($this->request->post['custom_field']) ? $this->request->post['custom_field'] : array()
				);

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

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

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

If an address is successfully saved in the session then, it returns the success message as the response.

Images

The second method is “methods”. The method is used to get the list of shipping methods that can be applied to a particular order based on the shipping address. The code of the method is given below:

/**
 * Webkul Software.
 *
 * @category Webkul
 * @package api
 * @author Webkul
 * @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
 * @license https://store.webkul.com/license.html
 */

public function methods() {
	$this->load->language('api/shipping');

	// Delete past shipping methods and method just in case there is an error
	unset($this->session->data['shipping_methods']);
	unset($this->session->data['shipping_method']);

	$json = array();

	//Check for api login
	if (!isset($this->session->data['api_id'])) {
		$json['error'] = $this->language->get('error_permission');
	} elseif ($this->cart->hasShipping()) {
		if (!isset($this->session->data['shipping_address'])) {
			$json['error'] = $this->language->get('error_address');
		}

		if (!$json) {
			// Shipping Methods
			$json['shipping_methods'] = array();

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

			//Get the shipping methods
			$results = $this->model_extension_extension->getExtensions('shipping');

			foreach ($results as $result) {
				if ($this->config->get($result['code'] . '_status')) {
					$this->load->model('shipping/' . $result['code']);

					$quote = $this->{'model_shipping_' . $result['code']}->getQuote($this->session->data['shipping_address']);

					if ($quote) {
						$json['shipping_methods'][$result['code']] = array(
							'title'      => $quote['title'],
							'quote'      => $quote['quote'],
							'sort_order' => $quote['sort_order'],
							'error'      => $quote['error']
						);
					}
				}
			}

			$sort_order = array();

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

			array_multisort($sort_order, SORT_ASC, $json['shipping_methods']);

			//Set the shipping methods in the session
			if ($json['shipping_methods']) {
				$this->session->data['shipping_methods'] = $json['shipping_methods'];
			} else {
				$json['error'] = $this->language->get('error_no_shipping');
			}
		}
	} else {
		$json['shipping_methods'] = array();
	}

	if (isset($this->request->server['HTTP_ORIGIN'])) {
		$this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
		$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
		$this->response->addHeader('Access-Control-Max-Age: 1000');
		$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
	}

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

If the method successfully fetches the available shipping methods then it returns the list of available shipping methods.

Image

In the shipping API, there is one more method named “method”.

The method is used to set the shipping method that will be applied to the current order.

Opencart uses this method in the last step of order creation from the admin end as shown below. The method is called when we click the apply button(placed on the right side of the shipping method).

Image

The code of the method is given below :

/**
 * Webkul Software.
 *
 * @category Webkul
 * @package api
 * @author Webkul
 * @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
 * @license https://store.webkul.com/license.html
 */

public function method() {
	$this->load->language('api/shipping');

	// Delete old shipping method so not to cause any issues if there is an error
	unset($this->session->data['shipping_method']);

	$json = array();

	//Check for api login
	if (!isset($this->session->data['api_id'])) {
		$json['error'] = $this->language->get('error_permission');
	} else {
		if ($this->cart->hasShipping()) {
			// Shipping Address
			if (!isset($this->session->data['shipping_address'])) {
				$json['error'] = $this->language->get('error_address');
			}

			// Shipping Method
			if (empty($this->session->data['shipping_methods'])) {
				$json['error'] = $this->language->get('error_no_shipping');
			} elseif (!isset($this->request->post['shipping_method'])) {
				$json['error'] = $this->language->get('error_method');
			} else {
				$shipping = explode('.', $this->request->post['shipping_method']);

				if (!isset($shipping[0]) || !isset($shipping[1]) || !isset($this->session->data['shipping_methods'][$shipping[0]]['quote'][$shipping[1]])) {
					$json['error'] = $this->language->get('error_method');
				}
			}

			// If no error then save the shipping method in the session
			if (!$json) {
				$this->session->data['shipping_method'] = $this->session->data['shipping_methods'][$shipping[0]]['quote'][$shipping[1]];

				$json['success'] = $this->language->get('text_method');
			}
		} else {
			unset($this->session->data['shipping_address']);
			unset($this->session->data['shipping_method']);
			unset($this->session->data['shipping_methods']);
		}
	}

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

If the shipping method is successfully applied, then it returns the success message as given below :

Image

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home