php微信特约商户进件V3封装接口

<?php

/**
 * 微信服务商V3
 */
class Wxpaymch
{
    // 错误信息
    private $error = '';

    // 商户mchid
    private $mch_id = 'xxxx';

    // 商户API v3密钥(微信服务商-账户中心-API安全 api v3密钥 https://pay.weixin.qq.com/index.php/core/cert/api_cert)
    private $mch_api_key = 'xxxx';

    // 证书编号 (apiclient_cert.pem证书解析后获得)
    private $serial_no = 'xxxx';

    // 私钥 apiclient_key.pem(微信服务商-账户中心-API安全 自行下载 https://pay.weixin.qq.com/index.php/core/cert/api_cert)
    private $mch_private_key = __DIR__ . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR . 'apiclient_key.pem';

    // 支付平台公钥(接口获取)
    private $public_key_path = __DIR__ . DIRECTORY_SEPARATOR . 'cert_ficates_v3.pem';

    /*
     * 微信特约商户进件接口
     */
    public function subApplyment( array $params)
    {

        // 参数准备
        $data = [
            //业务申请编号
            'business_code'     => $this->getBusinessCode(),
            //超级管理员信息
            'contact_info'      => [
                'contact_name'      => $this->getEncrypt($params['contact_name']),//超级管理员姓名
                'contact_id_number' => $this->getEncrypt($params['contact_id_number']),//超级管理员身份证件号码
                'mobile_phone'      => $this->getEncrypt($params['mobile_phone']),//联系手机
                'contact_email'     => $this->getEncrypt($params['contact_email']),//联系邮箱
            ],
            //主体资料
            'subject_info'      => [
                //主体类型SUBJECT_TYPE_INDIVIDUAL(个体户)SUBJECT_TYPE_ENTERPRISE(企业)SUBJECT_TYPE_INSTITUTIONS(党政、机关及事业单位)SUBJECT_TYPE_OTHERS(其他组织)
                'subject_type'  => 'SUBJECT_TYPE_INDIVIDUAL',
                //经营者/法人身份证件
                'identity_info' => [
                    'id_doc_type'  => 'IDENTIFICATION_TYPE_IDCARD',//证件类型
                    'owner'        => true,//经营者/法人是否为受益人
                    //身份证信息
                    'id_card_info' => [
                        'id_card_copy'      => 'jTpGmxUX3FBWVQ5NJTZvlKX_gdU4cRz7z5NxpnFuAxhBTEO_PvWkfSCJ3zVIn001D8daLC-ehEuo0BJqRTvDujqhThn4ReFxikqJ5YW6zFQ',
                        'id_card_national'  => '47ZC6GC-vnrbEny__Ie_An5-tCpqxucuxi-vByf3Gjm7KE53JXvGy9tqZm2XAUf-4KGprrKhpVBDIUv0OF4wFNIO4kqg05InE4d2I6_H7I4',
                        'id_card_name'      => $this->getEncrypt($params['id_card_name']),
                        'id_card_number'    => $this->getEncrypt($params['id_card_number']),
                        'card_period_begin' => '2026-06-06',
                        'card_period_end'   => '2036-06-06',
                    ],
                ],
            ],
            //经营资料
            'business_info'     => [
                'merchant_shortname' => $params['merchant_shortname'],
                'service_phone'      => $params['service_phone'],
                'sales_info'         => [
                    'sales_scenes_type' => ['SALES_SCENES_STORE'],
                    //线下门店场景
                    'biz_store_info'    => [
                        'biz_store_name'     => $params['biz_store_name'],
                        'biz_address_code'   => $params['biz_address_code'],
                        'biz_store_address'  => $params['biz_store_address'],
                        'store_entrance_pic' => ['0P3ng6KTIW4-QJBZR9FwczhJehHhAZN6BKXQPcs-VvdSo'],
                        'indoor_pic'         => ['0P3ng6KTIW4-Q_l2FjmFJBZR9FwczhJehHhAZN6BKXQPcs-VvdSo'],
                    ],
                ],
            ],
            //结算规则
            'settlement_info'   => [
                'settlement_id'      => $params['settlement_id'],
                'qualification_type' => $params['qualification_type'],
                'activities_id'      => $params['activities_id'],
                'activities_rate'    => $params['activities_rate'],
            ],
            //结算银行账户
            'bank_account_info' => [
                'bank_account_type' => 'BANK_ACCOUNT_TYPE_CORPORATE',
                'account_name'      => $this->getEncrypt($params['account_name']),
                'account_bank'      => $params['account_bank'],
                'bank_address_code' => $params['bank_address_code'],
                'bank_name'         => $params['bank_name'],
                'account_number'    => $this->getEncrypt($params['account_number']),
            ],
            //补充材料
            'addition_info'=>[
                'legal_person_commitment'=>$params['legal_person_commitment'],
                'business_addition_pics'=>$params['business_addition_pics'],
            ],
        ];

        $url = 'https://api.mch.weixin.qq.com/v3/applyment4sub/applyment/';

        // 获取支付平台证书编码(也可以用接口中返回的serial_no  来源:https://api.mch.weixin.qq.com/v3/certificates)
        $serial_no = $this->parseSerialNo($this->getCertFicates());
        $bodyData  = json_encode($data);

        // 获取认证信息
        $authorization = $this->getAuthorization($url, 'POST', $bodyData);

        $header = [
            'Content-Type:application/json',
            'Accept:application/json',
            'User-Agent:*/*',

            'Authorization:' . $authorization,
            'Wechatpay-Serial:' . $serial_no
        ];
        $json   = $this->getCurl('POST', $url, $bodyData, $header);
        $data   = json_decode($json, true);

        if (isset($data['code']) && isset($data['message'])) {
            $this->error = '[subApplyment]请求错误 code:' . $data['code'] . ' msg:' . $data['message'];
            return false;
        }
        if (empty($applyment_id = $data['applyment_id'])) {
            $this->error = '[subApplyment]返回错误';
            return false;
        }
        return $applyment_id;
    }

