Minishlink\WebPush\VAPID::getVapidHeaders PHP Method

getVapidHeaders() public static method

This method takes the required VAPID parameters and returns the required header to be added to a Web Push Protocol Request.
public static getVapidHeaders ( string $audience, string $subject, string $publicKey, string $privateKey, integer $expiration = null ) : array
$audience string This must be the origin of the push service
$subject string This should be a URL or a 'mailto:' email address
$publicKey string The decoded VAPID public key
$privateKey string The decoded VAPID private key
$expiration integer The expiration of the VAPID JWT. (UNIX timestamp)
return array Returns an array with the 'Authorization' and 'Crypto-Key' values to be used as headers
    public static function getVapidHeaders($audience, $subject, $publicKey, $privateKey, $expiration = null)
    {
        $expirationLimit = time() + 43200;
        // equal margin of error between 0 and 24h
        if (!isset($expiration) || $expiration > $expirationLimit) {
            $expiration = $expirationLimit;
        }
        $header = array('typ' => 'JWT', 'alg' => 'ES256');
        $jwtPayload = json_encode(array('aud' => $audience, 'exp' => $expiration, 'sub' => $subject), JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
        $generator = EccFactory::getNistCurves()->generator256();
        $privateKeyObject = $generator->getPrivateKeyFrom(gmp_init(bin2hex($privateKey), 16));
        $pemSerialize = new PemPrivateKeySerializer(new DerPrivateKeySerializer());
        $pem = $pemSerialize->serialize($privateKeyObject);
        $jwk = JWKFactory::createFromKey($pem, null);
        $jws = JWSFactory::createJWSToCompactJSON($jwtPayload, $jwk, $header);
        return array('Authorization' => 'WebPush ' . $jws, 'Crypto-Key' => 'p256ecdsa=' . Base64Url::encode($publicKey));
    }

Usage Example

示例#1
0
 /**
  * @dataProvider vapidProvider
  *
  * @param $audience
  * @param $vapid
  * @param $expiration
  * @param $expectedAuthorization
  * @param $expectedCryptoKey
  */
 public function testGetVapidHeaders($audience, $vapid, $expiration, $expectedAuthorization, $expectedCryptoKey)
 {
     $vapid = VAPID::validate($vapid);
     $headers = VAPID::getVapidHeaders($audience, $vapid['subject'], $vapid['publicKey'], $vapid['privateKey'], $expiration);
     $this->assertArrayHasKey('Authorization', $headers);
     $this->assertEquals(Utils::safeStrlen($expectedAuthorization), Utils::safeStrlen($headers['Authorization']));
     $this->assertEquals($this->explodeAuthorization($expectedAuthorization), $this->explodeAuthorization($headers['Authorization']));
     $this->assertArrayHasKey('Crypto-Key', $headers);
     $this->assertEquals($expectedCryptoKey, $headers['Crypto-Key']);
 }
All Usage Examples Of Minishlink\WebPush\VAPID::getVapidHeaders