BaseClient.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2024 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace crmeb\services\easywechat;
  12. use think\facade\Log;
  13. use EasyWeChat\Core\AbstractAPI;
  14. use EasyWeChat\Core\AccessToken;
  15. use EasyWeChat\Core\Exceptions\HttpException;
  16. use EasyWeChat\Core\Exceptions\InvalidConfigException;
  17. use EasyWeChat\Core\Http;
  18. use EasyWeChat\Encryption\EncryptionException;
  19. use think\exception\InvalidArgumentException;
  20. class BaseClient extends AbstractAPI
  21. {
  22. protected $app;
  23. const KEY_LENGTH_BYTE = 32;
  24. const AUTH_TAG_LENGTH_BYTE = 16;
  25. protected $isService = true;
  26. public function __construct(AccessToken $accessToken, $app)
  27. {
  28. parent::__construct($accessToken);
  29. $this->app = $app;
  30. }
  31. public function setServiceStatus($val)
  32. {
  33. $this->isService = $val;
  34. return $this;
  35. }
  36. /**
  37. * @param $api
  38. * @param $params
  39. * @return \EasyWeChat\Support\Collection|null
  40. * @throws \EasyWeChat\Core\Exceptions\HttpException
  41. */
  42. protected function httpPostJson($api, $params)
  43. {
  44. try {
  45. return $this->parseJSON('json', [$api, $params]);
  46. } catch (HttpException $e) {
  47. $code = $e->getCode();
  48. throw new HttpException("接口异常[$code]" . ($e->getMessage()), $code);
  49. }
  50. }
  51. /**
  52. * @param $api
  53. * @param $params
  54. * @return \EasyWeChat\Support\Collection|null
  55. * @throws \EasyWeChat\Core\Exceptions\HttpException
  56. */
  57. protected function httpPost($api, $params)
  58. {
  59. try {
  60. return $this->parseJSON('post', [$api, $params]);
  61. } catch (HttpException $e) {
  62. $code = $e->getCode();
  63. throw new HttpException("接口异常[$code]" . ($e->getMessage()), $code);
  64. }
  65. }
  66. /**
  67. * @param $api
  68. * @param $params
  69. * @return \EasyWeChat\Support\Collection|null
  70. * @throws \EasyWeChat\Core\Exceptions\HttpException
  71. */
  72. protected function httpGet($api, $params)
  73. {
  74. try {
  75. return $this->parseJSON('get', [$api, $params]);
  76. } catch (HttpException $e) {
  77. $code = $e->getCode();
  78. throw new HttpException("接口异常[$code]" . ($e->getMessage()), $code);
  79. }
  80. }
  81. /**
  82. * request.
  83. *
  84. * @param string $endpoint
  85. * @param string $method
  86. * @param array $options
  87. * @param bool $returnResponse
  88. */
  89. public function request(string $endpoint, string $method = 'POST', array $options = [], $serial = true)
  90. {
  91. $sign_body = $options['sign_body'] ?? '';
  92. $headers = [
  93. 'Content-Type' => 'application/json',
  94. 'User-Agent' => 'curl',
  95. 'Accept' => 'application/json',
  96. 'Authorization' => $this->getAuthorization($endpoint, $method, $sign_body),
  97. // 'Wechatpay-Serial' => $this->app['config']['payment']['serial_no']
  98. ];
  99. $options['headers'] = array_merge($headers, ($options['headers'] ?? []));
  100. if ($serial) $options['headers']['Wechatpay-Serial'] = $this->app->certficates->setServiceStatus($this->isService)->get()['serial_no'];
  101. Http::setDefaultOptions($options);
  102. return $this->_doRequestCurl($method, 'https://api.mch.weixin.qq.com' . $endpoint, $options);
  103. }
  104. private function _doRequestCurl($method, $location, $options = [])
  105. {
  106. $curl = curl_init();
  107. // POST数据设置
  108. if (strtolower($method) === 'post') {
  109. curl_setopt($curl, CURLOPT_POST, true);
  110. curl_setopt($curl, CURLOPT_POSTFIELDS, $options['data'] ?? $options['sign_body'] ?? '');
  111. }
  112. // CURL头信息设置
  113. if (!empty($options['headers'])) {
  114. $headers = [];
  115. foreach ($options['headers'] as $k => $v) {
  116. $headers[] = "$k: $v";
  117. }
  118. curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  119. }
  120. curl_setopt($curl, CURLOPT_URL, $location);
  121. curl_setopt($curl, CURLOPT_HEADER, true);
  122. curl_setopt($curl, CURLOPT_TIMEOUT, 60);
  123. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  124. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  125. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
  126. $content = curl_exec($curl);
  127. $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
  128. curl_close($curl);
  129. return json_decode(substr($content, $headerSize), true);
  130. }
  131. /**
  132. * get sensitive fields name.
  133. *
  134. * @return array
  135. */
  136. protected function getSensitiveFieldsName()
  137. {
  138. return [
  139. 'contact_name',
  140. 'contact_id_number',
  141. 'mobile_phone',
  142. 'contact_email',
  143. 'id_card_name',
  144. 'id_card_number',
  145. 'id_card_address',
  146. 'id_doc_name',
  147. 'id_doc_number',
  148. 'id_doc_address',
  149. 'name',
  150. 'id_number',
  151. 'account_name',
  152. 'account_number',
  153. 'contact_id_card_number',
  154. 'contact_email',
  155. 'openid',
  156. 'ubo_id_doc_name',
  157. 'ubo_id_doc_number',
  158. 'ubo_id_doc_address',
  159. // 'bank_address_code',
  160. ];
  161. }
  162. /**
  163. * To id card, mobile phone number and other fields sensitive information encryption.
  164. *
  165. * @param string $string
  166. *
  167. * @return string
  168. */
  169. protected function encryptSensitiveInformation(string $string)
  170. {
  171. $encrypted = '';
  172. //自动分账
  173. if ($this->isService) {
  174. $pay_routine_public_id = $pay_routine_public_key = '';
  175. } else { //普通支付
  176. $pay_routine_public_id = $this->app['config']['payment']['pay_weixin_public_id'] ?? '';
  177. $pay_routine_public_key = $this->app['config']['payment']['pay_weixin_public_key'] ?? '';
  178. }
  179. if ($pay_routine_public_id && $pay_routine_public_key) {
  180. if (openssl_public_encrypt($string, $encrypted, $pay_routine_public_key, OPENSSL_PKCS1_OAEP_PADDING)) {
  181. //base64编码
  182. $sign = base64_encode($encrypted);
  183. } else {
  184. throw new InvalidConfigException('encrypt failed');
  185. }
  186. } else {
  187. $certificates = $this->app->certficates->setServiceStatus($this->isService)->get()['certificates'];
  188. if (null === $certificates) {
  189. throw new InvalidConfigException('config certificate connot be empty.');
  190. }
  191. if (openssl_public_encrypt($string, $encrypted, $certificates, OPENSSL_PKCS1_OAEP_PADDING)) {
  192. //base64编码
  193. $sign = base64_encode($encrypted);
  194. } else {
  195. throw new EncryptionException('Encryption of sensitive information failed');
  196. }
  197. }
  198. return $sign;
  199. }
  200. /**
  201. * processing parameters contain fields that require sensitive information encryption.
  202. *
  203. * @param array $params
  204. *
  205. * @return array
  206. */
  207. protected function processParams(array $params)
  208. {
  209. $sensitive_fields = $this->getSensitiveFieldsName();
  210. foreach ($params as $k => $v) {
  211. if (is_array($v)) {
  212. $params[$k] = $this->processParams($v);
  213. } else {
  214. if (in_array($k, $sensitive_fields, true)) {
  215. $params[$k] = $this->encryptSensitiveInformation($v);
  216. }
  217. }
  218. }
  219. return $params;
  220. }
  221. /**
  222. * @param string $url
  223. * @param string $method
  224. * @param string $body
  225. * @return string
  226. */
  227. protected function getAuthorization(string $url, string $method, string $body)
  228. {
  229. $nonce_str = uniqid();
  230. $timestamp = time();
  231. $message = $method . "\n" .
  232. $url . "\n" .
  233. $timestamp . "\n" .
  234. $nonce_str . "\n" .
  235. $body . "\n";
  236. openssl_sign($message, $raw_sign, $this->getPrivateKey(), 'sha256WithRSAEncryption');
  237. $sign = base64_encode($raw_sign);
  238. $schema = 'WECHATPAY2-SHA256-RSA2048 ';
  239. $token = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
  240. ($this->isService ? $this->app['config']['service_payment']['merchant_id'] : $this->app['config']['payment']['merchant_id']),
  241. $nonce_str,
  242. $timestamp,
  243. ($this->isService ? $this->app['config']['service_payment']['serial_no'] : $this->app['config']['payment']['serial_no']),
  244. $sign);
  245. return $schema . $token;
  246. }
  247. /**
  248. * 获取商户私钥
  249. * @return bool|resource
  250. */
  251. protected function getPrivateKey()
  252. {
  253. $key_path = $this->isService ? $this->app['config']['service_payment']['key_path'] : $this->app['config']['payment']['key_path'];
  254. if (!file_exists($key_path) || !is_file($key_path)) {
  255. //throw new \InvalidArgumentException("SSL certificate not found: {$key_path}");
  256. throw new \InvalidArgumentException("【请上传".($this->isService ? '分账':'微信')."支付书】SSL certificate not found");
  257. }
  258. return openssl_pkey_get_private(file_get_contents($key_path));
  259. }
  260. /**
  261. * decrypt ciphertext.
  262. *
  263. * @param array $encryptCertificate
  264. *
  265. * @return string
  266. */
  267. public function decrypt(array $encryptCertificate)
  268. {
  269. $ciphertext = base64_decode($encryptCertificate['ciphertext'], true);
  270. $associatedData = $encryptCertificate['associated_data'];
  271. $nonceStr = $encryptCertificate['nonce'];
  272. $aesKey = ($this->isService ? $this->app['config']['service_payment']['apiv3_key'] : $this->app['config']['payment']['apiv3_key']);
  273. if (strlen($aesKey) !== 32) {
  274. throw new InvalidArgumentException('The length of the key must be 32 bytes');
  275. }
  276. try {
  277. // ext-sodium (default installed on >= PHP 7.2)
  278. if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {
  279. return \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, $aesKey);
  280. }
  281. // ext-libsodium (need install libsodium-php 1.x via pecl)
  282. if (function_exists('\Sodium\crypto_aead_aes256gcm_is_available') && \Sodium\crypto_aead_aes256gcm_is_available()) {
  283. return \Sodium\crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, $aesKey);
  284. }
  285. // openssl (PHP >= 7.1 support AEAD)
  286. if (PHP_VERSION_ID >= 70100 && in_array('aes-256-gcm', \openssl_get_cipher_methods())) {
  287. $ctext = substr($ciphertext, 0, -self::AUTH_TAG_LENGTH_BYTE);
  288. $authTag = substr($ciphertext, -self::AUTH_TAG_LENGTH_BYTE);
  289. return \openssl_decrypt($ctext, 'aes-256-gcm', $aesKey, \OPENSSL_RAW_DATA, $nonceStr, $authTag, $associatedData);
  290. }
  291. } catch (\Exception $exception) {
  292. throw new InvalidArgumentException($exception->getMessage(), $exception->getCode());
  293. } catch (\SodiumException $exception) {
  294. throw new InvalidArgumentException($exception->getMessage(), $exception->getCode());
  295. }
  296. throw new InvalidArgumentException('AEAD_AES_256_GCM 需要 PHP 7.1 以上或者安装 libsodium-php');
  297. }
  298. }