神刀安全网

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. Here’s a nicearticle providing comprehensive insight into the subject just in case you would like to skip through it. Another important point: I’m using the latest version of OpenCart, that is 2.1.0.2 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.

<?php // catalog/controller/api/custom.php class ControllerApiCustom extends Controller {   public function products() {     $this->load->language('api/custom');     $json = array();      if (!isset($this->session->data['api_id'])) {       $json['error']['warning'] = $this->language->get('error_permission');     } else {       // load model       $this->load->model('catalog/product');        // 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');     $this->response->setOutput(json_encode($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.

<?php // 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.

<?php 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   curl_close($ch);    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.

<?php 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); var_dump($json);

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.

<?php 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);  var_dump($data);

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!

Conclusion

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.

You could reach me via the feed section below, and I also spend a bit of time on Twitter if you prefer to contact me there!

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Create a Custom API in OpenCart

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址