Blog Logo

12 Jan 2024 ~ 2 min read

Create App Store Sever API Key Using PHP


Intro

App Store Connect requires you to create API Key by signing a JWT API Token with mixed credentials and identities. This tutorial will guide you through the process of creating one.

Make sure you have all the required data

  • keyId: Key ID will be displayed when you generate new private key in Users And Access / Keys section.
  • issuerID: ID associated with you in the Users And Access / Keys section.
  • bundleId: Your app bundle ID
  • privateKey: The private key file you download from App Store Connect.

Code Sample

We would need to use a library that handles JWT in PHP, such as firebase/php-jwt.

First, install the firebase/php-jwt library using Composer:

composer require firebase/php-jwt

Then, generate the JWT token as follows:

<?php
require 'vendor/autoload.php';  // Make sure to use the correct path to autoload.php of Composer

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

function generateJWT($header, $payload, $privateKey) {
    $key = openssl_pkey_get_private($privateKey);
    if (!$key) {
        throw new Exception('Unable to load the private key');
    }

    $alg = $header['alg'];
    $jwt = JWT::encode($payload, $key, $alg, $header['kid']);

    return $jwt;
}

function genToken($kid, $iss, $bundle_id, $privateKey) {
    $header = [
        'alg' => 'ES256',
        'kid' => $kid,
        'typ' => 'JWT'
    ];

    $payload = [
        'iss' => $iss,
        'iat' => time(),
        'exp' => time() + 30 * 60, // 30 minutes
        'aud' => 'appstoreconnect-v1',
        'bid' => $bundle_id
    ];

    $token = generateJWT($header, $payload, $privateKey);

    return $token;
}

// Usage
try {
    $token = genToken($keyId, $issuerId, $bundleId, $privateKey);
    echo $token;
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}

Also, the line $key = openssl_pkey_get_private($privateKey); assumes that your private key is stored in a format that can be utilized by the openssl_pkey_get_private function. The PHP firebase/php-jwt library will handle the JWT creation and signing.

Alternative tool

Or if you just want to play around with the API, use our complete free Chrome Extension to generate key “locally” with complete privacy.

Extension Screenshot


Headshot of John

Hi, I'm John. Editor at ToolboxForWeb. Trying to make the internet a useful and friendly place for every person.