I'm writing a code to authenticate or connect JWT rest API, but I'm unable to connect with that, I've prepared all the code, but it's still unsuccessful, I don't know what's the issue with it.
I've generated the JWT token already. I don't know what exactly the issue is.
Here's the error I'm getting:
Client error:
POST https://apisandbox.swissmoney.com/api/integration/v1/company-profiles
resulted in a401 Unauthorized
response
Here is the code I created:
function sendApiRequest($method, $uri, $data) {
// Define your API base URL
$baseUrl = 'https://apisandbox.swissmoney.com';
// Define the API secret key
$apiSecretKey = file_get_contents('file:///home/cidrqqhe/cidrus_money_private.key'); // Replace with your actual secret key
// Generate a nonce (unique number or string)
$nonce = uniqid();
// Get the current UNIX timestamp
$timestamp = time();
// Define the JWT payload
$jwtPayload = [
'target' => $method . ' ' . $uri,
'nonce' => $nonce,
'nbf' => $timestamp,
'exp' => $timestamp + 30, // Adjust the expiration time as needed
'sub' => 'xxxx-xx-xxxx-xxxx-b2d4d5190967', // Replace with your API Key
'aud' => $baseUrl,
'bodyHash' => base64_encode(hash('sha256', json_encode($data))),
];
// Encode the JWT payload
$jwtHeader = [
'alg' => 'RS256',
'typ' => 'JWT',
];
// Encode the JWT header
$encodedJwtHeader = base64_encode(json_encode($jwtHeader));
$encodedJwtPayload = base64_encode(json_encode($jwtPayload));
// Create the JWT signature
$signature = '';
openssl_sign($encodedJwtHeader . '.' . $encodedJwtPayload, $signature, openssl_pkey_get_private($apiSecretKey));
// Encode the JWT signature
$encodedSignature = base64_encode($signature);
// Create the Authorization header
$authorizationHeader = 'Bearer ' . $encodedJwtHeader . '.' . $encodedJwtPayload . '.' . $encodedSignature;
// Create the request headers
$headers = [
'X-API-Key' => 'xxxx-xx-xxxx-xxxx-b2d4d5190967', // Replace with your API Key
'Authorization' => $authorizationHeader,
'Content-Type' => 'application/json',
];
// Create a Guzzle client
$client = new Client();
// Send the API request
$response = $client->request($method, $baseUrl . $uri, [
'headers' => $headers,
'json' => $data,
]);
// Handle the API response as needed
return $response->getBody()->getContents();
}