苹果v2 通知相比v1 减少了一次再次请求服务器验证,但是JWS 格式本人接触较少,翻阅了资料大概搞懂苹果整个验签流程。
如下
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\SignatureInvalidException;
//需要用到 friebase/jwt 这个组件 推荐composer 安装;git地址:https://github.com/firebase/php-jwt:
public function validateJwt($jws)
{
$jws = json_decode($jws, true)['signedPayload'];
//Jws 根据 . 分割的三段字符串
$components = explode('.', $jws);
if (count($components) !== 3) {
throw new \Exception('JWS string must contain 3 dot separated component.');
}
$header = base64_decode($components[0]);
$headerJson = json_decode($header, true);
$this->validateAppleRootCA($headerJson);
$data = $this->decodeCertificate($jws, $headerJson, 0);
return $data;
}
private function validateAppleRootCA($headerJson)
{
$lastIndex = count($headerJson['x5c']) - 1;
$certificate = $this->getCertificate($headerJson, $lastIndex);
// 去苹果官方下载根证书(第4个) https://www.apple.com/certificateauthority/. 本机终端转一下格式,命令如下: openssl x509 -inform der -in AppleRootCA-G3.cer -out AppleRootCA-G3.pem
$Path = ROOTPATH . "/AppleRootCA-G3.pem";
$appleRootCA = file_get_contents($Path);
if ($certificate != $appleRootCA) {
throw new \Exception('jws invalid');
}
}
private function getCertificate($headerJson, $certificateIndex)
{
$certificate = '-----BEGIN CERTIFICATE-----' . PHP_EOL;
$certificate .= chunk_split($headerJson['x5c'][$certificateIndex], 64, PHP_EOL);
$certificate .= '-----END CERTIFICATE-----' . PHP_EOL;
return $certificate;
}
private function decodeCertificate($jwt, $headerJson, $certificateIndex = 0)
{
$certificate = $this->getCertificate($headerJson, 0);
$cert_object = openssl_x509_read($certificate);
$pkey_object = openssl_pkey_get_public($cert_object);
$pkey_array = openssl_pkey_get_details($pkey_object);
$publicKey = $pkey_array['key'];
try {
$jwsDecoded = JWT::decode($jwt, new Key($publicKey, 'ES256'));
$jwsParsed = (array)$jwsDecoded;
return $jwsParsed;
} catch (SignatureInvalidException $e) {
throw new \Exception('signature invalid');
}
}
举例
苹果的消息 $jws = '12345678...';
$this->validateJwt($jws);
验签 并解码
结语:
苹果的消息用消息里面自带的证书加密的,x5c 里面第一个证书解码整个jws(里面总共有3个)