Completed
Push — master ( 19a932...f889a9 )
by Raza
04:52
created

PayPalRequest::setBillingType()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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