Completed
Push — master ( c24327...0abb5a )
by Raza
02:19
created

PayPalRequest::refundTransaction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
c 2
b 0
f 0
nc 1
nop 1
dl 0
loc 8
rs 9.4285
1
<?php
2
3
namespace Srmklive\PayPal\Traits;
4
5
use GuzzleHttp\Client as HttpClient;
6
use GuzzleHttp\Exception\BadResponseException as HttpBadResponseException;
7
use GuzzleHttp\Exception\ClientException as HttpClientException;
8
use GuzzleHttp\Exception\ServerException as HttpServerException;
9
use Illuminate\Support\Collection;
10
11
trait PayPalRequest
12
{
13
    /**
14
     * @var HttpClient
15
     */
16
    private $client;
17
18
    /**
19
     * @var \Illuminate\Support\Collection
20
     */
21
    protected $post;
22
23
    /**
24
     * @var array
25
     */
26
    private $config;
27
28
    /**
29
     * @var string
30
     */
31
    private $currency;
32
33
    /**
34
     * @var array
35
     */
36
    private $options;
37
38
    /**
39
     * @var string
40
     */
41
    private $paymentAction;
42
43
    /**
44
     * @var string
45
     */
46
    private $locale;
47
48
    /**
49
     * @var string
50
     */
51
    private $notifyUrl;
52
53
    /**
54
     * Function To Set PayPal API Configuration.
55
     *
56
     * @param array $config
57
     *
58
     * @return void
59
     */
60
    private function setConfig(array $config = [])
61
    {
62
        // Setting Http Client
63
        $this->client = $this->setClient();
64
65
        // Set Api Credentials
66
        if (function_exists('config')) {
67
            $this->setApiCredentials(
68
                config('paypal')
69
            );
70
        } elseif (!empty($config)) {
71
            $this->setApiCredentials($config);
72
        }
73
74
        $this->setRequestData();
75
    }
76
77
    /**
78
     * Function to initialize Http Client.
79
     *
80
     * @return HttpClient
81
     */
82
    protected function setClient()
83
    {
84
        return new HttpClient([
85
            'curl' => [
86
                CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1_2,
87
            ],
88
        ]);
89
    }
90
91
    /**
92
     * Set PayPal API Credentials.
93
     *
94
     * @param array  $credentials
95
     * @param string $mode
96
     *
97
     * @throws \Exception
98
     *
99
     * @return void
100
     */
101
    public function setApiCredentials($credentials, $mode = '')
102
    {
103
        // Setting Default PayPal Mode If not set
104
        if (empty($credentials['mode']) ||
105
            (!in_array($credentials['mode'], ['sandbox', 'live']))
106
        ) {
107
            $credentials['mode'] = 'live';
108
        }
109
110
        // Setting default mode.
111
        if (empty($mode)) {
112
            $mode = $credentials['mode'];
113
        }
114
115
        // Setting PayPal API Credentials
116
        foreach ($credentials[$mode] as $key => $value) {
117
            $this->config[$key] = $value;
118
        }
119
120
        // Setup PayPal API Signature value to use.
121
        if (!empty($this->config['secret'])) {
122
            $this->config['signature'] = $this->config['secret'];
123
        } else {
124
            $this->config['signature'] = file_get_contents($this->config['certificate']);
125
        }
126
127
        if ($this instanceof \Srmklive\PayPal\Services\AdaptivePayments) {
128
            $this->setAdaptivePaymentsOptions($mode);
129
        } elseif ($this instanceof \Srmklive\PayPal\Services\ExpressCheckout) {
130
            $this->setExpressCheckoutOptions($credentials, $mode);
131
        } else {
132
            throw new \Exception('Invalid api credentials provided for PayPal!. Please provide the right api credentials.');
133
        }
134
135
        // Set default currency.
136
        $this->setCurrency($credentials['currency']);
137
138
        // Set default payment action.
139
        $this->paymentAction = !empty($this->config['payment_action']) ?
140
            $this->config['payment_action'] : 'Sale';
141
142
        // Set default locale.
143
        $this->locale = !empty($this->config['locale']) ?
144
            $this->config['locale'] : 'en_US';
145
146
        // Set PayPal IPN Notification URL
147
        $this->notifyUrl = $credentials['notify_url'];
148
    }
149
150
    /**
151
     * Setup request data to be sent to PayPal.
152
     *
153
     * @param array $data
154
     *
155
     * @return \Illuminate\Support\Collection
156
     */
157
    protected function setRequestData(array $data = [])
158
    {
159
        if (($this->post instanceof Collection) && ($this->post->isNotEmpty())) {
160
            unset($this->post);
161
        }
162
163
        $this->post = new Collection($data);
164
165
        return $this->post;
166
    }
167
168
    /**
169
     * Set other/override PayPal API parameters.
170
     *
171
     * @param array $options
172
     *
173
     * @return $this
174
     */
175
    public function addOptions(array $options)
176
    {
177
        $this->options = $options;
178
179
        return $this;
180
    }
181
182
    /**
183
     * Function to set currency.
184
     *
185
     * @param string $currency
186
     *
187
     * @throws \Exception
188
     *
189
     * @return $this
190
     */
191
    public function setCurrency($currency = 'USD')
192
    {
193
        $allowedCurrencies = ['AUD', 'BRL', 'CAD', 'CZK', 'DKK', 'EUR', 'HKD', 'HUF', 'ILS', 'JPY', 'MYR', 'MXN', 'NOK', 'NZD', 'PHP', 'PLN', 'GBP', 'SGD', 'SEK', 'CHF', 'TWD', 'THB', 'USD', 'RUB'];
194
195
        // Check if provided currency is valid.
196
        if (!in_array($currency, $allowedCurrencies)) {
197
            throw new \Exception('Currency is not supported by PayPal.');
198
        }
199
200
        $this->currency = $currency;
201
202
        return $this;
203
    }
204
205
    /**
206
     * Retrieve PayPal IPN Response.
207
     *
208
     * @param array $post
209
     *
210
     * @return array
211
     */
212
    public function verifyIPN($post)
213
    {
214
        $this->setRequestData($post);
215
216
        return $this->doPayPalRequest('verifyipn');
217
    }
218
219
    /**
220
     * Refund PayPal Transaction.
221
     *
222
     * @param string $transaction
223
     *
224
     * @return array
225
     */
226
    public function refundTransaction($transaction)
227
    {
228
        $this->setRequestData([
229
            'TRANSACTIONID' => $transaction,
230
        ]);
231
232
        return $this->doPayPalRequest('RefundTransaction');
233
    }
234
235
    /**
236
     * Search Transactions On PayPal.
237
     *
238
     * @param array $post
239
     *
240
     * @return array
241
     */
242
    public function searchTransactions($post)
243
    {
244
        $this->setRequestData($post);
245
246
        return $this->doPayPalRequest('TransactionSearch');
247
    }
248
249
    /**
250
     * Function To Perform PayPal API Request.
251
     *
252
     * @param string $method
253
     *
254
     * @throws \Exception
255
     *
256
     * @return array|\Psr\Http\Message\StreamInterface
257
     */
258
    private function doPayPalRequest($method)
259
    {
260
        // Check configuration settings. Reset them if empty.
261
        if (empty($this->config)) {
262
            self::setConfig();
263
        }
264
265
        // Throw exception if configuration is still not set.
266
        if (empty($this->config)) {
267
            throw new \Exception('PayPal api settings not found.');
268
        }
269
270
        // Setting API Credentials, Version & Method
271
        $this->post->merge([
272
            'USER'      => $this->config['username'],
273
            'PWD'       => $this->config['password'],
274
            'SIGNATURE' => $this->config['signature'],
275
            'VERSION'   => 123,
276
            'METHOD'    => $method,
277
        ]);
278
279
        // Checking Whether The Request Is PayPal IPN Response
280
        if ($method == 'verifyipn') {
281
            $this->post = $this->post->filter(function ($value, $key) {
282
                if ($key !== 'METHOD') {
283
                    return $value;
284
                }
285
            });
286
287
            $post_url = $this->config['gateway_url'].'/cgi-bin/webscr';
288
        } else {
289
            $post_url = $this->config['api_url'];
290
        }
291
292
        // Merge $options array if set.
293
        if (!empty($this->options)) {
294
            $this->post->merge($this->options);
295
        }
296
297
        try {
298
            $request = $this->performHttpRequest($post_url);
299
300
            $response = $request->getBody();
301
302
            return ($method == 'verifyipn') ? $response : $this->retrieveData($response);
303
        } catch (HttpClientException $e) {
304
            throw new \Exception($e->getRequest().' '.$e->getResponse());
305
        } catch (HttpServerException $e) {
306
            throw new \Exception($e->getRequest().' '.$e->getResponse());
307
        } catch (HttpBadResponseException $e) {
308
            throw new \Exception($e->getRequest().' '.$e->getResponse());
309
        } catch (\Exception $e) {
310
            $message = $e->getMessage();
311
        }
312
313
        return [
314
            'type'      => 'error',
315
            'message'   => $message,
316
        ];
317
    }
318
319
    /**
320
     * Perform Http request and return response.
321
     *
322
     * @param string $url
323
     * @return \Psr\Http\Message\ResponseInterface
324
     */
325
    private function performHttpRequest($url)
326
    {
327
        try {
328
            return $this->client->post($url, [
329
                'body' => $this->post->toArray(),
330
            ]);
331
        } catch (\Exception $e) {
332
            return $this->client->post($url, [
333
                'form_params' => $this->post->toArray(),
334
            ]);
335
        }
336
    }
337
338
    /**
339
     * Parse PayPal NVP Response.
340
     *
341
     * @param string $request
342
     * @param array  $response
343
     *
344
     * @return array
345
     */
346
    private function retrieveData($request, array $response = null)
347
    {
348
        parse_str($request, $response);
349
350
        return $response;
351
    }
352
}
353