AppGateway::pay()   A
last analyzed

Complexity

Conditions 4
Paths 8

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 9.552
c 0
b 0
f 0
cc 4
nc 8
nop 2
1
<?php
2
3
namespace Yansongda\Pay\Gateways\Wechat;
4
5
use Exception;
6
use Symfony\Component\HttpFoundation\JsonResponse;
7
use Symfony\Component\HttpFoundation\Response;
8
use Yansongda\Pay\Events;
9
use Yansongda\Pay\Exceptions\GatewayException;
10
use Yansongda\Pay\Exceptions\InvalidArgumentException;
11
use Yansongda\Pay\Exceptions\InvalidSignException;
12
use Yansongda\Pay\Gateways\Wechat;
13
use Yansongda\Supports\Str;
14
15
class AppGateway extends Gateway
16
{
17
    /**
18
     * Pay an order.
19
     *
20
     * @author yansongda <[email protected]>
21
     *
22
     * @param string $endpoint
23
     * @param array  $payload
24
     *
25
     * @throws GatewayException
26
     * @throws InvalidArgumentException
27
     * @throws InvalidSignException
28
     * @throws Exception
29
     *
30
     * @return Response
31
     */
32
    public function pay($endpoint, array $payload): Response
33
    {
34
        $payload['appid'] = Support::getInstance()->appid;
35
        $payload['trade_type'] = $this->getTradeType();
36
37
        if (Wechat::MODE_SERVICE === $this->mode) {
38
            $payload['sub_appid'] = Support::getInstance()->sub_appid;
39
        }
40
41
        $pay_request = [
42
            'appid' => Wechat::MODE_SERVICE === $this->mode ? $payload['sub_appid'] : $payload['appid'],
43
            'partnerid' => Wechat::MODE_SERVICE === $this->mode ? $payload['sub_mch_id'] : $payload['mch_id'],
44
            'prepayid' => $this->preOrder($payload)->get('prepay_id'),
45
            'timestamp' => strval(time()),
46
            'noncestr' => Str::random(),
47
            'package' => 'Sign=WXPay',
48
        ];
49
        $pay_request['sign'] = Support::generateSign($pay_request);
50
51
        Events::dispatch(new Events\PayStarted('Wechat', 'App', $endpoint, $pay_request));
52
53
        return JsonResponse::create($pay_request);
54
    }
55
56
    /**
57
     * Get trade type config.
58
     *
59
     * @author yansongda <[email protected]>
60
     *
61
     * @return string
62
     */
63
    protected function getTradeType(): string
64
    {
65
        return 'APP';
66
    }
67
}
68