苹果支付v2 通知(订阅/退款回调通知)

苹果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个)


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

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值