I'm using the following code to try to return data for our warehouses via the Sage API. We're using Sage 200 standard (docs here). Every time I try to run the script it takes me to a 404 with an unauthorised error.
The annoying thing is that if I use all the same details in Postman then it works. The only difference being is that the callback url is https://id.sage.com/mobile and when I send the data, it brings up a popup to login. Once I login and get the access token everything works.
I just want to recreate that process but via a webpage but no matter how I structure the code I don't get the same popup and everything just falls apart after it.
Where am I going wrong? Any help much appreciated.
$clientId = 'XXX';
$clientSecret = 'XXX';
$redirectUri = 'https://example.com/sage-stock/';
if (!isset($_GET['code'])) {
// If the 'code' parameter is not in the URL, start the authorization process
$authUrl = 'https://id.sage.com/authorize?';
$authUrl .= 'response_type=code';
$authUrl .= '&client_id=' . $clientId;
$authUrl .= '&redirect_uri=' . urlencode($redirectUri);
$authUrl .= '&scope=openid%20profile%20email%20offline_access';
$authUrl .= '&audience=s200ukipd/sage200';
$authUrl .= '&state=1235';
header('Location: ' . $authUrl);
exit;
} else {
// If the 'code' parameter is in the URL, exchange it for an access token
$code = $_GET['code'];
$tokenUrl = 'https://id.sage.com/oauth/token';
$postData = [
'grant_type' => 'authorization_code',
'client_id' => $clientId,
'client_secret' => $clientSecret,
'code' => $code,
'redirect_uri' => $redirectUri
];
$ch = curl_init($tokenUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
$response = json_decode(curl_exec($ch), true);
curl_close($ch);
$accessToken = $response['access_token'];
$refreshToken = $response['refresh_token'];
// Use the access token to make a request to the Sage API
$headers = [
'Authorization: Bearer ' . $accessToken,
'Content-Type: application/json',
'ocp-apim-subscription-key: XXX',
'X-Site: XXX',
'X-Company: XXX'
];
$apiUrl = 'https://api.columbus.sage.com/uk/sage200/accounts/v1/warehouses/';
$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = json_decode(curl_exec($ch));
curl_close($ch);
echo '<pre>';
print_r($response);
echo '</pre>';
}