Passed
Pull Request — master (#909)
by Songda
02:12
created

PayPlugin   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
eloc 22
dl 0
loc 48
rs 10
c 1
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A normal() 0 5 1
A assembly() 0 24 2
A service() 0 8 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yansongda\Pay\Plugin\Wechat\Pay\Native;
6
7
use Closure;
8
use Yansongda\Pay\Contract\PluginInterface;
9
use Yansongda\Pay\Exception\ContainerException;
10
use Yansongda\Pay\Exception\ServiceNotFoundException;
11
use Yansongda\Pay\Logger;
12
use Yansongda\Pay\Pay;
13
use Yansongda\Pay\Rocket;
14
15
use function Yansongda\Pay\get_wechat_config;
16
use function Yansongda\Pay\get_wechat_config_type_key;
17
18
/**
19
 * @see https://pay.weixin.qq.com/docs/merchant/apis/native-payment/direct-jsons/native-prepay.html
20
 * @see https://pay.weixin.qq.com/docs/partner/apis/partner-native-payment/partner-jsons/partner-native-prepay.html
21
 */
22
class PayPlugin implements PluginInterface
23
{
24
    /**
25
     * @throws ContainerException
26
     * @throws ServiceNotFoundException
27
     */
28
    public function assembly(Rocket $rocket, Closure $next): Rocket
29
    {
30
        Logger::debug('[Wechat][Pay][Native][PayPlugin] 插件开始装载', ['rocket' => $rocket]);
31
32
        $params = $rocket->getParams();
33
        $config = get_wechat_config($params);
34
35
        if (Pay::MODE_SERVICE === $config['mode']) {
36
            $payload = $this->service($params, $config);
37
        }
38
39
        $rocket->mergePayload(array_merge(
40
            [
41
                '_method' => 'POST',
42
                '_url' => 'v3/pay/transactions/native',
43
                '_service_url' => 'v3/pay/partner/transactions/native',
44
                'notify_url' => $config['notify_url'] ?? '',
45
            ],
46
            $payload ?? $this->normal($params, $config)
47
        ));
48
49
        Logger::info('[Wechat][Pay][Native][PayPlugin] 插件装载完毕', ['rocket' => $rocket]);
50
51
        return $next($rocket);
52
    }
53
54
    protected function normal(array $params, array $config): array
55
    {
56
        return [
57
            'appid' => $config[get_wechat_config_type_key($params)] ?? '',
58
            'mchid' => $config['mch_id'] ?? '',
59
        ];
60
    }
61
62
    protected function service(array $params, array $config): array
63
    {
64
        $configKey = get_wechat_config_type_key($params);
65
66
        return [
67
            'sp_appid' => $config[$configKey] ?? '',
68
            'sp_mchid' => $config['mch_id'] ?? '',
69
            'sub_mchid' => $config['sub_mch_id'] ?? '',
70
        ];
71
    }
72
}
73