简体   繁体   中英

Opencart 2 API session issues

I'm trying to use the OpenCart 2 API but I'm not entirely familiar with it, nor Opencart in general TBH.

I have created an API key in the admin area, and I can successfully communicate with the API from an external source by passing the username, password and API key itself, and I get a success message.

Example:

$url = "http://opencart.local:8888/index.php?route=api/login";
$postData = array(
        "username" => $username,
        "password" => $password,
        "key" => $key
    );

$handle = curl_init($url);
curl_setopt($handle, CURLOPT_HEADER, true);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($postData));

$response = curl_exec($handle);

$header_size = curl_getinfo($handle, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $header_size);
$response = substr($response, $header_size);

curl_close($handle);

$return = json_decode($response, true);

The return response is as follows:

array(2) { ["success"]=> string(42) "Success: API session successfully started!" ["token"]=> string(32) "rfjOIzMWobWSvKvdy2LnWsekp9v1qoQQ" }

Then, after that, I call the cart/add function in the API, to add a product (by ID) to the cart:

$url = "http://opencart.local:8888/index.php?route=api/cart/add";
$cartData = array(
        "product_id" => '47',
        "quantity" => '1'
    );

which I CURL in the same way, but the response I get from OpenCart is:

array(1) { ["error"]=> array(1) { ["warning"]=> string(54) "Warning: You do not have permission to access the API!" } }

When I check the problem, it seems that the api_id which is required by opencart in order to grant permission is missing:

$this->session->data['api_id']

even though this is set when logging in through the API. It's somehow losing this session data when I do the second call to add a product to the cart. Bearing in mind that when this launches live, I will have no access to the OpenCart code as this is an external CRM which will only be able to communicate via the API with only the username, password and API Key.

Any ideas? I would appreciate any help as I'm a noob to OpenCart!

Thank you

I had a similar experience; I accidentally deleted the API key and created a new one, but the API just stopped working.

I found out that $this->config->get('config_api_id'); always returns '1'. So changed my newly created API key api_id value to 1 on the database and it worked.

I am using Version 2.1.0.1

You need to pass a file for the cookies, in the curl options. Almost all authenticaions need it to write and read: curl_setopt($handle, CURLOPT_COOKIEJAR, 'cookie_file.txt');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM