Functions.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. <?php
  2. declare(strict_types=1);
  3. namespace Yansongda\Pay;
  4. use Psr\Http\Message\MessageInterface;
  5. use Psr\Http\Message\ResponseInterface;
  6. use Psr\Http\Message\ServerRequestInterface;
  7. use Yansongda\Pay\Contract\ConfigInterface;
  8. use Yansongda\Pay\Direction\NoHttpRequestDirection;
  9. use Yansongda\Pay\Exception\ContainerException;
  10. use Yansongda\Pay\Exception\Exception;
  11. use Yansongda\Pay\Exception\InvalidConfigException;
  12. use Yansongda\Pay\Exception\InvalidParamsException;
  13. use Yansongda\Pay\Exception\InvalidResponseException;
  14. use Yansongda\Pay\Exception\ServiceNotFoundException;
  15. use Yansongda\Pay\Plugin\ParserPlugin;
  16. use Yansongda\Pay\Plugin\Wechat\PreparePlugin;
  17. use Yansongda\Pay\Plugin\Wechat\RadarSignPlugin;
  18. use Yansongda\Pay\Plugin\Wechat\WechatPublicCertsPlugin;
  19. use Yansongda\Pay\Provider\Wechat;
  20. use Yansongda\Supports\Str;
  21. if (!function_exists('should_do_http_request')) {
  22. function should_do_http_request(string $direction): bool
  23. {
  24. return NoHttpRequestDirection::class !== $direction
  25. && !in_array(NoHttpRequestDirection::class, class_parents($direction));
  26. }
  27. }
  28. if (!function_exists('get_tenant')) {
  29. function get_tenant(array $params = []): string
  30. {
  31. return strval($params['_config'] ?? 'default');
  32. }
  33. }
  34. if (!function_exists('get_alipay_config')) {
  35. /**
  36. * @throws ContainerException
  37. * @throws ServiceNotFoundException
  38. */
  39. function get_alipay_config(array $params = []): array
  40. {
  41. $alipay = Pay::get(ConfigInterface::class)->get('alipay');
  42. return $alipay[get_tenant($params)] ?? [];
  43. }
  44. }
  45. if (!function_exists('get_public_cert')) {
  46. function get_public_cert(string $key): string
  47. {
  48. return Str::endsWith($key, ['.cer', '.crt', '.pem']) ? file_get_contents($key) : $key;
  49. }
  50. }
  51. if (!function_exists('get_private_cert')) {
  52. function get_private_cert(string $key): string
  53. {
  54. if (Str::endsWith($key, ['.crt', '.pem'])) {
  55. return file_get_contents($key);
  56. }
  57. return "-----BEGIN RSA PRIVATE KEY-----\n".
  58. wordwrap($key, 64, "\n", true).
  59. "\n-----END RSA PRIVATE KEY-----";
  60. }
  61. }
  62. if (!function_exists('verify_alipay_sign')) {
  63. /**
  64. * @throws ContainerException
  65. * @throws InvalidConfigException
  66. * @throws ServiceNotFoundException
  67. * @throws InvalidResponseException
  68. */
  69. function verify_alipay_sign(array $params, string $contents, string $sign): void
  70. {
  71. $public = get_alipay_config($params)['alipay_public_cert_path'] ?? null;
  72. if (empty($public)) {
  73. throw new InvalidConfigException(Exception::ALIPAY_CONFIG_ERROR, 'Missing Alipay Config -- [alipay_public_cert_path]');
  74. }
  75. // 优化publickey判断
  76. if (!Str::endsWith($public, ['.cer', '.crt', '.pem']) && stripos($public, '-----BEGIN PUBLIC KEY-----') === false) {
  77. $public = "-----BEGIN PUBLIC KEY-----\n".
  78. wordwrap($public, 64, "\n", true).
  79. "\n-----END PUBLIC KEY-----";
  80. }
  81. $result = 1 === openssl_verify(
  82. $contents,
  83. base64_decode($sign),
  84. get_public_cert($public),
  85. OPENSSL_ALGO_SHA256
  86. );
  87. if (!$result) {
  88. throw new InvalidResponseException(Exception::INVALID_RESPONSE_SIGN, 'Verify Alipay Response Sign Failed', func_get_args());
  89. }
  90. }
  91. }
  92. if (!function_exists('get_wechat_config')) {
  93. /**
  94. * @throws ContainerException
  95. * @throws ServiceNotFoundException
  96. */
  97. function get_wechat_config(array $params): array
  98. {
  99. $wechat = Pay::get(ConfigInterface::class)->get('wechat');
  100. return $wechat[get_tenant($params)] ?? [];
  101. }
  102. }
  103. if (!function_exists('get_wechat_base_uri')) {
  104. /**
  105. * @throws ContainerException
  106. * @throws ServiceNotFoundException
  107. */
  108. function get_wechat_base_uri(array $params): string
  109. {
  110. $config = get_wechat_config($params);
  111. return Wechat::URL[$config['mode'] ?? Pay::MODE_NORMAL];
  112. }
  113. }
  114. if (!function_exists('get_wechat_sign')) {
  115. /**
  116. * @throws ContainerException
  117. * @throws ServiceNotFoundException
  118. * @throws InvalidConfigException
  119. */
  120. function get_wechat_sign(array $params, string $contents): string
  121. {
  122. $privateKey = get_wechat_config($params)['mch_secret_cert'] ?? null;
  123. if (empty($privateKey)) {
  124. throw new InvalidConfigException(Exception::WECHAT_CONFIG_ERROR, 'Missing Wechat Config -- [mch_secret_cert]');
  125. }
  126. $privateKey = get_private_cert($privateKey);
  127. openssl_sign($contents, $sign, $privateKey, 'sha256WithRSAEncryption');
  128. return base64_encode($sign);
  129. }
  130. }
  131. if (!function_exists('get_wechat_sign_v2')) {
  132. /**
  133. * @throws ContainerException
  134. * @throws ServiceNotFoundException
  135. * @throws InvalidConfigException
  136. */
  137. function get_wechat_sign_v2(array $params, array $payload, bool $upper = true): string
  138. {
  139. $key = get_wechat_config($params)['mch_secret_key_v2'] ?? null;
  140. if (empty($key)) {
  141. throw new InvalidConfigException(Exception::WECHAT_CONFIG_ERROR, 'Missing Wechat Config -- [mch_secret_key_v2]');
  142. }
  143. ksort($payload);
  144. $buff = '';
  145. foreach ($payload as $k => $v) {
  146. $buff .= ('sign' != $k && '' != $v && !is_array($v)) ? $k.'='.$v.'&' : '';
  147. }
  148. $sign = md5($buff.'key='.$key);
  149. return $upper ? strtoupper($sign) : $sign;
  150. }
  151. }
  152. if (!function_exists('verify_wechat_sign')) {
  153. /**
  154. * @param ResponseInterface|ServerRequestInterface $message
  155. *
  156. * @throws ContainerException
  157. * @throws InvalidConfigException
  158. * @throws InvalidResponseException
  159. * @throws ServiceNotFoundException
  160. * @throws InvalidParamsException
  161. */
  162. function verify_wechat_sign(MessageInterface $message, array $params): void
  163. {
  164. if ($message instanceof ServerRequestInterface && 'localhost' === $message->getUri()->getHost()) {
  165. return;
  166. }
  167. $wechatSerial = $message->getHeaderLine('Wechatpay-Serial');
  168. $timestamp = $message->getHeaderLine('Wechatpay-Timestamp');
  169. $random = $message->getHeaderLine('Wechatpay-Nonce');
  170. $sign = $message->getHeaderLine('Wechatpay-Signature');
  171. $body = (string) $message->getBody();
  172. $content = $timestamp."\n".$random."\n".$body."\n";
  173. $public = get_wechat_config($params)['wechat_public_cert_path'][$wechatSerial] ?? null;
  174. if (empty($sign)) {
  175. throw new InvalidResponseException(Exception::INVALID_RESPONSE_SIGN, '', ['headers' => $message->getHeaders(), 'body' => $body]);
  176. }
  177. $public = get_public_cert(
  178. empty($public) ? reload_wechat_public_certs($params, $wechatSerial) : $public
  179. );
  180. $result = 1 === openssl_verify(
  181. $content,
  182. base64_decode($sign),
  183. $public,
  184. 'sha256WithRSAEncryption'
  185. );
  186. if (!$result) {
  187. throw new InvalidResponseException(Exception::INVALID_RESPONSE_SIGN, '', ['headers' => $message->getHeaders(), 'body' => $body]);
  188. }
  189. }
  190. }
  191. if (!function_exists('encrypt_wechat_contents')) {
  192. function encrypt_wechat_contents(string $contents, string $publicKey): ?string
  193. {
  194. if (openssl_public_encrypt($contents, $encrypted, get_public_cert($publicKey), OPENSSL_PKCS1_OAEP_PADDING)) {
  195. return base64_encode($encrypted);
  196. }
  197. return null;
  198. }
  199. }
  200. if (!function_exists('reload_wechat_public_certs')) {
  201. /**
  202. * @throws ContainerException
  203. * @throws InvalidConfigException
  204. * @throws ServiceNotFoundException
  205. * @throws InvalidParamsException
  206. * @throws InvalidResponseException
  207. */
  208. function reload_wechat_public_certs(array $params, ?string $serialNo = null): string
  209. {
  210. $data = Pay::wechat()->pay(
  211. [PreparePlugin::class, WechatPublicCertsPlugin::class, RadarSignPlugin::class, ParserPlugin::class],
  212. $params
  213. )->get('data', []);
  214. foreach ($data as $item) {
  215. $certs[$item['serial_no']] = decrypt_wechat_resource($item['encrypt_certificate'], $params)['ciphertext'] ?? '';
  216. }
  217. $wechatConfig = get_wechat_config($params);
  218. Pay::get(ConfigInterface::class)->set(
  219. 'wechat.'.get_tenant($params).'.wechat_public_cert_path',
  220. ((array) ($wechatConfig['wechat_public_cert_path'] ?? [])) + ($certs ?? [])
  221. );
  222. if (!is_null($serialNo) && empty($certs[$serialNo])) {
  223. throw new InvalidConfigException(Exception::WECHAT_CONFIG_ERROR, 'Get Wechat Public Cert Error');
  224. }
  225. return $certs[$serialNo] ?? '';
  226. }
  227. }
  228. if (!function_exists('get_wechat_public_certs')) {
  229. /**
  230. * @throws ContainerException
  231. * @throws InvalidConfigException
  232. * @throws ServiceNotFoundException
  233. * @throws InvalidParamsException
  234. * @throws InvalidResponseException
  235. */
  236. function get_wechat_public_certs(array $params = [], ?string $path = null): void
  237. {
  238. reload_wechat_public_certs($params);
  239. $config = get_wechat_config($params);
  240. if (empty($path)) {
  241. var_dump($config['wechat_public_cert_path']);
  242. return;
  243. }
  244. foreach ($config['wechat_public_cert_path'] as $serialNo => $cert) {
  245. file_put_contents($path.'/'.$serialNo.'.crt', $cert);
  246. }
  247. }
  248. }
  249. if (!function_exists('decrypt_wechat_resource')) {
  250. /**
  251. * @throws ContainerException
  252. * @throws InvalidConfigException
  253. * @throws InvalidResponseException
  254. * @throws ServiceNotFoundException
  255. */
  256. function decrypt_wechat_resource(array $resource, array $params): array
  257. {
  258. $ciphertext = base64_decode($resource['ciphertext'] ?? '');
  259. $secret = get_wechat_config($params)['mch_secret_key'] ?? null;
  260. if (strlen($ciphertext) <= Wechat::AUTH_TAG_LENGTH_BYTE) {
  261. throw new InvalidResponseException(Exception::INVALID_CIPHERTEXT_PARAMS);
  262. }
  263. if (is_null($secret) || Wechat::MCH_SECRET_KEY_LENGTH_BYTE != strlen($secret)) {
  264. throw new InvalidConfigException(Exception::WECHAT_CONFIG_ERROR, 'Missing Wechat Config -- [mch_secret_key]');
  265. }
  266. switch ($resource['algorithm'] ?? '') {
  267. case 'AEAD_AES_256_GCM':
  268. $resource['ciphertext'] = decrypt_wechat_resource_aes_256_gcm($ciphertext, $secret, $resource['nonce'] ?? '', $resource['associated_data'] ?? '');
  269. break;
  270. default:
  271. throw new InvalidResponseException(Exception::INVALID_REQUEST_ENCRYPTED_METHOD);
  272. }
  273. return $resource;
  274. }
  275. }
  276. if (!function_exists('decrypt_wechat_resource_aes_256_gcm')) {
  277. /**
  278. * @return array|string
  279. *
  280. * @throws InvalidResponseException
  281. */
  282. function decrypt_wechat_resource_aes_256_gcm(string $ciphertext, string $secret, string $nonce, string $associatedData)
  283. {
  284. $decrypted = openssl_decrypt(
  285. substr($ciphertext, 0, -Wechat::AUTH_TAG_LENGTH_BYTE),
  286. 'aes-256-gcm',
  287. $secret,
  288. OPENSSL_RAW_DATA,
  289. $nonce,
  290. substr($ciphertext, -Wechat::AUTH_TAG_LENGTH_BYTE),
  291. $associatedData
  292. );
  293. if ('certificate' !== $associatedData) {
  294. $decrypted = json_decode(strval($decrypted), true);
  295. if (JSON_ERROR_NONE !== json_last_error()) {
  296. throw new InvalidResponseException(Exception::INVALID_REQUEST_ENCRYPTED_DATA);
  297. }
  298. }
  299. return $decrypted;
  300. }
  301. }
  302. if (!function_exists('get_unipay_config')) {
  303. /**
  304. * @throws ContainerException
  305. * @throws ServiceNotFoundException
  306. */
  307. function get_unipay_config(array $params): array
  308. {
  309. $unipay = Pay::get(ConfigInterface::class)->get('unipay');
  310. return $unipay[get_tenant($params)] ?? [];
  311. }
  312. }
  313. if (!function_exists('verify_unipay_sign')) {
  314. /**
  315. * @throws ContainerException
  316. * @throws InvalidConfigException
  317. * @throws InvalidResponseException
  318. * @throws ServiceNotFoundException
  319. */
  320. function verify_unipay_sign(array $params, string $contents, string $sign): void
  321. {
  322. if (empty($params['signPubKeyCert'])
  323. && empty($public = get_unipay_config($params)['unipay_public_cert_path'] ?? null)) {
  324. throw new InvalidConfigException(Exception::UNIPAY_CONFIG_ERROR, 'Missing Unipay Config -- [unipay_public_cert_path]');
  325. }
  326. $result = 1 === openssl_verify(
  327. hash('sha256', $contents),
  328. base64_decode($sign),
  329. get_public_cert($params['signPubKeyCert'] ?? $public ?? ''),
  330. 'sha256'
  331. );
  332. if (!$result) {
  333. throw new InvalidResponseException(Exception::INVALID_RESPONSE_SIGN, 'Verify Unipay Response Sign Failed', func_get_args());
  334. }
  335. }
  336. }