I have a small php script that fetch some product information from the Magento 2 Rest API.
The problem I am facing is that it works fine for some Magento 2 shops, but not others. For some shops I get
"The signature is invalid. Verify and try again."
But if I use the same credentials in Postman I get:
This is the script getting the products from Magento 2
$url = $_GET["url"];
$apiUrl = $url . 'rest/V1/products';
$consumerKey = $_GET["consumerKey"];
$consumerSecret = $_GET["consumerSecret"];
$accessToken = $_GET["accessToken"];
$accessTokenSecret = $_GET["accessTokenSecret"];
$searchurl = $apiUrl;
$method = 'GET';
function sign($method, $url, $data, $consumerSecret, $tokenSecret)
{
$url = urlEncodeAsZend($url);
$data = urlEncodeAsZend(http_build_query($data, '', '&'));
$data = implode('&', [$method, $url, $data]);
$secret = implode('&', [$consumerSecret, $tokenSecret]);
return base64_encode(hash_hmac('sha1', $data, $secret, true));
}
function urlEncodeAsZend($value)
{
$encoded = rawurlencode($value);
$encoded = str_replace('%7E', '~', $encoded);
return $encoded;
}
$search = [
'searchCriteria[pageSize]' => 2,
'searchCriteria[currentPage]' => 1,
];
ksort($search);
$data = array_merge([
'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',
],$search);
$data['oauth_signature'] = sign($method, $searchurl, $data, $consumerSecret, $accessTokenSecret);
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $searchurl . '?' . http_build_query($search),
CURLOPT_HTTPHEADER => [
'Authorization: OAuth ' . http_build_query($data, '', ',')
]
]);
$result = curl_exec($curl);
curl_close($curl);
Can anyone give me a clue as to why this happens?