SignHandler.php 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. <?php
  2. namespace App\Handlers;
  3. Class SignHandler
  4. {
  5. //读取商户api证书公钥
  6. public function getPublicKey(){
  7. return openssl_get_privatekey(file_get_contents(config('wechat.payment.default.key_path')));//商户平台API安全证书中下载,保存到服务器
  8. }
  9. //生成随机字符串
  10. public function nonce_str($length=32){
  11. $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
  12. $str ="";
  13. for ( $i = 0; $i < $length; $i++ ) {
  14. $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
  15. }
  16. return $str;
  17. }
  18. //签名
  19. public function sign($url,$http_method,$timestamp,$nonce,$body,$mch_private_key,$merchant_id,$serial_no){
  20. $url_parts=parse_url($url);
  21. $canonical_url=($url_parts['path'].(!empty($url_parts['query'])?"?${url_parts['query']}":""));
  22. $message=
  23. $http_method . "\n".
  24. $canonical_url . "\n".
  25. $timestamp . "\n".
  26. $nonce . "\n".
  27. $body . "\n";
  28. openssl_sign($message,$raw_sign,$mch_private_key,'sha256WithRSAEncryption');
  29. $sign=base64_encode($raw_sign);
  30. $schema='WECHATPAY2-SHA256-RSA2048';
  31. $token=sprintf(
  32. 'mchid="%s",nonce_str="%s",signature="%s",timestamp="%d",serial_no="%s"',
  33. $merchant_id,
  34. $nonce,
  35. $sign,
  36. $timestamp,
  37. $serial_no
  38. );
  39. return $token;
  40. }
  41. //获取平台证书
  42. public function getzhengshu(){
  43. $url="https://api.mch.weixin.qq.com/v3/certificates";//获取地址
  44. $timestamp=time();//时间戳
  45. $nonce=$this->nonce_str();//获取一个随机字符串
  46. $body="";
  47. $mch_private_key=$this->getPublicKey();//读取商户api证书公钥
  48. $merchant_id=config('wechat.payment.default.mch_id');//商户号
  49. $serial_no=config('wechat.payment.default.serial_no');//商户证书序列号
  50. $sign=$this->sign($url,'GET',$timestamp,$nonce,$body,$mch_private_key,$merchant_id,$serial_no);
  51. $header=[
  52. 'Authorization:WECHATPAY2-SHA256-RSA2048 '.$sign,
  53. 'Accept:application/json',
  54. 'User-Agent:'.$merchant_id
  55. ];
  56. $result=$this->curl($url,'',$header,'GET');
  57. $result=json_decode($result,true);
  58. $serial_no=$result['data'][0]['serial_no'];//获取的平台证书序列号
  59. $encrypt_certificate=$result['data'][0]['encrypt_certificate'];
  60. $sign_key=config('wechat.payment.default.api_v3'); //APIv3密钥,商户平台API安全中获取
  61. $result=$this->decryptToString($encrypt_certificate['associated_data'],$encrypt_certificate['nonce'],$encrypt_certificate['ciphertext'],$sign_key);
  62. file_put_contents(config('wechat.payment.default.cert_pem'),$result);//获取的文件临时保存到服务器
  63. return $serial_no;//返回平台证书序列号
  64. }
  65. //解密返回的信息
  66. public function decryptToString($associatedData,$nonceStr,$ciphertext,$aesKey){
  67. if (strlen($aesKey) != 32) {
  68. throw new InvalidArgumentException('无效的ApiV3Key,长度应为32个字节');
  69. }
  70. // $this->aesKey = $aesKey;
  71. $ciphertext=\base64_decode($ciphertext);
  72. if (strlen($ciphertext) <= 16) {
  73. return false;
  74. }
  75. if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') &&
  76. \sodium_crypto_aead_aes256gcm_is_available()) {
  77. return \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, $aesKey);
  78. return '1111';
  79. }
  80. // ext-libsodium (need install libsodium-php 1.x via pecl)
  81. if (function_exists('\Sodium\crypto_aead_aes256gcm_is_available') &&
  82. \Sodium\crypto_aead_aes256gcm_is_available()) {
  83. return '222';
  84. return \Sodium\crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, $aesKey);
  85. }
  86. // if(function_exists('\sodium_crypto_aead_aes256gcm_is_available')&& \sodium_crypto_aead_aes256gcm_is_available()){
  87. // return \sodium_crypto_aead_aes256gcm_decrypt($ciphertext,$associatedData,$nonceStr,$aesKey);
  88. // }
  89. if(PHP_VERSION_ID >= 70100 && in_array('aes-256-gcm', \openssl_get_cipher_methods())){
  90. $ctext=substr($ciphertext,0,-16);
  91. $authTag=substr($ciphertext,-16);
  92. return \openssl_decrypt(
  93. $ctext,
  94. 'aes-256-gcm',
  95. $aesKey,
  96. \OPENSSL_RAW_DATA,
  97. $nonceStr,
  98. $authTag,
  99. $associatedData
  100. );
  101. }
  102. throw new \RuntimeException('php7.1');
  103. }
  104. //curl提交
  105. public function curl($url,$data=[],$header,$method='POST'){
  106. $curl=curl_init();
  107. curl_setopt($curl,CURLOPT_URL,$url);
  108. curl_setopt($curl,CURLOPT_HTTPHEADER,$header);
  109. curl_setopt($curl,CURLOPT_HEADER,false);
  110. curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
  111. curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
  112. if($method=="POST"){
  113. curl_setopt($curl,CURLOPT_POST,TRUE);
  114. curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
  115. }
  116. $result=curl_exec($curl);
  117. curl_close($curl);
  118. return $result;
  119. }
  120. }