6

I have this basic API script:

<?php
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(-1);

    $usr = [
        'username' => 'username',
        'password' => 'somePassword'
    ];

    $ch = curl_init('https://magentostore/index.php/rest/V1/integration/admin/token');

    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($usr));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Content-Length: '. strlen(json_encode($usr))]);

    $token = curl_exec($ch);

    echo '<pre>';
    print_r($token);
    echo '</pre>';

    echo '========================';

    $ch = curl_init('https://magentostore/index.php/rest/V1/orders/1');

    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Authorization: Bearer '. json_decode($token)]);

    $result = curl_exec($ch);

    $result = json_decode($result, 1);
    echo '<pre>'. print_r($result) .'</pre>';

but it returns this message:

Array ( [message] => Consumer is not authorized to access %resources [parameters] => Array ( [resources] => Magento_Sales::sales ) )

I'm not sure why, my script should work but I can't figure out why? Is it because of username account permissions? Shouldn't be as user = admin. Just trying to get array of orders ...

Alternative testing method that yielded same results:

I did:

curl -X POST 'https://magentostore/index.php/rest/V1/integration/admin/token' \
-H 'Content-Type:application/xml' \
-d '<login><username>admin</username><password>password</password></login>'

which got me the Token, which I then used like this:

curl -X GET https://magentostore/index.php/rest/V1/orders/1' -H 'Authorization: Bearer <Token that was returned>'

which gets me the same error as above

Edit:

I've tried with a few different API Endpoints and some work (like getting categories) but /orders still doesn't. I've tried on 3 separate environments and only 1 works:

Env One - Doesn't Work

  • OS: CentOS 7
  • PHP Version: 7.1
  • Magento Version: 2.2.5
  • Hosted outside of LAN

Env Two - Doesn't Work

  • OS: CentOS 7
  • PHP Version: 7.0
  • Magento Version: 2.2.5
  • Hosted outside of LAN

Env Three - DOES WORK

  • OS: Linux Mint 19
  • PHP Version: 7.2
  • Magento Version: 2.3-develop
  • localhost
12
  • are you sure you passing admin's username and password correct. Oct 1, 2018 at 14:24
  • @AdityaShah as sure as a sea
    – treyBake
    Oct 1, 2018 at 14:25
  • Okay, do you have POSTMAN ? Oct 1, 2018 at 14:26
  • @AdityaShah no .. seems not needed? Just a way to develop APIs in IDE-format no?
    – treyBake
    Oct 1, 2018 at 14:28
  • No, just to get token with url - just for testing purpose Oct 1, 2018 at 14:30

8 Answers 8

8

1. First setup Integrations

Open the System > Extensions > Integrations

enter image description here

Add New Integration

enter image description here

Set the integration Name and other settings, then specify your Magento 2 back-end password in the Your Password field

enter image description here

Switch to the API sidebar tab and select the resources which will be available to OAuth clients:

enter image description here

Press the Save button. The integration will be saved and the Integrations list will be shown again. Press the Activate link in the integration row:

enter image description here

A confirmation screen will be shown. Press the Allow button

enter image description here

The credentials screen will be shown. Use them in your third-party software to access your Magento 2 as OAuth server.

You will see:

  • Consumer Key
  • Consumer Secret
  • Access Token
  • Access Token Secret

Copy it to somewhere, then press the Done button.

enter image description here

The integration will be saved and the Integrations list will be shown again. You will see your integration in the Active state: enter image description here

2. Now get admin token


