I'm trying to get the list of all magento2 products but I'm getting 401 authorization error
. I tried the below methods and in all methods I'm getting the mentioned error!
First Method:
$userData = array("username" => "user123", "password" => "pass123");
$ch = curl_init("http://shop.mysite.com/rest/V1/integration/admin/token");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($userData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Content-Lenght: " . strlen(json_encode($userData))));
$token = curl_exec($ch);
$ch = curl_init("http://shop.mysite.com/rest/V1/products");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));
$result = curl_exec($ch);
$mgtProducts = json_decode($result, 1);
Second Try:
$consumerKey = 'key';
$consumerSecret = 'key';
$accessToken = 'key';
$accessTokenSecret = 'key';
$method = 'GET';
$url = 'http://shop.mysite.com/rest/V1/products';
$data = array(
'oauth_consumer_key' => $consumerKey,
'oauth_nonce' => md5(uniqid(rand(), true)),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_token' => $accessToken,
'oauth_version' => '1.0'
);
$data['oauth_signature'] = $this->sign($method, $url, $data, $consumerSecret, $accessTokenSecret);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => array(
'Authorization: OAuth ' . http_build_query($data, '', ',')
)
));
$result = curl_exec($curl);
curl_close($curl);
Best Answer
Try the following code