Completed
Push — master ( f3a94d...aa0739 )
by Raza
02:37
created

PayPalRequest::setApiCredentials()   C

Complexity

Conditions 10
Paths 144

Size

Total Lines 48
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 10
eloc 24
nc 144
nop 2
dl 0
loc 48
rs 5.0666
c 1
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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