I am using the Magento 2 API to convert quotes (from custom made laravel project) to orders. I use an administrator bearer token, which works successfully for other API calls such as:
- Create guest cart
- Add product to guest cart
- Add payment and shipping addresses
- Create an order
However, when making Salesrule API calls (both POST and GET), I receive a 401 Unauthorized response.
Strangely, if I make the exact same Salesrule API call in Postman with the same bearer token, I do get a response.
Here’s what I’ve checked so far:
The bearer token is correctly set and works for other API calls.
The API calls are identical in both my code and Postman.
There are no additional headers or parameters in Postman that are not in my code.
What could be causing the 401 Unauthorized response specifically for Salesrule calls in my code, but not in Postman?
Function for getting a admin token:
protected function getAdminToken()
{
$url = $this->baseUrl.'/rest/V1/integration/admin/token';
$payload = [
'username' => env('MAGENTO_ADMIN_USERNAME'),
'password' => env('MAGENTO_ADMIN_PASSWORD'),
];
$client = new Client();
$response = $client->post($url, [
'json' => $payload
]);
return json_decode($response->getBody(), true);
}
This is responding with an admin token.
Here is api call function:
public function createCartPriceRule(int $websiteId, int $discountTotal, int $quoteId): int
{
$discountTotal = round($discountTotal / 100, 2);
$url = $this->baseUrl.'/rest/V1/salesRules';
$payload = [
"rule" => [
"name" => "Quote".$quoteId,
"website_ids" => [
$websiteId
],
"customer_group_ids" => [
0,1
],
"uses_per_customer" => 1,
"is_active" => true,
"stop_rules_processing" => false,
"is_advanced" => true,
"sort_order" => 0,
"simple_action" => "cart_fixed",
"discount_amount" => $discountTotal,
"discount_step" => 1,
"apply_to_shipping" => false,
"times_used" => 0,
"is_rss" => false,
"coupon_type" => "SPECIFIC_COUPON",
"use_auto_generation" => true,
"uses_per_coupon" => 1,
"coupon_code" => "Quote".$quoteId."discount",
]
];
$response = $this->postRequest($url, $payload);
return $response['rule_id'];
}
Post request function:
protected function postRequest(string $url, array $payload = [])
{
$client = new Client();
$response = $client->post($url, [
'headers' => $this->getHeaders(),
'json' => $payload
]);
return json_decode($response->getBody(), true);
}
Get headers function:
protected function getHeaders(): array
{
return [
'headers' => [
'Authorization' => 'Bearer '.$this->accessToken,
'Accept' => 'application/json',
],
];
}
rubinjo13 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.