Using the new API methods of OpenCart 2.x

Introduction

In OpenCart 2.x a new API system has been introduced. It allows third party applications to talk to your OpenCart store for better integration capabilities. In this article, we will explain how the API works and how to use it. A good progress has been made on the API and although it is by no means the final version, we believe it is a good idea to get familiar with its current state and the way it works.

Configuration

In order to use any of the API methods, you will need to login first. Login credentials for the API users are managed from OpenCart’s admin panel by going to System > Users > API. Creating a new pair of credentials is pretty straight-forward. After you have obtained your username and password, you are ready to start playing with the API.

Logging in

All of the API controllers are found in the api directory so your base URL, should look similar to this: yourdomain.com/index.php?route=api/controller/method. Here yourdomain.com should be replaced with your actual domain name and controller / method with the needed controller and method from the API. Keep in mind that the method part is optional. If you want to call the default index() function of a controller, you can omit the method from your request URL.

 

In order to login you need to call the index function of the login controller, so the request URL will be: yourdomain.com/index.php?route=api/login. The request type should be POST and the required POST data is “username” and “password“. Each API method returns JSON formatted data. In the case of the login method, it will either return a success message or an error message. So checking whether the returned object has a success or error member will tell you whether the login was successful or not. It will also return a cookie, which is the value of your session ID. You will most probably not need this value, since the cookie’s name is not returned. In order to maintain a session, you will need to extract the cookies from the raw HTTP response and send them with each consequent request.

Adding a product to the cart

After a successful login, you can now interact with the API. One thing you can do is add a product to your cart using the cart/add method. The URL for this operation is:yourdomain.com/index.php?route=api/cart/add. In its most basic form, the method takes aproduct_id and quantity. You can also feed an option array to add the desired product with specific options. If you want to add more than one product, you can pass the method a singleproduct array where each element, should be an array with product_id, quantity, and (not mandatory) option keys.

Note: The bolded words in this section are the names of the POST variables you need to supply.

Explore the API

We cannot cover all of the available API methods here, but we encourage you to go inspect all the files in your catalog/controller/api/ directory. This way you will have an idea of what you can do and what not with the API.

What is missing

Ok, so I showed you how to add an item to the cart, but for that method I told you that you need to supply a product_id. Now you may be wondering how to get a list of the available product IDs – well currently you cannot. This is not implemented yet, and we do not have a way to query the product database, or get a list of options for a particular product. This seems like a pretty solid feature, so we expect that it will be coming in one of the next versions of OpenCart.

A helper library

We thought it would be nice if there was a library to help us work with the API without thinking of cookies, GET / POST parameters and their names – so we created one. You can get a copy from https://github.com/iSenseLabs/OpenCartAPI. The main class is called OpenCart and is in the namespace OpenCart. We tried to keep it consistent with the API URLs, so thecart/add method became the add() method of the cart object of an OpenCart object. Let me show you an example of logging in and adding a product to the cart:

$oc = new OpenCart\OpenCart('yourdomain.com');
if ($oc->login('your_username', 'your_password')) {
   $oc->cart->add(40, 3);
   $cart = $oc->cart->products();
   foreach ($cart['products'] as $product) {
       echo $product['name']."\n";
   }
} else {
   echo $oc->getLastError();
}

You can also save your session for later use, just add a second parameter to the constructor of the OpenCart class. This should be a filename, where the cookie information will be stored. You can point this anywhere in your filesystem. Here is an example of the simplest form:

$oc = new OpenCart\OpenCart('yourdomain.com', 'cookiejar');

And here is a reference of all the methods in our library:

OpenCart->cart->add($product, $quantity = 1, $option = array());
OpenCart->cart->edit($key, $quantity);
OpenCart->cart->remove($key);
OpenCart->cart->products();

OpenCart->order->add($shipping_method = '', $comment = '', $affiliate_id = '', $order_satus_id = '')
OpenCart->order->edit($order_id, $shipping_method = '', $comment = '', $affiliate_id = '', $order_status_id = '')
OpenCart->order->delete($order_id)
OpenCart->order->history($order_id, $order_status_id = '', $notify = '', $append = '', $comment = '')

OpenCart->payment->address($firstname = '', $lastname = '', $company = '', $address_1 = '', $address_2 = '', $postcode = '', $city = '', $zone_id = '', $country_id = '')
OpenCart->payment->methods()
OpenCart->payment->method($payment_method)

OpenCart->shipping->address($firstname = '', $lastname = '', $company = '', $address_1 = '', $address_2 = '', $postcode = '', $city = '', $zone_id = '', $country_id = '')
OpenCart->shipping->methods()
OpenCart->shipping->method($shipping_method)

OpenCart->reward->add($reward)
OpenCart->reward->maximum()
OpenCart->reward->available()

OpenCart->voucher->apply($voucher)
OpenCart->voucher->add($voucher_from_name = '', $from_email = '', $to_name = '', $to_email = '', $voucher_theme_id = '', $message = '', $amount = '')

OpenCart($url, $sessionFile = '')
OpenCart->getUrl($method)
OpenCart->getCookie()
OpenCart->getLastError()
OpenCart->login($username, $password)
OpenCart->coupon($coupon)
OpenCart->customer($customer_id = 0, $customer_group_id = 0, $firstname = '', $lastname = '', $email = '', $telephone = '', $fax = '')

Final words

We hope this will help you get started with the OpenCart API. Feel free to suggest API functionality you think will be useful to the OpenCart project in GitHub:https://github.com/opencart/opencart