Test.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. <?php
  2. namespace app\api\controller;
  3. use app\api\service\WxService;
  4. use app\common\controller\Api;
  5. class Test extends Api
  6. {
  7. protected $noNeedLogin = ["*"];
  8. function payment()
  9. {
  10. $service = (new WxService);
  11. $SR = $service->appletPay("oQ_977SN3KhBetHY9OPckGP9DNNc", self::getRandomStr(20), "sbsbsb", 0.01);
  12. $SR->code() ? $this->success($SR->data()) : $this->error($SR->msg());
  13. }
  14. function test1()
  15. {
  16. self::certificates();
  17. }
  18. /**
  19. * 获取证书
  20. * @return mixed
  21. */
  22. public static function certificates()
  23. {
  24. //请求参数(报文主体)
  25. $headers = self::sign('GET', 'https://api.mch.weixin.qq.com/v3/certificates', '');
  26. $result = self::curl_get('https://api.mch.weixin.qq.com/v3/certificates', $headers);
  27. $result = json_decode($result, true);
  28. dump($result);//解密后的内容,就是证书内容
  29. $aa = self::decryptToString($result['data'][0]['encrypt_certificate']['associated_data'], $result['data'][0]['encrypt_certificate']['nonce'], $result['data'][0]['encrypt_certificate']['ciphertext']);
  30. var_dump($aa);//解密后的内容,就是证书内容
  31. }
  32. /**
  33. * 签名
  34. * @param string $http_method 请求方式GET|POST
  35. * @param string $url url
  36. * @param string $body 报文主体
  37. * @return array
  38. */
  39. public static function sign($http_method = 'POST', $url = '', $body = '')
  40. {
  41. $mch_private_key = self::getMchKey();//私钥
  42. $timestamp = time();//时间戳
  43. $nonce = self::getRandomStr(32);//随机串
  44. $url_parts = parse_url($url);
  45. $canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
  46. //构造签名串
  47. $message = $http_method . "\n" .
  48. $canonical_url . "\n" .
  49. $timestamp . "\n" .
  50. $nonce . "\n" .
  51. $body . "\n";//报文主体
  52. //计算签名值
  53. openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');
  54. $sign = base64_encode($raw_sign);
  55. //设置HTTP头
  56. $config = self::config();
  57. $token = sprintf('WECHATPAY2-SHA256-RSA2048 mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
  58. $config['mchid'], $nonce, $timestamp, $config['serial_no'], $sign);
  59. return [
  60. 'Accept: application/json',
  61. 'User-Agent: */*',
  62. 'Content-Type: application/json; charset=utf-8',
  63. 'Authorization: ' . $token,
  64. ];
  65. }
  66. //私钥
  67. public static function getMchKey()
  68. {
  69. //path->私钥文件存放路径
  70. return openssl_get_privatekey(file_get_contents("file://D:/project_c/billiards-server/certificate/wx/apiclient_key.pem"));
  71. }
  72. /**
  73. * 获得随机字符串
  74. * @param $len integer 需要的长度
  75. * @param $special bool 是否需要特殊符号
  76. * @return string 返回随机字符串
  77. */
  78. public static function getRandomStr($len, $special = false)
  79. {
  80. $chars = array(
  81. "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
  82. "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
  83. "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
  84. "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
  85. "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
  86. "3", "4", "5", "6", "7", "8", "9"
  87. );
  88. if ($special) {
  89. $chars = array_merge($chars, array(
  90. "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
  91. "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
  92. "}", "<", ">", "~", "+", "=", ",", "."
  93. ));
  94. }
  95. $charsLen = count($chars) - 1;
  96. shuffle($chars); //打乱数组顺序
  97. $str = '';
  98. for ($i = 0; $i < $len; $i++) {
  99. $str .= $chars[mt_rand(0, $charsLen)]; //随机取出一位
  100. }
  101. return $str;
  102. }
  103. /**
  104. * 配置
  105. */
  106. public static function config()
  107. {
  108. return [
  109. 'appid' => '',
  110. 'mchid' => '1638097896',//商户号
  111. 'serial_no' => '13A336433257E2C58CB5A6BC469B7040EF7E7456',//证书序列号
  112. 'description' => '',//应用名称(随意)
  113. 'notify' => '',//支付回调
  114. ];
  115. }
  116. //get请求
  117. public static function curl_get($url, $headers = array())
  118. {
  119. $info = curl_init();
  120. curl_setopt($info, CURLOPT_RETURNTRANSFER, true);
  121. curl_setopt($info, CURLOPT_HEADER, 0);
  122. curl_setopt($info, CURLOPT_NOBODY, 0);
  123. curl_setopt($info, CURLOPT_SSL_VERIFYPEER, false);
  124. curl_setopt($info, CURLOPT_SSL_VERIFYPEER, false);
  125. curl_setopt($info, CURLOPT_SSL_VERIFYHOST, false);
  126. //设置header头
  127. curl_setopt($info, CURLOPT_HTTPHEADER, $headers);
  128. curl_setopt($info, CURLOPT_URL, $url);
  129. $output = curl_exec($info);
  130. curl_close($info);
  131. return $output;
  132. }
  133. const KEY_LENGTH_BYTE = 32;
  134. const AUTH_TAG_LENGTH_BYTE = 16;
  135. /**
  136. * Decrypt AEAD_AES_256_GCM ciphertext
  137. *
  138. * @param string $associatedData AES GCM additional authentication data
  139. * @param string $nonceStr AES GCM nonce
  140. * @param string $ciphertext AES GCM cipher text
  141. *
  142. * @return string|bool Decrypted string on success or FALSE on failure
  143. */
  144. public static function decryptToString($associatedData, $nonceStr, $ciphertext)
  145. {
  146. $aesKey = '5a523a148c428bf8c4af91000fc307a6';
  147. $ciphertext = \base64_decode($ciphertext);
  148. if (strlen($ciphertext) <= self::AUTH_TAG_LENGTH_BYTE) {
  149. return false;
  150. }
  151. // ext-sodium (default installed on >= PHP 7.2)
  152. if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {
  153. return \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, $aesKey);
  154. }
  155. // ext-libsodium (need install libsodium-php 1.x via pecl)
  156. if (function_exists('\Sodium\crypto_aead_aes256gcm_is_available') && \Sodium\crypto_aead_aes256gcm_is_available()) {
  157. return \Sodium\crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, $aesKey);
  158. }
  159. // openssl (PHP >= 7.1 support AEAD)
  160. if (PHP_VERSION_ID >= 70100 && in_array('aes-256-gcm', \openssl_get_cipher_methods())) {
  161. $ctext = substr($ciphertext, 0, -self::AUTH_TAG_LENGTH_BYTE);
  162. $authTag = substr($ciphertext, -self::AUTH_TAG_LENGTH_BYTE);
  163. return \openssl_decrypt($ctext, 'aes-256-gcm', $aesKey, \OPENSSL_RAW_DATA, $nonceStr,
  164. $authTag, $associatedData);
  165. }
  166. throw new \RuntimeException('AEAD_AES_256_GCM需要PHP 7.1以上或者安装libsodium-php');
  167. }
  168. }