Add new comment

OpenCart API system

What is it?

API system appeared in OpenCart since OpenCart 2.0. It gives you ability to get access to OpenCart data programmatically.
In theory, it gives you ability to share data between two OpenCart stores or between OpenCart and other CMS or beetwen OpenCart and mobile app or desktop programm etc. 

How does it work?

There is an ability to create OpenCart API keys in the admin area of your store (Menu->Settings->Users->API). Using these keys you can get OpenCart data programmatically. 
For each key you can:
  • set key name
  • generate key code
  • enable or disable it
  • set IP addrees from which you can use this key
  • see sessions of this key
If you have a key, you can access OpenCart from your code.

Autorisation first 

You need to log into OpenCart programmatically before you get ability to get some data.:

$apiKey = 'dzL3oaoqLHXCT3ZEyS4u3in3urBrUAD1kLagTFihrKN8D1XUQewGsxSOSWzibnWs4F414PPxmMuDD';
$curl = curl_init( 'http : // localhost/opencart/2101/index.php?route=api/login/' );
$post = array (
  'key' => $apiKey
curl_setopt_array( $curl, array(
  CURLOPT_POSTFIELDS      => $post
) );
$response = json_decode(curl_exec( $curl ));
if (isset($response->token)) {
  $token = $response->token;
} else {
  // errors handler
  // var_dump($response)

Now we are having a token and we can use this token to send another requests to OpenCart. For examle this code will add a new product to a cart.:

$curl = curl_init( 'http :// localhost/opencart/2101/index.php?route=api/cart/add/&token=' . $token );
$post = array (
  'product_id' => 41
curl_setopt_array( $curl, array(
  CURLOPT_POSTFIELDS      => $post
) );
$response = json_decode(curl_exec( $curl ));


What can we do with OpenCart API?

Unfortunately, not to much. For now, we can only work with a cart. 
We can:

  • add products to the cart
  • get products from the cart
  • change currency
  • add coupons
  • add payment and delivery methods
  • create an order
  • etc.
However, if you need more, you can easily create your own API methods to get another data from OpenCart.

A bit of criticism:

  1. Very few API methods. For now, you can only "buy" some products programmatically. And that is all what you get from the box.
  2. Weak API. You can not set specific key to the specific API method or methods, there are no requests log with information about requests (IP, POST, GET data, response, etc.)
  3. IP for the API key is mandatory. You can not create key which will work for any IP
  4. Uncomfortable errors statuses which are returned by API. Sometimes it is string , sometimes it is object "error" with value "key", sometimes it is "warning", etc. It is difficult to handle all of these statuses.
But of course, they are small flaws, it is very good that API system appears in OpenCart. Everything else what you need, you can add by yourself, every method.
And I hope that OpenCart API system will evolve.
Spam protection
Target Image