php 微信转账大金额 证书问题

发布时间 2023-03-23 09:57:45作者: 垖垏尐
<?php
namespace app\common;
class common
{
    /**
     * @notes 商家转账到零钱
     * @param $batch_no //提现订单号
     * @param $left_money //提现金额 单位 元
     * @param $user_openid //用户openID
     * @param $withdraw_name //提现金额大于200,用户真实名字必填
     * @return bool
     * @throws \Exception
     */
    public function transfer($batch_no, $left_money, $user_openid, $withdraw_name = '')
    {
       
        $config = [
            'app_id' => '******',
            'mch_id' => '*****', //商户ID
            'cert_client' => './weixin/cert/apiclient_cert.pem', //cert证书地址//绝对路径
            'cert_key' => './weixin/cert/apiclient_key.pem', //key支付证书绝对地址
            'wx_public_cert' => './weixin/cert/wx_public_cert.pem', //平台证书
        ];
        $withdrawApply = [
            'real_name' => $withdraw_name,
        ];
        //请求URL
        $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches';
        //请求方式
        $http_method = 'POST';
        //请求参数
        
        $data = [
            'appid' => $config['app_id'], //申请商户号的appid或商户号绑定的appid(企业号corpid即为此appid)
            'out_batch_no' => $batch_no, //商户系统内部的商家批次单号,要求此参数只能由数字、大小写字母组成,在商户系统内部唯一
            'batch_name' => '提现至微信零钱', //该笔批量转账的名称
            'batch_remark' => '提现至微信零钱', //转账说明,UTF8编码,最多允许32个字符
            'total_amount' => $left_money * 100, //转账金额单位为“分”。转账总金额必须与批次内所有明细转账金额之和保持一致,否则无法发起转账操作
            'total_num' => 1, //一个转账批次单最多发起三千笔转账。转账总笔数必须与批次内所有明细之和保持一致,否则无法发起转账操作
            'transfer_detail_list' => [
                [ //发起批量转账的明细列表,最多三千笔
                    'out_detail_no' => $batch_no, //商户系统内部区分转账批次单下不同转账明细单的唯一标识,要求此参数只能由数字、大小写字母组成
                    'transfer_amount' => $left_money * 100, //转账金额单位为分
                    'transfer_remark' => '提现至微信零钱', //单条转账备注(微信用户会收到该备注),UTF8编码,最多允许32个字符
                    'openid' => $user_openid, //openid是微信用户在公众号appid下的唯一用户标识(appid不同,则获取到的openid就不同),可用于永久标记一个用户
                ]
            ]
        ];
        // $certificatesInfo = self::get_Certificates();
        
        if ($left_money >= 2000) {
            if (empty($withdraw_name)) {
                throw new \Exception('转账金额 >= 2000元,收款用户真实姓名必填');
            }
            $data['transfer_detail_list'][0]['user_name'] = self::getEncrypt($withdrawApply['real_name'], $config);
        }

        $token = self::token($url, $http_method, $data, $config); //获取token
        
        $result = self::https_request($url, json_encode($data), $token,$config); //发送请求
        $result_arr = json_decode($result, true);

        if (!isset($result_arr['create_time'])) { //批次受理失败
            throw new \Exception($result_arr['message']);
        }
        //成功返回信息  {"batch_id":"1030001036201351072852022101201442513049","create_time":"2022-10-12T22:08:21+08:00","out_batch_no":"20221011004103000000146822"}
        //批次受理成功,更新提现申请单为提现中状态
        //业务修改为提现中
        return $result_arr;
    }
    
    
    /**
     * @notes 签名生成
     * @param $url
     * @param $http_method
     * @param $data
     * @param $config
     * @return string
     */
    public static function token($url, $http_method, $data, $config)
    {
        $timestamp = time(); //请求时间戳
        $url_parts = parse_url($url); //获取请求的绝对URL
        $nonce = $timestamp . rand('10000', '99999'); //请求随机串
        $body = empty($data) ? '' : json_encode((object)$data); //请求报文主体
        $stream_opts = [
            "ssl" => [
                "verify_peer" => false,
                "verify_peer_name" => false,
            ]
        ];
        $serial_no = '*******************'; //商户证书序列号
        $mch_private_key = file_get_contents($config['cert_key'], false, stream_context_create($stream_opts)); //密钥
        $merchant_id = $config['mch_id']; //商户id
        $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); //签名
        $schema = 'WECHATPAY2-SHA256-RSA2048';
        $token = sprintf(
            'mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
            $merchant_id,
            $nonce,
            $timestamp,
            $serial_no,
            $sign
        ); //微信返回token
        return $schema . ' ' . $token;
    }
    
     /**
     * @notes 发送请求
     * @param $url
     * @param $data
     * @param $token
     * @return bool|string
     */
    public static function https_request($url, $data, $token, $config)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, (string)$url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if(!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //添加请求头
        $headers = [
            'Authorization:' . $token,
            'Wechatpay-Serial:'.self::getPulicCert($config),
            'Accept: application/json',
            'Content-Type: application/json; charset=utf-8',
            'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
        ];
        if (!empty($headers)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
    
    
    
    
    
     /**
     * 获取平台证书内容
     */
    public function get_Certificates()
    {
        $merchant_id      ="**************";//商户号
        $serial_no        = "*****************";//API证书序列号
        $sign             = self::get_Sign("https://api.mch.weixin.qq.com/v3/certificates","GET","",self::get_Privatekey(), $merchant_id, $serial_no);//$http_method要大写
        $header[]         = 'User-Agent:https://zh.wikipedia.org/wiki/User_agent';
        $header[]         = 'Accept:application/json';
        $header[]         = 'Authorization:WECHATPAY2-SHA256-RSA2048 ' . $sign;
        $back = self::http_Request("https://api.mch.weixin.qq.com/v3/certificates",$header);
        $re = json_decode($back,true);
        if(!isset($re['data'])){
            return ['err' => '平台证书获取失败'];
        }
        
        $ciphertext = $re['data'][0]['encrypt_certificate']['ciphertext'];

        $associatedData = $re['data'][0]['encrypt_certificate']['associated_data'];

        $nonceStr = $re['data'][0]['encrypt_certificate']['nonce'];

        $data = self::decryptToString($ciphertext, $associatedData, $nonceStr);

        if (!$data) {

            return ['err' => '平台证书解密失败'];
        }

        file_put_contents('./weixin/cert/wx_public_cert.pem', $data);

        return $data;
    }
    
    //解密数据

    public static function decryptToString($ciphertext, $associatedData, $nonceStr)
    {

        $aesKey = "*************"; //商户apiv3密钥解密

        $str = base64_decode($ciphertext);

        if (strlen($str) <= 16) {

            return '';
        }

        // 开启php sodium扩展

        return sodium_crypto_aead_aes256gcm_decrypt($str, $associatedData, $nonceStr, $aesKey);
    }
    
    //获取平台证书序列号

    public static function getPulicCert($config)
    {

        $publicCert = openssl_x509_parse(file_get_contents($config['wx_public_cert'], false));

        $wx_serial_no = $publicCert['serialNumberHex'];

        return $wx_serial_no;
    }
    
    /**
     * 获取sign
     * @param $url
     * @param $http_method [POST GET 必读大写]
     * @param $body [请求报文主体(必须进行json编码)]
     * @param $mch_private_key [商户私钥]
     * @param $merchant_id [商户号]
     * @param $serial_no [证书编号]
     * @return string
     */
    public static function get_Sign($url, $http_method, $body, $mch_private_key, $merchant_id, $serial_no)
    {
        $timestamp     = time();//时间戳
        $nonce         = $timestamp . rand(10000, 99999);//随机字符串
        $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);
        $token = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
            $merchant_id, $nonce, $timestamp, $serial_no, $sign);
        return $token;
    }
 
    /**
     * 获取商户私钥
     * @return false|resource
     */
    public static function get_Privatekey()
    {
        $private_key_file = (dirname(__FILE__) . '/key/private_key.pem');//私钥文件路径 如linux服务器秘钥地址地址:/www/wwwroot/test/key/private_key.pem"key支付证书绝对地址
        $mch_private_key  = openssl_get_privatekey(file_get_contents($private_key_file));//获取私钥
        return $mch_private_key;
    }

    
    
    /**
     * 数据请求
     * @param $url
     * @param array $header 获取头部
     * @param string $post_data POST数据,不填写默认以GET方式请求
     * @return bool|string
     */
    public static function http_Request($url, $header = array(), $post_data = "")
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 2);
        if ($post_data != "") {
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); //设置post提交数据
        }
        //判断当前是不是有post数据的发
        $output = curl_exec($ch);
        if ($output === FALSE) {
            $output = "curl 错误信息: " . curl_error($ch);
        }
        curl_close($ch);
        return $output;
    }
    
    // /**
    //  * @notes 敏感信息加解密
    //  * @param $str
    //  * @param $config
    //  * @return string
    //  * @throws \Exception
    //  */
    public static function getEncrypt($str, $config)
    {
        //$str是待加密字符串
        $public_key = file_get_contents($config['wx_public_cert']);
        $encrypted = '';
        if (openssl_public_encrypt($str, $encrypted, $public_key, OPENSSL_PKCS1_OAEP_PADDING)) {
            //base64编码
            $sign = base64_encode($encrypted);
        } else {
            throw new \Exception('encrypt failed');
        }
        return $sign;
    }
}

 

