Test.php 7.0 KB

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