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