/** * Converts and signs a PHP object or array into a JWT string. * * @param object|array $payload PHP object or array * @param string $key The secret key. * If the algorithm used is asymmetric, this is the private key * @param string $alg The signing algorithm. * Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256' * @param array $head An array with header elements to attach * * @return string A signed JWT * * @uses jsonEncode * @uses urlsafeB64Encode */ public static function encode($payload, $key, $alg = 'HS256', $keyId = null, $head = null) { $header = array('typ' => 'JWT', 'alg' => $alg); if ($keyId !== null) { $header['kid'] = $keyId; } if (isset($head) && is_array($head)) { $header = array_merge($head, $header); } $segments = array(); $segments[] = JWT::urlsafeB64Encode(JWT::jsonEncode($header)); $segments[] = JWT::urlsafeB64Encode(JWT::jsonEncode($payload)); $signing_input = implode('.', $segments); $signature = JWT::sign($signing_input, $key, $alg); $segments[] = JWT::urlsafeB64Encode($signature); return implode('.', $segments); }