ReturnPlugin::assembly()   A
last analyzed

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