I has api keys, but when i request appstore connect api, it return 401 NOT_AUTHORIZED.

<?php
// Path to the private key file
$file_path = '/www/wwwroot/domain.com/folder/AuthKey_WAJVXXXXXX.p8';

// Read the private key from the file
$private_key = openssl_pkey_get_private("file://$file_path");

if (!$private_key) {
    echo "Error retrieving the private key: " . openssl_error_string();
    exit;
}

// Setup the Header without 'alg' ,Also with 'alg' the code didn't work properly
$header = json_encode([
    'kid' => 'WAJVXXXXXX' // Key ID
]);

// Setup the Payload
$payload = json_encode([
    'iss' => '69a6de97-1498-47e3-e053-xxxxxxxxxxxx', // Issuer ID
    'exp' => time() + 3600, // Token validity for one hour
    'aud' => 'appstoreconnect-v1' // Audience
]);

// Encode Header and Payload to Base64
$header_base64 = base64_encode($header);
$payload_base64 = base64_encode($payload);
$data = $header_base64 . '.' . $payload_base64;

// Sign the data
$signature = '';
if (!openssl_sign($data, $signature, $private_key, OPENSSL_ALGO_SHA256)) {
    echo "Error signing the data: " . openssl_error_string();
    exit;
}

// Encode the signature to Base64
$signature_base64 = base64_encode($signature);

// Create the JWT
$jwt = $header_base64 . '.' . $payload_base64 . '.' . $signature_base64;

echo "JWT: " . $jwt;
?>

{ "errors": [{ "status": "401", "code": "NOT_AUTHORIZED", "title": "Authentication credentials are missing or invalid.", "detail": "Provide a properly configured and signed bearer token, and make sure that it has not expired. Learn more about Generating Tokens for API Requests https://developer.apple.com/go/?id=api-generating-tokens" }] }

I think you're missing the ampersand in the openssl_sign call:

// Sign the data
$signature = '';
if (!openssl_sign($data, &$signature, $private_key, OPENSSL_ALGO_SHA256)) {
    echo "Error signing the data: " . openssl_error_string();
    exit;
}

// Encode the signature to Base64
$signature_base64 = base64_encode($signature);

Because if you haven't got it, the call doesn't write to $signature so you end up base64-encoding '' in that last line.

Did the above work?

I has api keys, but when i request appstore connect api, it return 401 NOT_AUTHORIZED.
 
 
Q