Passed
Push — master ( 96d02d...d08d15 )
by Songda
02:13 queued 10s
created

CallbackPlugin::getSignContent()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yansongda\Pay\Plugin\Alipay;
6
7
use Closure;
8
use Yansongda\Pay\Contract\PluginInterface;
9
use Yansongda\Pay\Exception\InvalidResponseException;
10
use Yansongda\Pay\Parser\NoHttpRequestParser;
11
use Yansongda\Pay\Rocket;
12
use Yansongda\Supports\Collection;
13
14
class CallbackPlugin implements PluginInterface
15
{
16
    /**
17
     * @throws \Yansongda\Pay\Exception\ContainerDependencyException
18
     * @throws \Yansongda\Pay\Exception\ContainerException
19
     * @throws \Yansongda\Pay\Exception\InvalidConfigException
20
     * @throws \Yansongda\Pay\Exception\ServiceNotFoundException
21
     * @throws \Yansongda\Pay\Exception\InvalidResponseException
22
     */
23
    public function assembly(Rocket $rocket, Closure $next): Rocket
24
    {
25
        $this->filterPayload($rocket);
26
27
        if (!($rocket->getParams()['sign'] ?? false)) {
28
            throw new InvalidResponseException(InvalidResponseException::INVALID_RESPONSE_SIGN, '', $rocket->getParams());
29
        }
30
31
        if (!verify_alipay_response(
32
                $rocket->getParams(),
33
                $this->getSignContent($rocket->getPayload()),
34
                base64_decode($rocket->getParams()['sign']))
35
        ) {
36
            throw new InvalidResponseException(InvalidResponseException::INVALID_RESPONSE_SIGN, '', $rocket->getParams());
37
        }
38
39
        $rocket->setDirection(NoHttpRequestParser::class)
40
            ->setDestination($rocket->getPayload());
41
42
        return $next($rocket);
43
    }
44
45
    protected function filterPayload(Rocket $rocket): void
46
    {
47
        $payload = (new Collection($rocket->getParams()))->filter(function ($v, $k) {
48
            return '' !== $v && !is_null($v) && 'sign' != $k && 'sign_type' != $k;
49
        });
50
51
        $rocket->setPayload($payload);
52
    }
53
54
    protected function getSignContent(Collection $payload): string
55
    {
56
        return urldecode($payload->sortKeys()->toString());
57
    }
58
}
59