    /**
     * 进件查询
     */
    public function queryApplyment($business_code)
    {
        $url = 'https://api.mch.weixin.qq.com/v3/applyment4sub/applyment/business_code/' . $business_code;

        // 获取认证信息
        $authorization = $this->getAuthorization($url);
        $header        = [
            'Content-Type:application/json',
            'Accept:application/json',
            'User-Agent:*/*',

            'Authorization:' . $authorization
        ];
        $json          = $this->getCurl('GET', $url, '', $header);

        $data = json_decode($json, true);

        if (isset($data['code']) && isset($data['message'])) {
            $this->error = '[queryApplyment]请求错误 code:' . $data['code'] . ' msg:' . $data['message'];
            return false;
        }
        return $data;
    }

    /**
     * 上传文件
     */
    public function mediaUpload()
    {
        // 上传图片
        $filename = '1.png';
        $filepath = __DIR__ . '/' . $filename;
        if (!file_exists($filepath)) {
            $this->error = '[mediaUpload]文件找不到';
        }

        $url       = 'https://api.mch.weixin.qq.com/v3/merchant/media/upload';
        $fi        = new \finfo(FILEINFO_MIME_TYPE);
        $mime_type = $fi->file($filepath);
        $meta      = [
            'filename' => $filename,
            'sha256'   => hash_file('sha256', $filepath)
        ];

        // 获取认证信息
        $authorization = $this->getAuthorization($url, 'POST', json_encode($meta));
        $boundary      = uniqid();
        $header        = [
            'Accept:application/json',
            'User-Agent:*/*',

            'Content-Type:multipart/form-data;boundary=' . $boundary,
            'Authorization:' . $authorization
        ];

        // 组合参数
        $boundaryStr = "--{$boundary}\r\n";
        $out         = $boundaryStr;
        $out         .= 'Content-Disposition: form-data; name="meta"' . "\r\n";
        $out         .= 'Content-Type: application/json' . "\r\n";
        $out         .= "\r\n";
        $out         .= json_encode($meta) . "\r\n";
        $out         .= $boundaryStr;
        $out         .= 'Content-Disposition: form-data; name="file"; filename="' . $filename . '"' . "\r\n";
        $out         .= 'Content-Type: ' . $mime_type . ';' . "\r\n";
        $out         .= "\r\n";
        $out         .= file_get_contents($filepath) . "\r\n";
        $out         .= "--{$boundary}--\r\n";
        $json        = $this->getCurl('POST', $url, $out, $header);
        $data        = json_decode($json, true);

        if (isset($data['code']) && isset($data['message'])) {
            $this->error = '[mediaUpload]请求错误 code:' . $data['code'] . ' msg:' . $data['message'];
            return false;
        }
        if (empty($media_id = $data['media_id'])) {
            $this->error = '[mediaUpload]返回错误';
            return false;
        }
        return $media_id;
    }

    /**
     * 获取微信支付平台证书
     */
    public function certFicates()
    {
        $url = 'https://api.mch.weixin.qq.com/v3/certificates';

        // 获取认证信息
        $authorization = $this->getAuthorization($url);
        $header        = [
            'Content-Type:application/json',
            'Accept:application/json',
            'User-Agent:*/*',

            'Authorization:' . $authorization
        ];

        $json = $this->getCurl('GET', $url, '', $header);
        $data = json_decode($json, true);
        if (isset($data['code']) && isset($data['message'])) {
            $this->error = '[certFicates]请求错误 code:' . $data['code'] . ' msg:' . $data['message'];
            return false;
        }
        if (empty($cfdata = $data['data'][0])) {
            $this->error = '[certFicates]返回错误';
            return false;
        }
        return $cfdata;
    }

