本文介绍: 苹果内购消息 v2

苹果v2 通知相比v1 减少了一次再次请求服务器验证,但是JWS 格式本人接触较少,翻阅了资料大概搞懂苹果整个验签流程。

如下
 

use FirebaseJWTJWT;
use FirebaseJWTKey;
use FirebaseJWTSignatureInvalidException;

//需要用到 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个)

参考:php – What fields do I verify in a x509 (as x5c header in a JWS) to prove legitimacy of the Certificate? – Stack Overflow

原文地址:https://blog.csdn.net/panhanshiwo/article/details/127496245

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

如若转载,请注明出处:http://www.7code.cn/show_50579.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注