php微信支付v3版簽名生成,代金券、微信支付分、支付即服務等


對接微信新版SDKv3版

簽名生成規則,微信的官方文檔里面說明的還算可以吧,不過個人覺得不太理想- -。  自己調試的時候調試了半天才找了錯誤原因。

https://wechatpay-api.gitbook.io/wechatpay-api-v3

 

微信v3接口更換了新版簽名方式

  商戶需要使用自身的私鑰對API URL、消息體等關鍵數據的組合進行SHA-256 with RSA簽名。
       請求的簽名信息通過HTTP頭Authorization傳遞,具體說明請見簽名生成指南
       沒有攜帶簽名或者簽名驗證不通過的請求,都不會被執行,並返回401 Unauthorized
 
 
 
官方有給提供了類庫和SDK
     不過我這里是舊項目沒有用着composer, 使用官方提供的話  需要改動太大,所以這里就自己做了一個簡單的封裝, 所以不清楚官方提供的庫具體如何。
 
 
//生成v3 Authorization
    protected function createAuthorization( $url , $method = 'GET' ){

        if (!in_array('sha256WithRSAEncryption', \openssl_get_md_methods(true))) {
            throw new \RuntimeException("當前PHP環境不支持SHA256withRSA");
        }
        $url_parts = parse_url($url);
        $canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));

        //私鑰地址
        $mch_private_key = $this->mch_private_key;
        //商戶號
        $merchant_id = $this->mch_id;
        //當前時間戳
        $timestamp =  time();
        //隨機字符串
        $nonce = $this->createNoncestr();
        //POST請求時 需要 轉JSON字符串
        $body =  $this->body ;
        $message = "{$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);
        //Authorization 類型  
        $schema = 'WECHATPAY2-SHA256-RSA2048';
        //生成token
        $token = sprintf('mchid="%s",serial_no="%s",nonce_str="%s",timestamp="%d",signature="%s"', $merchant_id,$this->serial_no, $nonce, $timestamp,  $sign);

        $header = [
            'Content-Type:application/json',
            'Accept:application/json',
            'User-Agent:*/*',
            'Authorization: '.  $schema . ' ' . $token
        ];
        return $header;
    }
/**
     *  作用:產生隨機字符串,不長於32位
     */
    public function createNoncestr( $length = 32 )
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str ="";
        for ( $i = 0; $i < $length; $i++ )  {
            $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return $str;
    }

 

    獲取平台證書及平台證書序列號,加密解密,個別V3接口需要用到。

官方地址:https://wechatpay-api.gitbook.io/wechatpay-api-v3/qian-ming-zhi-nan-1/wei-xin-zhi-fu-ping-tai-zheng-shu-geng-xin-zhi-yin
 

/**
* 支付及服務 - 服務人員注冊
* 1. 獲取平台證書序列號 serial_no與 商戶支付證書不是一個
* 2. 解密平台證書,拿到平台證書信息
* 3. 加密請求參數時 需要用戶 平台證書進行加密
*/ public function regguide( $post ,$serial_no){ $url = "https://api.mch.weixin.qq.com/v3/smartguide/guides"; $this->setBody( $post ); //生成V3請求 header認證信息 $header = $this->createAuthorization( $url , 'POST' ); //增加平台證書序列號 , 平台證書序列號方法 getcertificates()
$header[] = 'Wechatpay-Serial:' . $serial_no; $data = $this->postXmlCurl(json_encode($post , JSON_UNESCAPED_UNICODE) , $url , 30 , $header ); return json_decode($data , true); }

 

    /**
     * 獲取平台證書, 與商戶證書不是一個內容
     */
    public function getcertificates(){

        $url="https://api.mch.weixin.qq.com/v3/certificates";

        //生成V3請求 header認證信息
        $header = $this->createAuthorization( $url );

        $header[] = 'User-Agent : https://zh.wikipedia.org/wiki/User_agent';

        $data = $this->getXmlCurl( $url  , $this->curl_timeout , $header );

        return json_decode($data , true);

    }
   /**
     * V3加密
     */
    public function getEncrypt($str){ 
        //$str是待加密字符串 
        $public_key_path = '證書地址'; //看情況使用證書, 個別接口證書 使用的是 平台證書而不是 api證書
        $public_key = file_get_contents($public_key_path); 
        $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;
    }


/**
     * Decrypt AEAD_AES_256_GCM ciphertext  V3簽名解密
     * @param stingr    $aesKey             V3簽名
     * @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 function decryptToString($aesKey ,$associatedData, $nonceStr, $ciphertext)
    {

        if (strlen($aesKey) != 32 ) {
            throw new InvalidArgumentException('無效的ApiV3Key,長度應為32個字節');
        }

        $ciphertext = \base64_decode($ciphertext , true);
        if (strlen($ciphertext) <= 16) {
            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);
        }
        
        // PHP >= 7.1
        if(PHP_VERSION_ID >= 70100 && in_array('aes-256-gcm', \openssl_get_cipher_methods()) ){
            $ctext = substr($ciphertext, 0, -16);
            $authTag = substr($ciphertext, -16);
            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');
    }

 

注意:
     我這里缺少代碼直接獲取商戶序列號的方法,serial_no
     可以自己查看官方文檔或者 我這里是直接 獲取的證書信息里面的序列號, 也可以通過  https://myssl.com/cert_decode.html   去查看證書的序列號。
     如果是GET請求方式的$url 需要是完整地址 host+path+query  。
     如果是POST等其他請求方式 時, 請求BODY需要與query參數一致,且轉JSON字符串
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM