Completed
Push — master ( 15f709...2105b8 )
by Raza
02:52
created

PayPalRequest::searchTransactions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 6
rs 9.4285
c 2
b 0
f 0
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
10
trait PayPalRequest
11
{
12
    /**
13
     * @var HttpClient
14
     */
15
    private $client;
16
17
    /**
18
     * @var array
19
     */
20
    protected $post;
21
22
    /**
23
     * @var array
24
     */
25
    private $config;
26
27
    /**
28
     * @var string
29
     */
30
    private $currency;
31
32
    /**
33
     * @var array
34
     */
35
    private $options;
36
37
    /**
38
     * @var string
39
     */
40
    private $paymentAction;
41
42
    /**
43
     * @var string
44
     */
45
    private $locale;
46
47
    /**
48
     * Function To Set PayPal API Configuration.
49
     *
50
     * @return void
51
     */
52
    private function setConfig()
53
    {
54
        // Setting Http Client
55
        $this->client = $this->setClient();
56
57
        // Set Api Credentials
58
        if (function_exists('config')) {
59
            $this->setApiCredentials(
60
                config('paypal')
61
            );
62
        }
63
    }
64
65
    /**
66
     * Function to initialize Http Client.
67
     *
68
     * @return HttpClient
69
     */
70
    protected function setClient()
71
    {
72
        return new HttpClient([
73
            'curl' => [
74
                CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1_2,
75
            ],
76
        ]);
77
    }
78
79
    /**
80
     * Set PayPal API Credentials.
81
     *
82
     * @param array  $credentials
83
     * @param string $mode
84
     *
85
     * @return void
86
     */
87
    public function setApiCredentials($credentials, $mode = '')
88
    {
89
        // Setting Default PayPal Mode If not set
90
        if (empty($credentials['mode']) ||
91
            (!in_array($credentials['mode'], ['sandbox', 'live']))
92
        ) {
93
            $credentials['mode'] = 'live';
94
        }
95
96
        // Setting default mode.
97
        if (empty($mode)) {
98
            $mode = $credentials['mode'];
99
        }
100
101
        // Setting PayPal API Credentials
102
        foreach ($credentials[$mode] as $key => $value) {
103
            $this->config[$key] = $value;
104
        }
105
106
        // Setup PayPal API Signature value to use.
107
        if (!empty($this->config['secret'])) {
108
            $this->config['signature'] = $this->config['secret'];
109
        } else {
110
            $this->config['signature'] = file_get_contents($this->config['certificate']);
111
        }
112
113
        if ($this instanceof \Srmklive\PayPal\Services\AdaptivePayments) {
114
            $this->setAdaptivePaymentsOptions($mode);
0 ignored issues
show
Bug introduced by
The method setAdaptivePaymentsOptions() cannot be called from this context as it is declared protected in class Srmklive\PayPal\Traits\PayPalRequest.

This check looks for access to methods that are not accessible from the current context.

If you need to make a method accessible to another context you can raise its visibility level in the defining class.

Loading history...
115
        } else {
116
            $this->setExpressCheckoutOptions($credentials, $mode);
117
        }
118
119
        // Set default currency.
120
        $this->setCurrency($credentials['currency']);
121
122
        // Set default payment action.
123
        $this->paymentAction = !empty($this->config['payment_action']) ?
124
            $this->config['payment_action'] : 'Sale';
125
126
        // Set default locale.
127
        $this->locale = !empty($this->config['locale']) ?
128
            $this->config['locale'] : 'en_US';
129
    }
130
131
    /**
132
     * Set other/override PayPal API parameters.
133
     *
134
     * @param array $options
135
     *
136
     * @return $this
137
     */
138
    public function addOptions(array $options)
139
    {
140
        $this->options = $options;
141
142
        return $this;
143
    }
144
145
    /**
146
     * Set ExpressCheckout API endpoints & options.
147
     *
148
     * @param array  $credentials
149
     * @param string $mode
150
     *
151
     * @return void
152
     */
153
    protected function setExpressCheckoutOptions($credentials, $mode)
154
    {
155
        // Setting API Endpoints
156
        if ($mode == 'sandbox') {
157
            $this->config['api_url'] = !empty($this->config['secret']) ?
158
                'https://api-3t.sandbox.paypal.com/nvp' : 'https://api.sandbox.paypal.com/nvp';
159
160
            $this->config['gateway_url'] = 'https://www.sandbox.paypal.com';
161
        } else {
162
            $this->config['api_url'] = !empty($this->config['secret']) ?
163
                'https://api-3t.paypal.com/nvp' : 'https://api.paypal.com/nvp';
164
165
            $this->config['gateway_url'] = 'https://www.paypal.com';
166
        }
167
168
        // Adding params outside sandbox / live array
169
        $this->config['payment_action'] = $credentials['payment_action'];
170
        $this->config['notify_url'] = $credentials['notify_url'];
171
        $this->config['locale'] = $credentials['locale'];
172
    }
173
174
    /**
175
     * Set AdaptivePayments API endpoints & options.
176
     *
177
     * @param string $mode
178
     *
179
     * @return void
180
     */
181
    protected function setAdaptivePaymentsOptions($mode)
182
    {
183
        if ($mode == 'sandbox') {
184
            $this->config['api_url'] = 'https://svcs.sandbox.paypal.com/AdaptivePayments';
185
            $this->config['gateway_url'] = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
186
        } else {
187
            $this->config['api_url'] = 'https://svcs.paypal.com/AdaptivePayments';
188
            $this->config['gateway_url'] = 'https://www.paypal.com/cgi-bin/webscr';
189
        }
190
    }
191
192
    /**
193
     * Function to set currency.
194
     *
195
     * @param string $currency
196
     *
197
     * @throws \Exception
198
     *
199
     * @return string
200
     */
201
    public function setCurrency($currency = 'USD')
202
    {
203
        $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'];
204
205
        // Check if provided currency is valid.
206
        if (!in_array($currency, $allowedCurrencies)) {
207
            throw new \Exception('Currency is not supported by PayPal.');
208
        }
209
210
        $this->currency = $currency;
211
212
        return $this;
213
    }
214
215
    /**
216
     * Retrieve PayPal IPN Response.
217
     *
218
     * @param array $post
219
     *
220
     * @return array
221
     */
222
    public function verifyIPN($post)
223
    {
224
        $this->post = collect($post);
0 ignored issues
show
Documentation Bug introduced by
It seems like collect($post) of type object<Illuminate\Support\Collection> is incompatible with the declared type array of property $post.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
225
226
        return $this->doPayPalRequest('verifyipn');
227
    }
228
229
    /**
230
     * Refund PayPal Transaction.
231
     *
232
     * @param string $transaction
233
     *
234
     * @return array
235
     */
236
    public function refundTransaction($transaction)
237
    {
238
        $this->post = collect([
0 ignored issues
show
Documentation Bug introduced by
It seems like collect(array('TRANSACTIONID' => $transaction)) of type object<Illuminate\Support\Collection> is incompatible with the declared type array of property $post.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
239
            'TRANSACTIONID' => $transaction,
240
        ]);
241
242
        return $this->doPayPalRequest('RefundTransaction');
243
    }
244
245
    /**
246
     * Search Transactions On PayPal.
247
     *
248
     * @param array $post
249
     *
250
     * @return array
251
     */
252
    public function searchTransactions($post)
253
    {
254
        $this->post = collect($post);
0 ignored issues
show
Documentation Bug introduced by
It seems like collect($post) of type object<Illuminate\Support\Collection> is incompatible with the declared type array of property $post.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
255
256
        return $this->doPayPalRequest('TransactionSearch');
257
    }
258
259
    /**
260
     * Function To Perform PayPal API Request.
261
     *
262
     * @param string $method
263
     *
264
     * @throws \Exception
265
     *
266
     * @return array|\Psr\Http\Message\StreamInterface
267
     */
268
    private function doPayPalRequest($method)
269
    {
270
        // Check configuration settings. Reset them if empty.
271
        if (empty($this->config)) {
272
            self::setConfig();
273
        }
274
275
        // Throw exception if configuration is still not set.
276
        if (empty($this->config)) {
277
            throw new \Exception('PayPal api settings not found.');
278
        }
279
280
        // Setting API Credentials, Version & Method
281
        $this->post->merge([
282
            'USER'      => $this->config['username'],
283
            'PWD'       => $this->config['password'],
284
            'SIGNATURE' => $this->config['signature'],
285
            'VERSION'   => 123,
286
            'METHOD'    => $method,
287
        ]);
288
289
        // Checking Whether The Request Is PayPal IPN Response
290
        if ($method == 'verifyipn') {
291
            $this->post = $this->post->filter(function($value, $key) {
292
                if ($key !== 'METHOD') {
293
                    return $value;
294
                }
295
            });
296
297
            $post_url = $this->config['gateway_url'].'/cgi-bin/webscr';
298
        } else {
299
            $post_url = $this->config['api_url'];
300
        }
301
302
        // Merge $options array if set.
303
        if (!empty($this->options)) {
304
            $this->post->merge($this->options);
305
        }
306
307
        try {
308
            $request = $this->client->post($post_url, [
309
                'form_params' => $this->post->toArray(),
310
            ]);
311
312
            $response = $request->getBody(true);
313
314
            return ($method == 'verifyipn') ? $response : $this->retrieveData($response);
315
        } catch (HttpClientException $e) {
316
            throw new \Exception($e->getRequest().' '.$e->getResponse());
317
        } catch (HttpServerException $e) {
318
            throw new \Exception($e->getRequest().' '.$e->getResponse());
319
        } catch (HttpBadResponseException $e) {
320
            throw new \Exception($e->getRequest().' '.$e->getResponse());
321
        } catch (\Exception $e) {
322
            $message = $e->getMessage();
323
        }
324
325
        return [
326
            'type'      => 'error',
327
            'message'   => $message,
328
        ];
329
    }
330
331
    /**
332
     * Parse PayPal NVP Response.
333
     *
334
     * @param string $request
335
     * @param array  $response
336
     *
337
     * @return array
338
     */
339
    private function retrieveData($request, array $response = null)
340
    {
341
        parse_str($request, $response);
342
343
        return $response;
344
    }
345
}
346