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

ReturnPlugin::assembly()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 28
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
dl 0
loc 28
rs 9.7666
c 1
b 0
f 0
cc 3
nc 3
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yansongda\Pay\Plugin\Wechat\Extend\ProfitSharing;
6
7
use Closure;
8
use Yansongda\Pay\Contract\PluginInterface;
9
use Yansongda\Pay\Exception\ContainerException;
10
use Yansongda\Pay\Exception\Exception;
11
use Yansongda\Pay\Exception\InvalidParamsException;
12
use Yansongda\Pay\Exception\ServiceNotFoundException;
13
use Yansongda\Pay\Logger;
14
use Yansongda\Pay\Pay;
15
use Yansongda\Pay\Rocket;
16
17
use function Yansongda\Pay\get_wechat_config;
18
19
/**
20
 * @see https://pay.weixin.qq.com/docs/merchant/apis/profit-sharing/return-orders/create-return-order.html
21
 * @see https://pay.weixin.qq.com/docs/partner/apis/profit-sharing/return-orders/create-return-order.html
22
 */
23
class ReturnPlugin implements PluginInterface
24
{
25
    /**
26
     * @throws ContainerException
27
     * @throws InvalidParamsException
28
     * @throws ServiceNotFoundException
29
     */
30
    public function assembly(Rocket $rocket, Closure $next): Rocket
31
    {
32
        Logger::debug('[Wechat][Extend][ProfitSharing][ReturnPlugin] 插件开始装载', ['rocket' => $rocket]);
33
34
        $params = $rocket->getParams();
35
        $config = get_wechat_config($params);
36
        $payload = $rocket->getPayload();
37
38
        if (is_null($payload)) {
39
            throw new InvalidParamsException(Exception::PARAMS_NECESSARY_PARAMS_MISSING, '参数异常: 缺少分账参数');
40
        }
41
42
        if (Pay::MODE_SERVICE === ($config['mode'] ?? Pay::MODE_NORMAL)) {
43
            $data = $this->service($config);
44
        }
45
46
        $rocket->mergePayload(array_merge(
47
            [
48
                '_method' => 'POST',
49
                '_url' => 'v3/profitsharing/return-orders',
50
                '_service_url' => 'v3/profitsharing/return-orders',
51
            ],
52
            $data ?? $this->normal($config),
53
        ));
54
55
        Logger::info('[Wechat][Extend][ProfitSharing][ReturnPlugin] 插件装载完毕', ['rocket' => $rocket]);
56
57
        return $next($rocket);
58
    }
59
60
    protected function normal(array $config): array
61
    {
62
        return [
63
            'return_mchid' => $config['mch_id'],
64
        ];
65
    }
66
67
    protected function service(array $config): array
68
    {
69
        return [
70
            'sub_mchid' => $config['sub_mch_id'],
71
            'return_mchid' => $config['mch_id'],
72
        ];
73
    }
74
}
75