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.

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)


How to detect Malicious code in nulled or Free WordPress Themes and Plugins.


Apart from Official WordPress repository there are hundreds and thousands of websites which provides free WordPress themes and Plugins but the problem is you can not trust them always.

Yes, Most of them add a malicious code to themes and plugins which is not too easy for you to find out.

Before learning about the cure lets discuss about the cause.

Here  is why they add their custom codes

  • To get backlink from your blog unknowingly
  • To get access to your blog
  • To redirect your blog to spam links
  • To add their advertisements and banners.
  • or to simply get your website down

Not only free themes and plugins also the premium nulled plugins and themes that you have download from Warez and torrents may also infected by these malicious codes.

My Confessions

Did  you wonder what triggered me write this article ?

Yes, I too fell prey to these free plugins.Few days back, I was desperate to download a very famous nulled plugin from warez and after installing it in my blog I got to know that the plugin was infected and it redirects my blog to a spam blog.

I immediately disabled the plugin and checked for the code that caused the redirection in plugin files. After an hour I found the code and immediately removed it [ I don’t use that plugin now ]

This incident taught me very important thing.

Never trust nulled WordPress plugins and themes

However many of you might want to use those nulled or free plugins and themes for God’s Sake, If you are one of them then read the remaining article

Detecting Malicious codes

After downloading the plugin or theme,The first thing you should do is to check for virus,trojans and other worms that you may not like it.

Check for Virus and Trojans

Go to and upload the zip file to check for virus.

If your file is infected you will get a red signal and if not then you can move on to next step.

VirusTotal Scan result

VirusTotal Scan result

Check for unwanted codes in Plugins

Now lets check for unwanted codes in plugins using another WordPress plugin called Exploit Scanner,which can be securely downloaded from WordPress website.

After installing it go to Dashboard >> Tools >> Exploit Scanner and run the scan.It will take some time to complete the scan and the time depends on number of plugins you have installed.

After the scan you can see a list of codes that are suspected.You can use the browser search function to find the plugins that you installed from outside WordPress repository.

Exploit Scanner

Exploit Scanner

[mybox]Note : This plugin will also scan themes but you might to be interested to try the tip that I am about to give next.[/mybox]

Check for Theme authenticity

Adding a backlink in a free theme is very common technique but you can easily find those exploited themes by the plugin called Theme Authenticity Checker (TAC).

Install the plugin and go to Dashboard >> Appearance >> TAC

You can see the list of themes installed with their authenticity result.It will give a warning if any encrypted links are found in a theme.

Theme Authenticity Checker

Theme Authenticity Checker

Security is in your hands

Its very rare to get hacked unless,We make mistake.So,security is in your hand : Either Act wisely or get fooled easily.

How to upgrade your ordinary router with functionality of a high cost one with Tomato firmware


Here is how to install Tomato firmware on your cheap Wi-Fi router to attain functionality of a high cost router.

What if you could simply enhance your router’s functionalities just by some software alteration. well, Few people understand why some routers cost $15 and some hundreds of dollars.

There are hardware differences and… software differences.

Using a custom firmware (if supported by the router) can give you options/features available on much more expensive hardware.

Such a firmware is Tomato USB. Its an open source firmware for Broadcomm based routers.

The first step is to see if your router is supported by Tomato, so please check Shibby Tomato Builds. If it is, get the newest version and flash it on the administration interface.

Usually, there are some flavors: AIO (All in One) or VPN (few features, smaller size, perfect for most users).

If it cannot be flashed through Web interface (like Asus RT-N53), you must use the emergency procedure (see router documentation) to upload the custom firmware to the router.

After you install and set up all the usual settings on Tomato (WIFI, LAN etc.), you can go further, and with some work, you can install many programs, for example a webserver with PHP support or Transmission Torrent client (the router must have USB ports).

Different routers have different flash memory sizes. Inside the flash reside the firmware and settings. Depending on the flash size and firmware size (VPN or AIO), some unused space might still remain, so you can create a JFFS partition to install software. This is critical for routers without USB or if you do not want to use a USB drive. If you do want to use a USB drive, read here how to create a partition, and after you create it, continue this tutorial from Step 3.

Okay lets start.
Step 1: Create a JFFS partition.
Go to Administration – JFFS – Enable – Format Erase

In the text box paste:

mount -o bind /jffs /opt

Wait a few minutes, and if you do not get any message, reboot the router.

Step 2:
Go to Administration – Admin Access and modify the default port settings for router administration (ex: 8082).
This will allow you to access your router on specified port.


Step 3:
3. Access the router on SSH using Putty (Windows) or Terminal (Mac).

On Mac, the command is:

ssh -l root IP

Username must be root and the password of the admin user.

Step 4:
Install Optware package manager by using the following code.

cd /tmp

wget–files/tut:optware-installation/ -O – | tr -d ‘\r’ > /tmp/

chmod 755


Note that it may take time depending on your internet speed and your router’s processing power.

Step 5:
Install nano (text editor), lighttpd (webserver), and PHP

ipkg install nano
ipkg install lighttpd
ipkg install php-fcgi

Step 6: Edit the lighttpd configuration file.

nano /opt/etc/lighttpd/lighttpd.conf

and add this:

server.event-handler =”poll”

Modify the default running port of the webserver (default is 8081).

server.port = 80

Save everything and close nano.

Step 7:
Restart the webserver.

/opt/etc/init.d/S80lighttpd restart

Now you can put files and scripts in /opt/share/www/

If you want your webserver to be accessible from WAN, you need to add those lines to the Firewall script (Administration – Scripts – Firewall):

iptables -t filter -A INPUT -p tcp –dport 80 -j ACCEPT
iptables -t filter -A INPUT -p tcp –dport 443 -j ACCEPT

Its done! now enjoy the features on your budget router. Do post your queries or suggestions in the comments.

The 11 Phases of a Web Developer’s Career (As Illustrated by Memes)

The career of a web developer is an interesting one with many slopes. Considering a learning curve this steep, you can fully expect to live through periods of frustration, enlightenment, self-righteousness, and every mindset in between. In this article, we’ll have some fun, by reviewing each of these phases through the lens of a meme!

Complete Noob

We all have warm feelings for the early days of our careers; the period when you have absolutely no clue what you’re doing. Like a fish out of water, each new line of code is a mystery. Doctype? Huh? What the heck does a <div> do? The first phase is an intimidating, scary, but exciting one. How many dang languages are there?


Cross Site Request Forgery (CSRF) [HOW-TO]

Cross-Site Request Forgery (CSRF) is an attack outlined in the OWASP Top 10 whereby a malicious website will send a request to a web application that a user is already authenticated against from a different website. This way an attacker can access functionality in a target web application via the victim’s already authenticated browser. Targets include web applications like social media, in-browser email clients, online banking and web interfaces for network devices.



In this article we will learn about subnetting   (sub + netting) in which sub means division and netting means network i.e. division of network. Subnetting is a process of division of large network into smaller networks.Here we will learn about subnetting of Class A , Class B. and Class C of  IPV4 ((Internet Protocol Version)



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.


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”?