Reading list Switch to dark mode

    How to use OpenCart’s Rest API?

    Updated 11 January 2023

    As OpenCart already provides the REST API so we need to learn how to use the API. This is very helpful in order to use a store’s functionality from different devices irrespective of technology.

    In order to start, we have to add a new API. For that, we have to visit System->Users->API from the admin panel.

    addapi
    After clicking the add button, we will get into a form where we have to provide API name and API Key. The API key can be generated automatically after clicking on generate button.

    apikey
    After creating the API Key, we have login into the OpenCart API using the created API key. In this blog, I will tell you about the login part. We will discuss over the other files in further posts.

    In the folder catalog->controller->api, we have several files containing APIs. We have to log-in first, so need to access the login.php file.

    Searching for an experienced
    Opencart Company ?
    Find out More

    We used curl to access the API. The code below will provide you the process of writing flat PHP code to access the API.

    <?php
    
    	$url = "http://my-opencart.com/index.php?route=api/login";
    	$params = array(
    		'key=IENkO5W3VN2vKCEXYO4L6g3zGxM6LC1WdrylZF86gWSjgrBn80jHrIFcysXVCkJeoX1q8YEKwdT7eyaTN8MHSca41kXDpMtf53nN6npVEOOtK6ZL3LEn5eMO4Zj4bPdb14c22iaQJEBB2Lkl0Ef2AzXfdtwhyykDRZXqmVbEHweGkif353u0vdthYSqQtbXZWWD3LceyDUuuI8YGPZ5eflIes8SjM48sCw3h1mZj8w6hGSI1o6TOpuFAs6xjGpkc'
    		); // this array can contain the any number of parameter you need to send
    
    	$parameters = implode('&', $params);
    
    	$ch = curl_init();
    	curl_setopt($ch,CURLOPT_URL, $url);
    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
    	curl_setopt($ch,CURLOPT_POST, $parameter_count);
    	curl_setopt($ch,CURLOPT_POSTFIELDS, $parameters);
    
    	//execute post
    	$result = curl_exec($ch);
    
    	//close connection
    	curl_close($ch);
    
    	print_r($result);
    ?>

    If we run this code, then it will return a JSON object.

    On incorrect API Key:

    incorrectkey

    On correct API Key:

    correctkey
    The token return from the login API is required in order to access other APIs. We will discuss more on OpenCart API development. Thanks 🙂

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    11 comments

  • prasoon
    Hi in which file the above code added?
    i make a new file with name login.php on root but it does not work for me
    • Webkul Support
      Hi,
      It can be added to any PHP file. You have to check if you are requesting a correct URL. The API key must be generated from that specific opencart instance.
  • Ankush Shinde
    class ControllerApiLogin extends Controller {

    public function index() {
    $this->load->language(‘api/login’);

    $json = array();

    $this->load->model(‘account/api’);

    // Login with API Key
    $api_info = $this->model_account_api->getApiByKey( $this->request->post[‘key=’]);

    if ($api_info) {
    // Check if IP is allowed
    $ip_data = array();

    $results = $this->model_account_api->getApiIps($api_info[‘api_id’]);

    foreach ($results as $result) {
    $ip_data[] = trim($result[‘ip’]);
    }

    if (!in_array($this->request->server[‘REMOTE_ADDR’], $ip_data)) {
    $json[‘error’][‘ip’] = sprintf($this->language->get(‘error_ip’), $this->request->server[‘REMOTE_ADDR’]);
    }

    if (!$json) {
    $json[‘success’] = $this->language->get(‘text_success’);

    // We want to create a seperate session so changes do not interfere with the admin user.
    $session_id_old = $this->session->getId();

    $session_id_new = $this->session->createId();

    $this->session->start(‘api’, $session_id_new);

    $this->session->data[‘api_id’] = $api_info[‘api_id’];

    // Close and write the new session.
    //$session->close();

    $this->session->start(‘default’);

    // Create Token
    $json[‘token’] = $this->model_account_api->addApiSession($api_info[‘api_id’], $session_id_new, $this->request->server[‘REMOTE_ADDR’]);
    } else {
    $json[‘error’][‘key’] = $this->language->get(‘error_key’);
    }
    }

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

    }
    }

    This is my login class in php I want to create the login api please help .

    • Webkul Support
      Hi Ankush Shinde,
      Thanks for the query, for sure we will try to cover this in our future blogs.
  • Jansanman
    I’m a total novice at this stuff. How do I ACTUALLY do a do_curl_request to connect to the API? I’ve tried every variation of http://my-opencart-domain.com/index.php?route=api/login that I can think of and I’m unable to log in. When I try to curl anything, I just get a bunch of HTML back with no mention of login success or failure. Can someone provide an example of an actual curl request that will establish the connection?
  • Kshitij Baluni
    Hi, I am getting this error again and again. Please help
    Notice: Undefined index: key in /home/rationat/public_html/catalog/controller/api/login.php on line 25{“error”:{“key”:”Warning: Incorrect API Key!”}}
    • Ivan Kutas
      For me helped:
      1. Add header ‘Content-Type’ : ‘application/x-www-form-urlencoded’
      2. In body use next format “key=your_key”
  • Kshitij Baluni
    Notice: Undefined index: key in /home/rationat/public_html/catalog/controller/api/login.php on line 25{“error”:{“key”:”Warning: Incorrect API Key!”}}
  • Suraj Mandal
    I got an error of your address is 1 you can not access this API. Is that work on localhost.
  • Biplab Rout
    did as you said. but not getting any response
    • Vikhyat Sharma
      What issue are you getting on implementing this? Let me know in detail.
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home