    /**
     * 获取认证信息
     * @param string $url
     * @param string $http_method
     * @param string $body
     * @return string
     * @throws Exception
     */
    private function getAuthorization($url, $http_method = 'GET', $body = '')
    {
        if (!in_array('sha256WithRSAEncryption', \openssl_get_md_methods(true))) {
            throw new \Exception("当前PHP环境不支持SHA256withRSA");
        }
        //私钥地址
        $mch_private_key = $this->mch_private_key;
        //商户号
        $merchant_id = $this->mch_id;
        //当前时间戳
        $timestamp = time();
        //随机字符串
        $nonce = $this->getNonceStr();
        //证书编号
        $serial_no = $this->serial_no;

        $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, \openssl_get_privatekey(\file_get_contents($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);
        return $schema . ' ' . $token;
    }

    /**
     * 敏感字符加密
     * @param $str
     * @return string
     * @throws Exception
     */
    private function getEncrypt($str)
    {
        static $content;
        if (empty($content)) {
            $content = $this->getCertFicates();
        }
        $encrypted = '';
        if (openssl_public_encrypt($str, $encrypted, $content, OPENSSL_PKCS1_OAEP_PADDING)) {
            //base64编码
            $sign = base64_encode($encrypted);
        }
        else {
            throw new \Exception('encrypt failed');
        }
        return $sign;
    }

    /**
     * 获取支付平台证书
     * @return false|string
     */
    private function getCertFicates()
    {
        $public_key_path = $this->public_key_path;
        if (!file_exists($public_key_path)) {
            $cfData = $this->certFicates();

            $content = $this->decryptToString($cfData['encrypt_certificate']['associated_data'], $cfData['encrypt_certificate']['nonce'], $cfData['encrypt_certificate']['ciphertext'], $this->mch_api_key);
            file_put_contents($public_key_path, $content);
        }
        else {
            $content = file_get_contents($public_key_path);
        }
        return $content;
    }

    /**
     * 业务编号
     * @return string
     */
    private function getBusinessCode()
    {
        return date('Ymd') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
    }

    /**
     * 随机字符串
     * @param int $length
     * @return string
     */
    private function getNonceStr($length = 16)
    {
        // 密码字符集,可任意添加你需要的字符
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str   = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $str;
    }

    /**
     * @param string       $method
     * @param string       $url
     * @param array|string $data
     * @param array        $headers
     * @param int          $timeout
     * @return bool|string
     */
    private function getCurl($method = 'GET', $url, $data, $headers = [], $timeout = 10)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);

        if (!empty($headers)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        if ($method == 'POST') {
            curl_setopt($curl, CURLOPT_POST, TRUE);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        else {
        }
        $result = curl_exec($curl);

        curl_close($curl);
        return $result;
    }

    /**
     * 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
     */
    private function decryptToString($associatedData, $nonceStr, $ciphertext, $aesKey)
    {
        $auth_tag_length_byte = 16;

        $ciphertext = \base64_decode($ciphertext);
        if (strlen($ciphertext) <= $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, -$auth_tag_length_byte);
            $authTag = substr($ciphertext, -$auth_tag_length_byte);

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

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

    /**
     * 获取证书编号(官方案例-已改造)
     * @param $certificate
     * @return string
     */
    private function parseSerialNo($certificate)
    {
        $info = \openssl_x509_parse($certificate);
        if (!isset($info['serialNumber']) && !isset($info['serialNumberHex'])) {
            throw new \InvalidArgumentException('证书格式错误');
        }

        $serialNo = '';
        // PHP 7.0+ provides serialNumberHex field
        if (isset($info['serialNumberHex'])) {
            $serialNo = $info['serialNumberHex'];
        }
        else {
            // PHP use i2s_ASN1_INTEGER in openssl to convert serial number to string,
            // i2s_ASN1_INTEGER may produce decimal or hexadecimal format,
            // depending on the version of openssl and length of data.
            if (\strtolower(\substr($info['serialNumber'], 0, 2)) == '0x') { // HEX format
                $serialNo = \substr($info['serialNumber'], 2);
            }
            else { // DEC format
                $value     = $info['serialNumber'];
                $hexvalues = ['0', '1', '2', '3', '4', '5', '6', '7',
                    '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
                while ($value != '0') {
                    $serialNo = $hexvalues[\bcmod($value, '16')] . $serialNo;
                    $value    = \bcdiv($value, '16', 0);
                }
            }
        }

        return \strtoupper($serialNo);
    }

    public function getError()
    {
        return $this->error;
    }

}
————————————————
版权声明:本文为CSDN博主「variation8」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_31151123/article/details/117529627

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值