Completed
Push — master ( 1f7a83...be92b0 )
by Raza
01:46
created

PayPalRequest::setCurrency()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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