Completed
Push — master ( 13d232...963395 )
by Carlos
07:14
created

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