Completed
Pull Request — master (#274)
by Carlos
03:29
created

Payment::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
/*
4
 * This file is part of the overtrue/wechat.
5
 *
6
 * (c) overtrue <[email protected]>
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
/**
13
 * Payment.php.
14
 *
15
 * @author    overtrue <[email protected]>
16
 * @copyright 2015 overtrue <[email protected]>
17
 *
18
 * @link      https://github.com/overtrue
19
 * @link      http://overtrue.me
20
 */
21
namespace EasyWeChat\Payment;
22
23
use EasyWeChat\Core\Exceptions\FaultException;
24
use EasyWeChat\Support\Url as UrlHelper;
25
use EasyWeChat\Support\XML;
26
use Symfony\Component\HttpFoundation\Response;
27
28
/**
29
 * Class Payment.
30
 */
31
class Payment
32
{
33
    /**
34
     * Scheme base path.
35
     */
36
    const SCHEME_PATH = 'weixin://wxpay/bizpayurl';
37
38
    /**
39
     * @var API
40
     */
41
    protected $api;
42
43
    /**
44
     * Merchant instance.
45
     *
46
     * @var \EasyWeChat\Payment\Merchant
47
     */
48
    protected $merchant;
49
50
    /**
51
     * Constructor.
52
     *
53
     * @param Merchant $merchant
54
     */
55 4
    public function __construct(Merchant $merchant)
56
    {
57 4
        $this->merchant = $merchant;
58 4
    }
59
60
    /**
61
     * Build payment scheme for product.
62
     *
63
     * @param string $productId
64
     *
65
     * @return string
66
     */
67 1
    public function scheme($productId)
68
    {
69
        $params = [
70 1
            'appid' => $this->merchant->app_id,
71 1
            'mch_id' => $this->merchant->merchant_id,
72 1
            'time_stamp' => time(),
73 1
            'nonce_str' => uniqid(),
74 1
            'product_id' => $productId,
75 1
        ];
76
77 1
        $params['sign'] = generate_sign($params, $this->merchant->key, 'md5');
78
79 1
        return self::SCHEME_PATH.'?'.http_build_query($params);
80
    }
81
82
    /**
83
     * Handle payment notify.
84
     *
85
     * @param callable $callback
86
     *
87
     * @return Response
88
     */
89 2
    public function handleNotify(callable $callback)
90
    {
91 2
        $notify = $this->getNotify();
92
93 2
        if (!$notify->isValid()) {
94 1
            throw new FaultException('Invalid request XML.', 400);
95
        }
96
97 1
        $notify = $notify->getNotify();
98 1
        $successful = $notify->get('result_code') === 'SUCCESS';
99
100 1
        $handleResult = call_user_func_array($callback, [$notify, $successful]);
101
102 1
        if (is_bool($handleResult) && $handleResult) {
103
            $response = [
104 1
                'return_code' => 'SUCCESS',
105 1
                'return_msg' => 'OK',
106 1
            ];
107 1
        } else {
108
            $response = [
109 1
                'return_code' => 'FAIL',
110 1
                'return_msg' => $handleResult,
111 1
            ];
112
        }
113
114 1
        return new Response(XML::build($response));
115
    }
116
117
    /**
118
     * Gernerate js config for payment.
119
     *
120
     * @param string $prepayId
121
     * @param bool   $json
122
     *
123
     * @return string|array
124
     */
125
    public function configForPayment($prepayId, $json = true)
126
    {
127
        $params = [
128
            'appId' => $this->merchant->app_id,
129
            'timeStamp' => strval(time()),
130
            'nonceStr' => uniqid(),
131
            'package' => "prepay_id=$prepayId",
132
            'signType' => 'MD5',
133
        ];
134
135
        $params['paySign'] = generate_sign($params, $this->merchant->key, 'md5');
136
137
        return $json ? json_encode($params) : $params;
138
    }
139
140
    /**
141
     * Generate js config for share user address.
142
     *
143
     * @param string $accessToken
144
     * @param bool   $json
145
     *
146
     * @return string|array
147
     */
148
    public function configForShareAddress($accessToken, $json = true)
149
    {
150
        $params = [
151
            'appId' => $this->merchant->app_id,
152
            'scope' => 'jsapi_address',
153
            'timeStamp' => strval(time()),
154
            'nonceStr' => uniqid(),
155
            'package' => "prepay_id=$prepayId",
0 ignored issues
show
Bug introduced by
The variable $prepayId does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
156
            'signType' => 'SHA1',
157
        ];
158
159
        $signParams = [
160
            'appid' => $params['appId'],
161
            'url' => UrlHelper::current(),
162
            'timestamp' => $params['timeStamp'],
163
            'noncestr' => $params['nonceStr'],
164
            'accesstoken' => $accessToken,
165
        ];
166
167
        $params['addrSign'] = generate_sign($signParams, $this->merchant->key, 'sha1');
168
169
        return $json ? json_encode($params) : $params;
170
    }
171
172
    /**
173
     * Merchant setter.
174
     *
175
     * @param Merchant $merchant
176
     */
177 1
    public function setMerchant(Merchant $merchant)
178
    {
179 1
        $this->merchant = $merchant;
180 1
    }
181
182
    /**
183
     * Merchant getter.
184
     *
185
     * @return Merchant
186
     */
187 1
    public function getMerchant()
188
    {
189 1
        return $this->merchant;
190
    }
191
192
    /**
193
     * Return Notify instance.
194
     *
195
     * @return \EasyWeChat\Payment\Notify
196
     */
197
    public function getNotify()
198
    {
199
        return new Notify($this->merchant);
200
    }
201
202
    /**
203
     * API setter.
204
     *
205
     * @param API $api
206
     */
207 1
    public function setAPI(API $api)
208
    {
209 1
        $this->api = $api;
210 1
    }
211
212
    /**
213
     * Return API instance.
214
     *
215
     * @return API
216
     */
217 1
    public function getAPI()
218
    {
219 1
        return $this->api ?: $this->api = new API($this->getMerchant());
220
    }
221
222
    /**
223
     * Magic call.
224
     *
225
     * @param string $method
226
     * @param array  $args
227
     *
228
     * @return mixed
229
     *
230
     * @codeCoverageIgnore
231
     */
232
    public function __call($method, $args)
233
    {
234
        if (is_callable([$this->getAPI(), $method])) {
235
            return call_user_func_array([$this->api, $method], $args);
236
        }
237
    }
238
}
239