GetUnipayCerts.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. declare(strict_types=1);
  3. namespace Yansongda\Pay\Traits;
  4. use Yansongda\Pay\Contract\ConfigInterface;
  5. use Yansongda\Pay\Exception\ContainerException;
  6. use Yansongda\Pay\Exception\Exception;
  7. use Yansongda\Pay\Exception\InvalidConfigException;
  8. use Yansongda\Pay\Exception\ServiceNotFoundException;
  9. use Yansongda\Pay\Pay;
  10. trait GetUnipayCerts
  11. {
  12. /**
  13. * @throws ContainerException
  14. * @throws InvalidConfigException
  15. * @throws ServiceNotFoundException
  16. */
  17. public function getCertId(string $tenant, array $config): string
  18. {
  19. if (!empty($config['certs']['cert_id'])) {
  20. return $config['certs']['cert_id'];
  21. }
  22. $certs = $this->getCerts($config);
  23. $ssl = openssl_x509_parse($certs['cert'] ?? '');
  24. if (false === $ssl) {
  25. throw new InvalidConfigException(Exception::UNIPAY_CONFIG_ERROR, 'Parse `mch_cert_path` Error');
  26. }
  27. $certs['cert_id'] = $ssl['serialNumber'] ?? '';
  28. Pay::get(ConfigInterface::class)->set('unipay.'.$tenant.'.certs', $certs);
  29. return $certs['cert_id'];
  30. }
  31. /**
  32. * @return array ['cert' => 公钥, 'pkey' => 私钥, 'extracerts' => array]
  33. *
  34. * @throws InvalidConfigException
  35. */
  36. protected function getCerts(array $config): array
  37. {
  38. $path = $config['mch_cert_path'] ?? null;
  39. $password = $config['mch_cert_password'] ?? null;
  40. if (is_null($path) || is_null($password)) {
  41. throw new InvalidConfigException(Exception::UNIPAY_CONFIG_ERROR, 'Missing Unipay Config -- [mch_cert_path] or [mch_cert_password]');
  42. }
  43. if (false === openssl_pkcs12_read(file_get_contents($path), $certs, $password)) {
  44. throw new InvalidConfigException(Exception::UNIPAY_CONFIG_ERROR, 'Read `mch_cert_path` Error');
  45. }
  46. return $certs;
  47. }
  48. }