2

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
  • are you sure you passing admin's username and password correct. – Aditya Shah Oct 1 '18 at 14:24
  • @AdityaShah as sure as a sea – treyBake Oct 1 '18 at 14:25
  • Okay, do you have POSTMAN ? – Aditya Shah Oct 1 '18 at 14:26
  • @AdityaShah no .. seems not needed? Just a way to develop APIs in IDE-format no? – treyBake Oct 1 '18 at 14:28
  • No, just to get token with url - just for testing purpose – Aditya Shah Oct 1 '18 at 14:30
4

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;
}
  • same error :/ - just a different way of getting to it – treyBake Oct 1 '18 at 14:47
  • woh, share me your actual url – Aditya Shah Oct 1 '18 at 14:47
  • forget about it, just tell me are you getting any admin TOKEN ? – Aditya Shah Oct 1 '18 at 14:48
  • yeah I do - it's already specified in question ^^ – treyBake Oct 1 '18 at 14:53
  • But there's no other possibilities. – Aditya Shah Oct 1 '18 at 14:53
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

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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