Passed
Pull Request — master (#1002)
by
unknown
02:31
created

AddPayloadSignPlugin   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 21
c 1
b 0
f 0
dl 0
loc 49
rs 10
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A assembly() 0 22 3
A getSignature() 0 7 1
A getPrivateKey() 0 9 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yansongda\Pay\Plugin\Epay;
6
7
use Closure;
8
use Yansongda\Artful\Contract\PluginInterface;
9
use Yansongda\Artful\Exception\ContainerException;
10
use Yansongda\Artful\Exception\InvalidConfigException;
11
use Yansongda\Artful\Exception\InvalidParamsException;
12
use Yansongda\Artful\Exception\ServiceNotFoundException;
13
use Yansongda\Artful\Logger;
14
use Yansongda\Artful\Rocket;
15
use Yansongda\Pay\Exception\Exception;
16
use Yansongda\Supports\Collection;
17
18
use function Yansongda\Pay\get_provider_config;
19
20
class AddPayloadSignPlugin implements PluginInterface
21
{
22
    /**
23
     * @throws ServiceNotFoundException
24
     * @throws InvalidParamsException
25
     * @throws ContainerException|InvalidConfigException
26
     */
27
    public function assembly(Rocket $rocket, Closure $next): Rocket
28
    {
29
        Logger::info('[Epay][AddPayloadSignPlugin] 插件开始装载', ['rocket' => $rocket]);
30
31
        $params = $rocket->getParams();
32
        $config = get_provider_config('epay', $params);
33
        $payload = $rocket->getPayload();
34
35
        if (empty($payload) || $payload->isEmpty()) {
36
            throw new InvalidParamsException(Exception::PARAMS_NECESSARY_PARAMS_MISSING, '参数异常: epay支付必要参数缺失。可能插件用错顺序,应该先使用 `业务插件`');
37
        }
38
39
        $pkey = $this->getPrivateKey($config);
40
        $sign = $this->getSignature($pkey, $payload);
41
        $rocket->mergePayload([
42
            'signType' => 'RSA',
43
            'sign' => $sign,
44
        ]);
45
46
        Logger::info('[Epay][AddPayloadSignPlugin] 插件装载完毕', ['rocket' => $rocket]);
47
48
        return $next($rocket);
49
    }
50
51
    protected function getSignature(string $pkey, Collection $payload): string
52
    {
53
        $content = $payload->sortKeys()->toString();
54
55
        openssl_sign($content, $signature, $pkey);
56
57
        return base64_encode($signature);
58
    }
59
60
    protected function getPrivateKey(array $config): string
61
    {
62
        $privateCertPath = $config['mch_secret_cert_path'] ?? '';
63
64
        if (!$privateCertPath) {
65
            throw new InvalidConfigException(Exception::CONFIG_EPAY_INVALID, '参数异常: epay支付配置文件中未找到 `mch_secret_cert_path` 配置项。可能插件用错顺序,应该先使用 `StartPlugin`');
66
        }
67
68
        return file_get_contents($privateCertPath);
69
    }
70
}
71