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