Create a Custom API in OpenCart

Create a Custom API in OpenCart

You’ll need to create custom APIs for unique requirements in your project development at some point in time, and that’s what we’ll cover throughout the course of this tutorial. In our custom API module, we’ll fetch the list of all products available in the store, and it’ll be a JSON encoded output as required by the REST standards in OpenCart.

I assume that you’re familiar with the basic module development process in OpenCart.  Another important point: I’m using the latest version of OpenCart, that is as of writing this, and you should do that too to ensure the compatibility of core APIs.

Without wasting much of your time, I’ll straight away dive into the practical stuff, and that’s what the next section is all about.

A Glance at the File Setup

Let’s have a look at the list of files required for the desired setup.

  • catalog/controller/api/custom.php: It’s a controller file, and most of our application logic resides in this file.
  • catalog/language/en-gb/api/custom.php: It’s a language file that holds language variables.
  • common.php: This file holds the common code for reusability purposes.
  • login.php: It’s a file that demonstrates how to log in to the store using the REST API.
  • products.php: It’s a file that demonstrates how to fetch products using our custom API module.

So, that’s all it takes to set up our custom API module and test it using PHP CURL library.

We’ll start with the controller file, go ahead and create a file catalog/controller/api/custom.php with the following contents.

// catalog/controller/api/custom.php
class ControllerApiCustom extends Controller {
public function products() {
$json = array();

if (!isset($this->session->data[‘api_id’])) {
$json[‘error’][‘warning’] = $this->language->get(‘error_permission’);
} else {
// load model

// get products
$products = $this->model_catalog_product->getProducts();
$json[‘success’][‘products’] = $products;

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’);

Probably, it should be pretty familiar stuff if you’re aware of the structure of OpenCart module files. However, we’ll discuss the important snippets from the products method.

First of all, we have to check the authenticity of the request, and it’s checked by the existence of the api_id variable in the active session. In the case of a valid and authenticated request, we’ll go ahead and fetch all the products using the getProducts method of the core Product model. Of course, it’ll give a permission denied error message in the case of invalid login.

Next, there’s a generic security check to protect against CSRF attacks. It’s accomplished by checking the existence of the HTTP_ORIGIN variable, and adding appropriate headers if it does exist.

Finally, we’ve used the json_encode function to encode the $products array, and the result is passed as an argument of the setOutput method.

Next, we’ll go ahead and create a language file for our module at catalog/language/en-gb/api/custom.php with the following contents.

// catalog/language/english/api/custom.php
// Error
$_[‘error_permission’] = ‘Warning: You do not have permission to access the API!’;

So, that’s it as far as the OpenCart-related file setup is concerned. From the next section onwards, we’ll create the files that help us test our custom API using the PHP CURL library.

How It Works

Before we go ahead and test our custom API module, you should make sure that you’ve created API user credentials from the back-end of OpenCart.

If you haven’t done so yet, it’s pretty easy. Head over to the back-end, navigate to System > Users > API, and add a new API user. While doing so, it’s important to note that you also need to add an IP address from which you’re supposed to make API calls.

Go ahead and create a common.php file and paste the following contents in that file.

function do_curl_request($url, $params=array()) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, ‘/tmp/apicookie.txt’);
curl_setopt($ch, CURLOPT_COOKIEFILE, ‘/tmp/apicookie.txt’);

$params_string = ”;
if (is_array($params) && count($params)) {
foreach($params as $key=>$value) {
$params_string .= $key.’=’.$value.’&’;
rtrim($params_string, ‘&’);

curl_setopt($ch,CURLOPT_POST, count($params));
curl_setopt($ch,CURLOPT_POSTFIELDS, $params_string);

//execute post
$result = curl_exec($ch);

//close connection

return $result;

As you can see, it contains just one function, do_curl_request, which will make a CURL call to the URL passed by the $url argument. The second argument is an array of parameters in case you need to POST the data.

The other important things to note are the CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE settings. These set the file in which the cookies will be stored and read from. As we’ll need to make authenticated calls, it’s a must! Of course, you want to change the path /tmp/apicookie.txt according to your system settings. Make sure that it’s writable by the web server too!

Finally, the function returns the response by the CURL request!

Obviously, the first thing to do is to start the session, and you’ll need to use the login method. Let’s have a look at an example. Go ahead and create a login.php file with the following contents.

require “common.php”;

$url = ‘http://your-opencart-store-url/index.php?route=api/login’;

$fields = array(
‘username’ => ‘demouser’,
‘key’ => ‘ysvF7M1nqNYiZV3GFtU252jhn0FrCWMdH8Kw8qR6DApZ7RSJWCN7S0IvIxnti1QP2wUNsYCaG6vHa2l2q8FTFbWNwNYQUO58CfSYJHHJRG0vt7OBN60BnE5MdEVLBSSJVBZJ7ioFuiAmQN1dmBO56dmaawULlY8lnWFXQimecZznUo7NCJHp3rkL1tOAYgeIUl1oVjzrZ7cayikQEvUtwIGj7Ai4XudDH70E7hKGNJcXPiY5RfgFI8PQ8eLg1FZJ’,

$json = do_curl_request($url, $fields);

First, we’ve included the common.php file created in the previous section. Next, the $url variable defines the API login URL of the OpenCart store. Next, the $fields array holds the API user credentials created earlier.

Finally, we call the do_curl_request method to log in. Importantly, you should see a token variable in the $json object. Note down the value of that variable as we’ll need to pass it while making subsequent API calls.

Next, let’s create a products.php file with the following contents.

require “common.php”;

$url = ‘http://your-opencart-store-url/index.php?route=api/custom/products&token=GtULQW9ZMhhHLi3ooobDukIqTmqOZ1fJ’;
$json = do_curl_request($url, $fields);
$data = json_decode($json);


The important snippet to note in the above example is the route querystring variable. It’s set to the api/custom/products value, which by convention calls the products method defined in the custom.php controller file created at the beginning of this tutorial. Also, we’ve passed the token variable along with its value to make sure that we have access to the API.

Anyway, what we’re interested in is the proper JSON encoded output in the $data variable. And that’s what you should see when you run the products.php file! It should work out of the box if you’ve created proper user credentials and set up the files as explained.

This is just scratching the surface of what the REST API in OpenCart is capable of. In our case, it was a pretty simple yet effective example to demonstrate the topic. Having said that, you could extend it and implement tailor-made solutions according to your requirements.

That’s it for today’s article. Don’t hesitate to ask queries and leave your suggestions as they are valuable!


Today, we’ve discussed how you could create a custom API in OpenCart by creating a custom module. In the process, we went through the complete workflow to achieve the aforementioned functionality.

4 Kudos
You are
awsome 🙂

Simple way to proxy all your traffic trough SSH (LINUX)

Simple way to proxy all your traffic trough SSH (LINUX)

VPS – can be lowend since we only need to connect to it
Machine that will use proxy

1. Setup passwordless ssh access via keys (Linux)

Type this in terminal on main server:

ssh-keygen -t rsa -C mainserver

Skip all password requests with enter key (so you don’t need to use password to connect)

Now you should see the files id_rsa and in your .ssh directory in your home folder:

ls ~/.ssh
authorized_keys  id_rsa  known_hosts

P.S: don’t worry if you don’t have “authorized_keys” or “known_hosts” files 🙂

2. Make it secure:

Connect to remote host and make new user (named proxy here):

adduser proxy

then just press enter until you need to confirm that all information is correct, press y and then enter to create new user

Change default SSH port (22) to something random (Port you can access on remote server)

nano /etc/ssh/sshd_config

Find: "Port 22"

and change it to Port x where x is your choosen port

3. Copy public key to Remote host (Proxy):

cat ~/.ssh/ | ssh proxy@remote-host'install -d -m 700 ~/.ssh; cat >> .ssh/authorized_keys'

4. Try to login with same username that you used to copy public key:

ssh proxy@remote-host

you should be auto connected now

5. Use this as proxy:

ssh -D 1025 proxy@remote-host [-p x (only if you changed port)]

now set local proxy settings to

Firefox Proxy settings

Firefox Proxy settings

Socks host: localhost and port 1025 (or any port you choosen before on -D switch)

6. Make it persistent
as root install screen: “apt-get install screen” and edit /etc/rc.local file

nano /etc/rc.local

and add this line to it

/usr/bin/screen -dmS screenname bash -c 'ssh -C -D 1025 proxy@remote-ip-address' &

“-C” is used to compress traffic and lower bandwith 😉

copy private key from the user you used before (if it wasn’t root sure)

cp /home/proxy/.ssh/id_rsa ~/.ssh/id_rsa

this way ssh proxy will auto start when sytem is booted 🙂

I hope you liked this tutorial, if you don’t understand something or have problems feel free to comment bellow 🙂 Sugestions are appreciated 😉

P.S: you can now use cheap vps to run proxy on them :p

my screens – proxies


Cheap VPS hosting providers:

VirtWire (Recomended: fast servers, cached ssd, low memory avaliable)


3 Kudos
You are
awsome 🙂

My Traffic Value Review

Name: My Traffic ValueMy Traffic Value
Price: Free to Join
Owner: Joel William Cook
Who it is for: Newbie – Expert
Rating: star,full,favourite,bookmarkstar,full,favourite,bookmarkstar,full,favourite,bookmarkstar,full,favourite,bookmarkstar,half,favourite,bookmark

Introduction To My Traffic Value

In this My Traffic Value Review I’m going to show you how the site works and I’m going to explain all the important information.

My Traffic Value (MTV) is a crowdfunding Platform made by Joel William Cook in 2011. Joel William Cook is an expert marketer also founder of Paid Verts who created a stable system which is working for 3 years and growing day by day.


9 Kudos
You are
awsome 🙂

How To Earn Bitcoin Playing Fun Games (No Deposit Needed)

Earn bitcoin playing games

There are a million and two different ways out there to earn bitcoin, from picking up a few Satoshi for filling out captchas on faucet websites, to working a full time job that pays in btc. But all of those things are boring. What you really want is a way to earn yourself some lovely bitcoin whilst doing something which is actually good fun to do. Like playing video games. It may come as a surprise to you to find out just how many different websites and apps there are which include ways for you to earn bitcoin – or earn an internal currency that can be cashed out in bitcoin – whilst playing a fun game. Everything you will find listed on this page is free to play – no deposit needed. I have also taken care to make sure that all of the games are fun to play and, preferably, require some element of skill rather than just straight up luck. As always I welcome suggestions in the comments if you know of anything I’ve missed off these lists, just as long as you don’t spam and only recommend quality.


15 Kudos
You are
awsome 🙂

How to Detect and Effectively Stop Users with AdBlock in WordPress

How to Detect and Effectively Stop Users with AdBlock in WordPress


AdBlock is a simple but effective add-on for web browsers that allows users to disable ads on your WordPress site. This can hurt you by reducing your earning potential. If you are interested in stopping people from using Adblock, then you have arrived to the right place. In this article, I will show you how to detect and deal with people using AdBlock while viewing your WordPress site.


24 Kudos
You are
awsome 🙂

Six ways to make money playing video games

Characters on World of Warcraft have sold for as much as $10,000

Everyone knows there are prizes galore to be won if keen gamers decide to take up the slightly bizarre title of “professional gamer”, with competitions offering large financial rewards for the very best.

But what about if you just want to earn a bit of pocket money from your usual gaming habit without making the leap from “amateur” to “professional”?


10 Kudos
You are
awsome 🙂

10 Creative Ways To Make Money Online

If you’d claimed it was possible for the average guy on the street to make millions of dollars online just a decade ago, the chances are good you’d have heard nothing but laughter in response. Today, though, there are countless Internet millionaires who turned a great idea into obscene profit, used the power of the web to promote their offline business or simply worked their butt off to sell their skills online.


7 Kudos
You are
awsome 🙂