Completed
Push — master ( 8e1cce...aa0857 )
by Raza
08:07
created

PayPalRequest::setApiProviderConfiguration()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 21
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 21
rs 9.3142
cc 2
eloc 10
nc 2
nop 1
1
<?php
2
3
namespace Srmklive\PayPal\Traits;
4
5
use Illuminate\Support\Collection;
6
7
trait PayPalRequest
8
{
9
    use PayPalHttpClient;
10
11
    /**
12
     * Http Client class object.
13
     *
14
     * @var HttpClient
15
     */
16
    private $client;
17
18
    /**
19
     * Http Client configuration.
20
     *
21
     * @var array
22
     */
23
    private $httpClientConfig;
24
25
    /**
26
     * PayPal API Certificate data for authentication.
27
     *
28
     * @var string
29
     */
30
    private $certificate;
31
32
    /**
33
     * PayPal API mode to be used.
34
     *
35
     * @var string
36
     */
37
    public $mode;
38
39
    /**
40
     * Request data to be sent to PayPal.
41
     *
42
     * @var \Illuminate\Support\Collection
43
     */
44
    protected $post;
45
46
    /**
47
     * PayPal API configuration.
48
     *
49
     * @var array
50
     */
51
    private $config;
52
53
    /**
54
     * Default currency for PayPal.
55
     *
56
     * @var string
57
     */
58
    private $currency;
59
60
    /**
61
     * Additional options for PayPal API request.
62
     *
63
     * @var array
64
     */
65
    private $options;
66
67
    /**
68
     * Default payment action for PayPal.
69
     *
70
     * @var string
71
     */
72
    private $paymentAction;
73
74
    /**
75
     * Default locale for PayPal.
76
     *
77
     * @var string
78
     */
79
    private $locale;
80
81
    /**
82
     * PayPal API Endpoint.
83
     *
84
     * @var string
85
     */
86
    private $apiUrl;
87
88
    /**
89
     * IPN notification url for PayPal.
90
     *
91
     * @var string
92
     */
93
    private $notifyUrl;
94
95
    /**
96
     * Http Client request body parameter name.
97
     *
98
     * @var string
99
     */
100
    private $httpBodyParam;
101
102
    /**
103
     * Validate SSL details when creating HTTP client.
104
     *
105
     * @var bool
106
     */
107
    private $validateSSL;
108
109
    /**
110
     * Function To Set PayPal API Configuration.
111
     *
112
     * @param array $config
113
     *
114
     * @throws \Exception
115
     */
116
    private function setConfig(array $config = [])
117
    {
118
        // Set Api Credentials
119
        if (function_exists('config')) {
120
            $this->setApiCredentials(
121
                config('paypal')
122
            );
123
        } elseif (!empty($config)) {
124
            $this->setApiCredentials($config);
125
        }
126
127
        $this->setRequestData();
128
    }
129
130
    /**
131
     * Set default values for configuration.
132
     *
133
     * @return void
134
     */
135
    private function setDefaultValues()
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
136
    {
137
        // Set default payment action.
138
        if (empty($this->paymentAction)) {
139
            $this->paymentAction = 'Sale';
140
        }
141
142
        // Set default locale.
143
        if (empty($this->locale)) {
144
            $this->locale = 'en_US';
145
        }
146
147
        // Set default value for SSL validation.
148
        if (empty($this->validateSSL)) {
149
            $this->validateSSL = false;
150
        }
151
    }
152
153
    /**
154
     * Set PayPal API Credentials.
155
     *
156
     * @param array $credentials
157
     *
158
     * @throws \Exception
159
     *
160
     * @return void
161
     */
162
    public function setApiCredentials($credentials)
163
    {
164
        // Setting Default PayPal Mode If not set
165
        $this->setApiEnvironment($credentials);
166
167
        // Set API configuration for the PayPal provider
168
        $this->setApiProviderConfiguration($credentials);
169
170
        // Set default currency.
171
        $this->setCurrency($credentials['currency']);
172
173
        // Set Http Client configuration.
174
        $this->setHttpClientConfiguration();
175
    }
176
177
    /**
178
     * Set API environment to be used by PayPal.
179
     *
180
     * @param array $credentials
181
     *
182
     * @return void
183
     */
184
    private function setApiEnvironment($credentials)
185
    {
186
        if (empty($credentials['mode']) || !in_array($credentials['mode'], ['sandbox', 'live'])) {
187
            $this->mode = 'live';
188
        } else {
189
            $this->mode = $credentials['mode'];
190
        }
191
    }
192
193
    /**
194
     * Set configuration details for the provider.
195
     *
196
     * @param array $credentials
197
     *
198
     * @throws \Exception
199
     *
200
     * @return void
201
     */
202
    private function setApiProviderConfiguration($credentials)
203
    {
204
        // Setting PayPal API Credentials
205
        collect($credentials[$this->mode])->map(function ($value, $key) {
206
            $this->config[$key] = $value;
207
        });
208
209
        // Setup PayPal API Signature value to use.
210
        $this->config['signature'] = empty($this->config['certificate']) ?
211
            $this->config['secret'] : $this->config['certificate'];
212
213
        $this->paymentAction = $credentials['payment_action'];
214
215
        $this->locale = $credentials['locale'];
216
217
        $this->certificate = $this->config['certificate'];
218
219
        $this->validateSSL = $credentials['validate_ssl'];
220
221
        $this->setApiProvider($credentials);
222
    }
223
224
    /**
225
     * Determines which API provider should be used.
226
     *
227
     * @param array $credentials
228
     *
229
     * @throws \Exception
230
     */
231
    private function setApiProvider($credentials)
232
    {
233
        if ($this instanceof \Srmklive\PayPal\Services\AdaptivePayments) {
234
            $this->setAdaptivePaymentsOptions();
235
        } elseif ($this instanceof \Srmklive\PayPal\Services\ExpressCheckout) {
236
            $this->setExpressCheckoutOptions($credentials);
237
        } else {
238
            throw new \Exception('Invalid api credentials provided for PayPal!. Please provide the right api credentials.');
239
        }
240
    }
241
242
    /**
243
     * Setup request data to be sent to PayPal.
244
     *
245
     * @param array $data
246
     *
247
     * @return \Illuminate\Support\Collection
248
     */
249
    protected function setRequestData(array $data = [])
250
    {
251
        if (($this->post instanceof Collection) && (!$this->post->isEmpty())) {
252
            unset($this->post);
253
        }
254
255
        $this->post = new Collection($data);
256
257
        return $this->post;
258
    }
259
260
    /**
261
     * Set other/override PayPal API parameters.
262
     *
263
     * @param array $options
264
     *
265
     * @return $this
266
     */
267
    public function addOptions(array $options)
268
    {
269
        $this->options = $options;
270
271
        return $this;
272
    }
273
274
    /**
275
     * Function to set currency.
276
     *
277
     * @param string $currency
278
     *
279
     * @throws \Exception
280
     *
281
     * @return $this
282
     */
283
    public function setCurrency($currency = 'USD')
284
    {
285
        $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'];
286
287
        // Check if provided currency is valid.
288
        if (!in_array($currency, $allowedCurrencies)) {
289
            throw new \Exception('Currency is not supported by PayPal.');
290
        }
291
292
        $this->currency = $currency;
293
294
        return $this;
295
    }
296
297
    /**
298
     * Retrieve PayPal IPN Response.
299
     *
300
     * @param array $post
301
     *
302
     * @return array
303
     */
304
    public function verifyIPN($post)
305
    {
306
        $this->setRequestData($post);
307
308
        $this->apiUrl = $this->config['gateway_url'].'/cgi-bin/webscr';
309
310
        return $this->doPayPalRequest('verifyipn');
311
    }
312
313
    /**
314
     * Create request payload to be sent to PayPal.
315
     *
316
     * @param string $method
317
     */
318
    private function createRequestPayload($method)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
319
    {
320
        $config = array_merge([
321
            'USER'      => $this->config['username'],
322
            'PWD'       => $this->config['password'],
323
            'SIGNATURE' => $this->config['signature'],
324
            'VERSION'   => 123,
325
            'METHOD'    => $method,
326
        ], $this->options);
327
328
        $this->post = $this->post->merge($config);
329
        if ($method === 'verifyipn') {
330
            $this->post->forget('METHOD');
331
        }
332
    }
333
334
    /**
335
     * Parse PayPal NVP Response.
336
     *
337
     * @param string                                  $method
338
     * @param array|\Psr\Http\Message\StreamInterface $response
339
     *
340
     * @return array
341
     */
342
    private function retrieveData($method, $response)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
343
    {
344
        if ($method === 'verifyipn') {
345
            return $response;
346
        }
347
348
        parse_str($response, $output);
349
350
        return $output;
351
    }
352
}
353