Search code examples
phpmagentooauth

Magento Rest API error:`The signature is invalid. Verify and try again.` after adding searchCriteria Filter


I'm trying to send an API request to the magento 2 api to retrieve all orders. I'm sending this request from Laravel using the Illuminate\Support\Facades\Http. To authenticate myself to magento im using the integration Oauth credentials. I gave the integration resource access to 'all' to make testing easier

Magento version is 2.4.4

$orderEndpoint = '/rest/V1/orders';

$oauthParams = [
    'oauth_consumer_key' => $clientId,
    'oauth_nonce' => md5(uniqid(rand(), true)),
    'oauth_signature_method' => 'HMAC-SHA256',
    'oauth_timestamp' => time(),
    'oauth_token' => $accessToken,
];

ksort($oauthParams);

$queryParams = [
    'searchCriteria[currentPage]' => 1,
    'searchCriteria[pageSize]' => 10,
];

$baseString = 'GET&' . rawurlencode($baseUrl . $orderEndpoint) . '&' . rawurlencode(http_build_query(array_merge($oauthParams, $queryParams), '', '&', PHP_QUERY_RFC3986));
dump($baseString);

$signatureKey = rawurlencode($consumerSecret) . '&' . rawurlencode($tokenSecret);
$signature = base64_encode(hash_hmac('sha256', $baseString, $signatureKey, true));
dump($signature);

$oauthParams['oauth_signature'] = $signature;

$authorizationHeader = 'OAuth ' . http_build_query($oauthParams, '', ', ', PHP_QUERY_RFC3986);
$fullUrl = $baseUrl . $orderEndpoint . '?' . http_build_query(array_merge($oauthParams, $queryParams));
dump($fullUrl);

$response = Http::withHeaders([
    'Authorization' => $authorizationHeader,
])->get($baseUrl . $orderEndpoint, $queryParams);

if ($response->successful()) {
    $orderData = $response->json();
    dd($orderData);
} else {
    dd($response->json());
}

This is my code and it works like it should work, but when I try to change $queryParams to:

$queryParams = [
    'searchCriteria[filter_groups][0][filters][0][field]' => 'status',
    'searchCriteria[filter_groups][0][filters][0][value]' => 'complete',
    'searchCriteria[currentPage]' => 1,
    'searchCriteria[pageSize]' => 10,
];

I get the error The signature is invalid. Verify and try again.

Anybody has an idea what I'm doing wrong and what the solution may be?


Solution

  • The actual fix for the problem is way stupider, The filters have to be in alphabetical order. My code works if I format it like this:

    $queryParams = [
        'searchCriteria[currentPage]' => 1,
        'searchCriteria[filter_groups][0][filters][0][field]' => 'status',
        'searchCriteria[filter_groups][0][filters][0][value]' => 'complete',
        'searchCriteria[filter_groups][1][filters][0][condition_type]' => 'gt',
        'searchCriteria[filter_groups][1][filters][0][field]' => 'created_at',
        'searchCriteria[filter_groups][1][filters][0][value]' => Carbon::now()->subWeek()->toTimeString(),
        'searchCriteria[pageSize]' => 10,
    ];
    

    It works...