Passed
Pull Request — master (#662)
by Songda
01:53
created

GetUnipayCerts::getCertId()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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