<?phpnamespace app\common\business;class WechatMerchantTransfer4{    /**     * @notes 商家转账到零钱     * @param $batch_no //提现订单号     * @param $left_money //提现金额 单位 元     * @param $user_openid //用户openID     * @param $withdraw_name //提现金额大于200,用户真实名字必填     * @return bool     * @throws \Exception     * @author ljj     * @date 2022/9/27 4:40 下午     */    public function transfer($batch_no, $left_money, $user_openid, $withdraw_name = '')    {               $config = [            'app_id' => 'wx44a99a70f322a945',            'mch_id' => '1600905662', //商户ID            'cert_client' => '/www/wwwroot/tp/public/www.clshj.wang/pay/SQRC/paychonglangcs/weixin/cert/apiclient_cert.pem', //cert证书地址//绝对路径            'cert_key' => '/www/wwwroot/tp/public/www.clshj.wang/pay/SQRC/paychonglangcs/weixin/cert/apiclient_key.pem', //key支付证书绝对地址            'wx_public_cert' => '/www/wwwroot/tp/public/www.clshj.wang/pay/SQRC/paychonglangcs/weixin/cert/wx_public_cert.pem', //平台证书        ];        $withdrawApply = [            'orderid' => '4889798798779878',            'real_name' => $withdraw_name,        ];        //请求URL        $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches';        //请求方式        $http_method = 'POST';        //请求参数                $data = [            'appid' => $config['app_id'], //申请商户号的appid或商户号绑定的appid(企业号corpid即为此appid)            'out_batch_no' => $batch_no, //商户系统内部的商家批次单号,要求此参数只能由数字、大小写字母组成,在商户系统内部唯一            'batch_name' => '提现至微信零钱', //该笔批量转账的名称            'batch_remark' => '提现至微信零钱', //转账说明,UTF8编码,最多允许32个字符            'total_amount' => $left_money * 100, //转账金额单位为“分”。转账总金额必须与批次内所有明细转账金额之和保持一致,否则无法发起转账操作            'total_num' => 1, //一个转账批次单最多发起三千笔转账。转账总笔数必须与批次内所有明细之和保持一致,否则无法发起转账操作            'transfer_detail_list' => [                [ //发起批量转账的明细列表,最多三千笔                    'out_detail_no' => $batch_no, //商户系统内部区分转账批次单下不同转账明细单的唯一标识,要求此参数只能由数字、大小写字母组成                    'transfer_amount' => $left_money * 100, //转账金额单位为分                    'transfer_remark' => '提现至微信零钱', //单条转账备注(微信用户会收到该备注),UTF8编码,最多允许32个字符                    'openid' => $user_openid, //openid是微信用户在公众号appid下的唯一用户标识(appid不同,则获取到的openid就不同),可用于永久标记一个用户                ]            ]        ];        // $certificatesInfo = self::get_Certificates();        // $serial_no = $certificatesInfo['data'][0]['serial_no'];        // $ciphertext = $certificatesInfo['data'][0]['encrypt_certificate']['ciphertext'];                if ($left_money >= 2000) {            if (empty($withdraw_name)) {                throw new \Exception('转账金额 >= 2000元,收款用户真实姓名必填');            }            $data['transfer_detail_list'][0]['user_name'] = self::getEncrypt($withdrawApply['real_name'], $config);            // $data['transfer_detail_list'][0]['user_name'] = "张学军";        }                
        $token = self::token($url, $http_method, $data, $config); //获取token                $result = self::https_request($url, json_encode($data), $token,$config); //发送请求        $result_arr = json_decode($result, true);
        if (!isset($result_arr['create_time'])) { //批次受理失败            throw new \Exception($result_arr['message']);        }        //      成功返回信息  {"batch_id":"1030001036201351072852022101201442513049","create_time":"2022-10-12T22:08:21+08:00","out_batch_no":"20221011004103000000146822"}        //批次受理成功,更新提现申请单为提现中状态        //业务修改为提现中
        return $result_arr;    }            /**     * @notes 签名生成     * @param $url     * @param $http_method     * @param $data     * @param $config     * @return string     * @author ljj     * @date 2022/9/27 4:14 下午     */    public static function token($url, $http_method, $data, $config)    {        $timestamp = time(); //请求时间戳        $url_parts = parse_url($url); //获取请求的绝对URL        $nonce = $timestamp . rand('10000', '99999'); //请求随机串        $body = empty($data) ? '' : json_encode((object)$data); //请求报文主体        $stream_opts = [            "ssl" => [                "verify_peer" => false,                "verify_peer_name" => false,            ]        ];        // $apiclient_cert_arr = openssl_x509_parse(file_get_contents($config['cert_client'], false, stream_context_create($stream_opts)));                      // $serial_no = $apiclient_cert_arr['serialNumberHex']; //证书序列号        $serial_no = '4DB946C0137A914AB92B3F2B5D5A9E0ADB9273C5'; //证书序列号        $mch_private_key = file_get_contents($config['cert_key'], false, stream_context_create($stream_opts)); //密钥        $merchant_id = $config['mch_id']; //商户id        $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); //签名        $schema = 'WECHATPAY2-SHA256-RSA2048';        $token = sprintf(            'mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',            $merchant_id,            $nonce,            $timestamp,            $serial_no,            $sign        ); //微信返回token        return $schema . ' ' . $token;    }         /**     * @notes 发送请求     * @param $url     * @param $data     * @param $token     * @return bool|string     * @author ljj     * @date 2022/9/27 4:15 下午     */    public static function https_request($url, $data, $token, $config)    {        $curl = curl_init();        curl_setopt($curl, CURLOPT_URL, (string)$url);        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);        if(!empty($data)){            curl_setopt($curl, CURLOPT_POST, 1);            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);        }        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);                // $verifier = "4DB946C0137A914AB92B3F2B5D5A9E0ADB9273C5";        // $verifier = self::getEncrypt($verifier, $config);        //添加请求头        $headers = [            'Authorization:' . $token,            'Wechatpay-Serial:'.self::getPulicCert($config),            'Accept: application/json',            'Content-Type: application/json; charset=utf-8',            'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',        ];        if (!empty($headers)) {            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);        }        $output = curl_exec($curl);        curl_close($curl);        return $output;    }                         /**     * 获取平台证书内容     */    public function get_Certificates()    {        $merchant_id      ="1600905662";//商户号        $serial_no        = "4DB946C0137A914AB92B3F2B5D5A9E0ADB9273C5";//API证书序列号        $sign             = self::get_Sign("https://api.mch.weixin.qq.com/v3/certificates","GET","",self::get_Privatekey(), $merchant_id, $serial_no);//$http_method要大写        $header[]         = 'User-Agent:https://zh.wikipedia.org/wiki/User_agent';        $header[]         = 'Accept:application/json';        $header[]         = 'Authorization:WECHATPAY2-SHA256-RSA2048 ' . $sign;        $back = self::http_Request("https://api.mch.weixin.qq.com/v3/certificates",$header);        $re = json_decode($back,true);        if(!isset($re['data'])){            return ['err' => '平台证书获取失败'];        }                $ciphertext = $re['data'][0]['encrypt_certificate']['ciphertext'];
        $associatedData = $re['data'][0]['encrypt_certificate']['associated_data'];
        $nonceStr = $re['data'][0]['encrypt_certificate']['nonce'];
        $data = self::decryptToString($ciphertext, $associatedData, $nonceStr);
        if (!$data) {
            return ['err' => '平台证书解密失败'];        }
        file_put_contents('/www/wwwroot/tp/public/www.clshj.wang/pay/SQRC/paychonglangcs/weixin/cert/wx_public_cert.pem', $data);
        return $data;    }        //解密数据
    public static function decryptToString($ciphertext, $associatedData, $nonceStr)    {
        $aesKey = "WNcTiKrVIIFOqiod0uU2IUzIhuLeLCab"; //商户apiv3密钥解密
        $str = base64_decode($ciphertext);
        if (strlen($str) <= 16) {
            return '';        }
        // 开启php sodium扩展
        return sodium_crypto_aead_aes256gcm_decrypt($str, $associatedData, $nonceStr, $aesKey);    }        //获取平台证书序列号
    public static function getPulicCert($config)    {
        $publicCert = openssl_x509_parse(file_get_contents($config['wx_public_cert'], false));
        $wx_serial_no = $publicCert['serialNumberHex'];
        return $wx_serial_no;    }        /**     * 获取sign     * @param $url     * @param $http_method [POST GET 必读大写]     * @param $body [请求报文主体(必须进行json编码)]     * @param $mch_private_key [商户私钥]     * @param $merchant_id [商户号]     * @param $serial_no [证书编号]     * @return string     */    public static function get_Sign($url, $http_method, $body, $mch_private_key, $merchant_id, $serial_no)    {        $timestamp     = time();//时间戳        $nonce         = $timestamp . rand(10000, 99999);//随机字符串        $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);        $token = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',            $merchant_id, $nonce, $timestamp, $serial_no, $sign);        return $token;    }     /**     * 获取商户私钥     * @return false|resource     */    public static function get_Privatekey()    {        //$private_key_file = (dirname(__FILE__) . '/key/private_key.pem');//私钥文件路径 如linux服务器秘钥地址地址:/www/wwwroot/test/key/private_key.pem"        $private_key_file = '/www/wwwroot/tp/public/www.clshj.wang/pay/SQRC/paychonglangcs/weixin/cert/apiclient_key.pem'; //key支付证书绝对地址        $mch_private_key  = openssl_get_privatekey(file_get_contents($private_key_file));//获取私钥        return $mch_private_key;    }
            /**     * 数据请求     * @param $url     * @param array $header 获取头部     * @param string $post_data POST数据,不填写默认以GET方式请求     * @return bool|string     */    public static function http_Request($url, $header = array(), $post_data = "")    {        $ch = curl_init();        curl_setopt($ch, CURLOPT_URL, $url);        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 2);        if ($post_data != "") {            curl_setopt($ch, CURLOPT_POST, TRUE);            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); //设置post提交数据        }        //判断当前是不是有post数据的发        $output = curl_exec($ch);        if ($output === FALSE) {            $output = "curl 错误信息: " . curl_error($ch);        }        curl_close($ch);        return $output;    }        // /**    //  * @notes 敏感信息加解密    //  * @param $str    //  * @param $config    //  * @return string    //  * @throws \Exception    //  * @author ljj    //  * @date 2022/9/27 3:53 下午    //  */    public static function getEncrypt($str, $config)    {        //$str是待加密字符串        $public_key = file_get_contents($config['wx_public_cert']);        $encrypted = '';        if (openssl_public_encrypt($str, $encrypted, $public_key, OPENSSL_PKCS1_OAEP_PADDING)) {            //base64编码            $sign = base64_encode($encrypted);        } else {            throw new \Exception('encrypt failed');        }        return $sign;    }}