The `certs(%1$s)` contains the merchant‘s certificate serial number(%2$s) which is not allowed here.

php对接微信h5新版 V3支付遇到的第一个报错
意思是说证书序列号不正确
解决过程:
1、我得到的证书有apiclient_cert.pem,apiclient_key.pem,wpay.p12这三个文件
2、我下载了官网提供的sdk(下载地址 https://github.com/wechatpay-apiv3/wechatpay-php)
3、按照文件写了代码
在这里插入图片描述
$merchantPrivateKeyFilePath 这个字段,填写apiclient_key.pem文件绝对路径
一定要保留file://,不然会报错
p l a t f o r m C e r t i f i c a t e F i l e P a t h 这 个 字 段 , 填 写 的 a p i c l i e n t c e r t . p e m 文 件 地 址 , 其 他 参 数 对 应 填 写 , 然 后 运 行 在 构 造 客 户 端 实 例 时 就 报 了 T h e ‘ c e r t s ( platformCertificateFilePath这个字段,填写的apiclient_cert.pem文件地址,其他参数对应填写,然后运行在构造客户端实例时就报了The `certs(%1 platformCertificateFilePathapiclientcert.pemThecerts(s)` contains the merchant’s certificate serial number(%2KaTeX parse error: Undefined control sequence: \wechatpay at position 48: …步一步打印到wechatpay\̲w̲e̲c̲h̲a̲t̲p̲a̲y̲\src\ClientJson…platformCertificateFilePath这个字段应该使用支付平台证书,而不是下载的apiclient_cert.pem这个文件
4、sdk不能调用,那我就自己封装获取,根据官网文档(https://pay.weixin.qq.com/wiki/doc/apiv3/apis/wechatpay5_1.shtml)
5、代码如下

/**
     * 获取证书
     * @return mixed
     */
    public static function certificates(){
        //请求参数(报文主体)
        $headers = self::sign('GET','https://api.mch.weixin.qq.com/v3/certificates','');
        $result = self::curl_get('https://api.mch.weixin.qq.com/v3/certificates',$headers);
        $result = json_decode($result,true);
        $aa = self::decryptToString($result['data'][0]['encrypt_certificate']['associated_data'],$result['data'][0]['encrypt_certificate']['nonce'],$result['data'][0]['encrypt_certificate']['ciphertext']);
        dd($aa);//解密后的内容,就是证书内容
    }
    /**
     * 签名
     * @param string $http_method    请求方式GET|POST
     * @param string $url            url
     * @param string $body           报文主体
     * @return array
     */
    public static function sign($http_method = 'POST',$url = '',$body = ''){
        $mch_private_key = self::getMchKey();//私钥
        $timestamp = time();//时间戳
        $nonce = self::getRandomStr(32);//随机串
        $url_parts = parse_url($url);
        $canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
        //构造签名串
        $message = $http_method."\n".
            $canonical_url."\n".
            $timestamp."\n".
            $nonce."\n".
            $body."\n";//报文主体
        //计算签名值
        openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');
        $sign = base64_encode($raw_sign);
        //设置HTTP头
        $config = self::config();
        $token = sprintf('WECHATPAY2-SHA256-RSA2048 mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
            $config['mchid'], $nonce, $timestamp, $config['serial_no'], $sign);
        $headers = [
            'Accept: application/json',
            'User-Agent: */*',
            'Content-Type: application/json; charset=utf-8',
            'Authorization: '.$token,
        ];
        return $headers;
    }
    //私钥
    public static function getMchKey(){
        //path->私钥文件存放路径
        return openssl_get_privatekey(file_get_contents('你的apiclient_key.pem文件绝对路径'));
    }
    /**
     * 获得随机字符串
     * @param $len      integer       需要的长度
     * @param $special  bool      是否需要特殊符号
     * @return string       返回随机字符串
     */
    public static function getRandomStr($len, $special=false){
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );

        if($special){
            $chars = array_merge($chars, array(
                "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
                "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
                "}", "<", ">", "~", "+", "=", ",", "."
            ));
        }

        $charsLen = count($chars) - 1;
        shuffle($chars);                            //打乱数组顺序
        $str = '';
        for($i=0; $i<$len; $i++){
            $str .= $chars[mt_rand(0, $charsLen)];    //随机取出一位
        }
        return $str;
    }
    /**
     * 配置
     */
    public static function config(){
        return [
            'appid' => '',
            'mchid' => '',//商户号
            'serial_no' => '',//证书序列号
            'description' => '',//应用名称(随意)
            'notify' => '',//支付回调
        ];
    }
//get请求
    public static function curl_get($url,$headers=array())
    {
        $info = curl_init();
        curl_setopt($info,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($info,CURLOPT_HEADER,0);
        curl_setopt($info,CURLOPT_NOBODY,0);
        curl_setopt($info,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($info,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($info,CURLOPT_SSL_VERIFYHOST,false);
        //设置header头
        curl_setopt($info, CURLOPT_HTTPHEADER,$headers);
        curl_setopt($info,CURLOPT_URL,$url);
        $output = curl_exec($info);
        curl_close($info);
        return $output;
    }
    
    const KEY_LENGTH_BYTE = 32;
    const AUTH_TAG_LENGTH_BYTE = 16;
/**
     * Decrypt AEAD_AES_256_GCM ciphertext
     *
     * @param string    $associatedData     AES GCM additional authentication data
     * @param string    $nonceStr           AES GCM nonce
     * @param string    $ciphertext         AES GCM cipher text
     *
     * @return string|bool      Decrypted string on success or FALSE on failure
     */
    public static function decryptToString($associatedData, $nonceStr, $ciphertext) {
        $aesKey = '你的APIv3密钥';
        $ciphertext = \base64_decode($ciphertext);
        if (strlen($ciphertext) <= self::AUTH_TAG_LENGTH_BYTE) {
            return false;
        }

        // ext-sodium (default installed on >= PHP 7.2)
        if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {
            return \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, $aesKey);
		}

        // ext-libsodium (need install libsodium-php 1.x via pecl)
        if (function_exists('\Sodium\crypto_aead_aes256gcm_is_available') && \Sodium\crypto_aead_aes256gcm_is_available()) {
            return \Sodium\crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, $aesKey);
		}

        // openssl (PHP >= 7.1 support AEAD)
        if (PHP_VERSION_ID >= 70100 && in_array('aes-256-gcm', \openssl_get_cipher_methods())) {
            $ctext = substr($ciphertext, 0, -self::AUTH_TAG_LENGTH_BYTE);
            $authTag = substr($ciphertext, -self::AUTH_TAG_LENGTH_BYTE);

            return \openssl_decrypt($ctext, 'aes-256-gcm', $aesKey, \OPENSSL_RAW_DATA, $nonceStr,
				$authTag, $associatedData);
		}

        throw new \RuntimeException('AEAD_AES_256_GCM需要PHP 7.1以上或者安装libsodium-php');
    }

6、请求接口,获取到证书内容,保存到文件中,命名为cert.pem,然后在使用sdk时,$platformCertificateFilePath这个变量使用的路径改为新获取到证书的路径,就可以直接调用sdk了

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值