<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "http://magento.host/index.php/rest/V1/integration/admin/token?username=admin&password=admin123",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_HTTPHEADER => array(
    "Cache-Control: no-cache",
    "Postman-Token: b7d053fe-df0d-4a85-ab82-4093a9be9d15"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

3. add that Admin token

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "http://magento.host/index.php/rest/V1/orders/1",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "Authorization: Bearer <YOUR ADMIN TOKEN>",
    "Cache-Control: no-cache",
    "Postman-Token: 1057fee5-abde-4a88-bd39-2a623ca995e6"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
10
  • 1
    same error :/ - just a different way of getting to it
    – treyBake
    Oct 1, 2018 at 14:47
  • woh, share me your actual url Oct 1, 2018 at 14:47
  • forget about it, just tell me are you getting any admin TOKEN ? Oct 1, 2018 at 14:48
  • yeah I do - it's already specified in question ^^
    – treyBake
    Oct 1, 2018 at 14:53
  • 1
    I use admin token and it working for me. Jul 28, 2022 at 2:22
1

I had the same Problem. In my case, the response of the token was wrapped in "", which passed to the next calling function could of cause not work. So I just stripped the "" from the response, and than it worked for me. Here is my working code to update the stock of an item via sku:

$config = array(
    'shop_url' => "%YOUR_SHOP_URL%",
    'username' => "%YOUR_ADMIN_BACKEND_USER%",
    'password' => "%YOUR_ADMIN_BACKEND_PASSWORD%",
);

$testSKU = "%YOUR_TEST_SKU%";


// Request Admin Token 
$url = $config['shop_url']."/rest/all/V1/integration/admin/token";

$data = "{ \"username\": \"".$config['username']."\", \"password\": \"".$config['password']."\"}";

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST,  "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: application/json','accept: application/json')); 
curl_setopt($ch, CURLOPT_POSTFIELDS,     $data );

$response = curl_exec($ch);

if (!$response) 
{
    echo 'ERROR';
}

echo '<pre>';
var_dump($response);
echo '</pre>';

// Strip Response from unwanted Characters to save it as token
$token = str_ireplace('"', '', $response);


// Update qty for sku
$url = $config['shop_url']."/rest/V1/products/".$testSKU."/stockItems/1";

$data = '{"stockItem":{"qty":123}}';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST,  "PUT");
curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: application/json','accept: application/json', 'Authorization: Bearer '.$token));
curl_setopt($ch, CURLOPT_POSTFIELDS,     $data );

$response = curl_exec($ch);

if (!$response) 
{
    echo 'ERROR';
}

echo '<pre>';
var_dump($response);
echo '</pre>';

Tested on Magento 2.3.2

1
0

The APi user 'username' => 'username' does not have proper access at sales section.

Please go to admin>System>Extension>Intregation and open check your user is active or not .

Second , this user is active then please check open that use and check it resource area setting

1
  • 1
    what if the API user = admin user of Magento panel?
    – treyBake
    Oct 1, 2018 at 14:29
0

Try changing the PHP handler used by Apache on the Magento server. I also thought it was the PHP version, but then I realised the working version was using a different handler. I changed from cgi to suphp for the PHP version that was not working and the requests started to work. Interestingly, as mentioned in https://stackoverflow.com/questions/57028498/problem-with-magento-2-rest-authentication/59530132, POST requests would always work, but GET requests would fail. I have no idea why changing the handler solves the problem. Good luck.

0

I have been chasing my tail for hours on this ... :/

lm713: "Try changing the PHP handler used by Apache on the Magento server"

this did the trick, i am running magento 2 in cpanel environment and the php version was configured to use CGI as the PHP Handler. I changed it to suphp and all my api queries are now working!

0

I had the same issue on PHP 7.1.33 After I switched to 7.2.31 the issue was fixed. Not sure why it was. Magento ver. 2.3.2

0

In my case, the issue was being caused by Apache. The "Consumer is not authorized"-error is a broad error, also being shown when the the Authorization-header is not being received by Magento.

Apparently Apache does not pass the Authorization-header to the website on default. It's Apache's default security behaviour.

Issue fixed by adding these lines to .htaccess:

RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
0

Can be a redirects issue. During redirect (response with Location 301 header) the Authorization header might be lost. So you can try to avoid redirects. You can check redirects by getting cUrl code from Postman and add -v -L flags.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.