Magento 2 Updating Stock via Rest API

2019-08-29 01:51发布

问题:

I'm using this code to update my Magento 2 stocks via API; but there is an permission error, even the credentials are ok, and user role is 'administrator'.

Could some one help me?

ERROR Message:

string(366) " Forbidden You don't have permission to access /rest/V1/products/10001001/stockItems/1 on this server. Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.

And my code:

<?php
$url = "https://www.example.com/";
$token_url=$url."rest/V1/integration/admin/token";
$ch = curl_init();
$data = array("username" => "xxxx", "password" => "xxxx");
$data_string = json_encode($data);
$ch = curl_init($token_url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$token = curl_exec($ch);
$adminToken=  json_decode($token);

$skus = array(
  '10001001' => 10,
  '10001004' => 8
);

foreach ($skus as $sku => $stock) {
  $requestUrl='https://www.example.com/rest/V1/products/' . $sku . '/stockItems/1';
  $sampleProductData = array(
          'qty' => $stock
  );

$productData = json_encode(array('product' => $sampleProductData));
$setHaders = array('Content-Type:application/json','Authorization:Bearer '.$adminToken);

$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $requestUrl);
curl_setopt($ch,CURLOPT_POSTFIELDS, $productData);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_HTTPHEADER, $setHaders);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
curl_close($ch);

  var_dump($response);
}
?>
标签: php magento