Completed
Pull Request — master (#212)
by Dzmitry
01:45
created

ExpressCheckout::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 9
rs 9.6666
1
<?php
2
3
namespace Srmklive\PayPal\Services;
4
5
use Illuminate\Support\Collection;
6
use Srmklive\PayPal\Traits\PayPalRequest as PayPalAPIRequest;
7
use Srmklive\PayPal\Traits\PayPalTransactions;
8
use Srmklive\PayPal\Traits\RecurringProfiles;
9
10
class ExpressCheckout
11
{
12
    // Integrate PayPal Request trait
13
    use PayPalAPIRequest, PayPalTransactions, RecurringProfiles;
14
15
    /**
16
     * ExpressCheckout constructor.
17
     *
18
     * @param array $config
19
     *
20
     * @throws \Exception
21
     */
22
    public function __construct(array $config = [])
23
    {
24
        // Setting PayPal API Credentials
25
        $this->setConfig($config);
26
27
        $this->httpBodyParam = 'form_params';
28
29
        $this->options = [];
30
    }
31
32
    /**
33
     * Set ExpressCheckout API endpoints & options.
34
     *
35
     * @param array $credentials
36
     *
37
     * @return void
38
     */
39
    public function setExpressCheckoutOptions($credentials)
40
    {
41
        // Setting API Endpoints
42
        if ($this->mode === 'sandbox') {
43
            $this->config['api_url'] = !empty($this->config['secret']) ?
44
                'https://api-3t.sandbox.paypal.com/nvp' : 'https://api.sandbox.paypal.com/nvp';
45
46
            $this->config['gateway_url'] = 'https://www.sandbox.paypal.com';
47
        } else {
48
            $this->config['api_url'] = !empty($this->config['secret']) ?
49
                'https://api-3t.paypal.com/nvp' : 'https://api.paypal.com/nvp';
50
51
            $this->config['gateway_url'] = 'https://www.paypal.com';
52
        }
53
54
        // Adding params outside sandbox / live array
55
        $this->config['payment_action'] = $credentials['payment_action'];
56
        $this->config['notify_url'] = $credentials['notify_url'];
57
        $this->config['locale'] = $credentials['locale'];
58
    }
59
60
    /**
61
     * Set cart item details for PayPal.
62
     *
63
     * @param array $items
64
     *
65
     * @return \Illuminate\Support\Collection
66
     */
67
    protected function setCartItems($items)
68
    {
69
        return (new Collection($items))->map(function ($item, $num) {
70
            return [
71
                'L_PAYMENTREQUEST_0_NAME'.$num => $item['name'],
72
                'L_PAYMENTREQUEST_0_AMT'.$num  => $item['price'],
73
                'L_PAYMENTREQUEST_0_QTY'.$num  => isset($item['qty']) ? $item['qty'] : 1,
74
            ];
75
        })->flatMap(function ($value) {
76
            return $value;
77
        });
78
    }
79
80
    /**
81
     * Set Recurring payments details for SetExpressCheckout API call.
82
     *
83
     * @param array $data
84
     * @param bool  $subscription
85
     */
86
    protected function setExpressCheckoutRecurringPaymentConfig($data, $subscription = false)
87
    {
88
        $this->post = $this->post->merge([
89
            'L_BILLINGTYPE0'                 => ($subscription) ? 'RecurringPayments' : 'MerchantInitiatedBilling',
90
            'L_BILLINGAGREEMENTDESCRIPTION0' => !empty($data['subscription_desc']) ?
91
                $data['subscription_desc'] : $data['invoice_description'],
92
        ]);
93
    }
94
95
    /**
96
     * Set item subtotal if available.
97
     *
98
     * @param array $data
99
     */
100
    protected function setItemSubTotal($data)
101
    {
102
        $this->subtotal = isset($data['subtotal']) ? $data['subtotal'] : $data['total'];
103
    }
104
105
    /**
106
     * Set shipping amount if available.
107
     *
108
     * @param array $data
109
     */
110
    protected function setShippingAmount($data)
111
    {
112
        if (isset($data['shipping'])) {
113
            $this->post = $this->post->merge([
114
                'PAYMENTREQUEST_0_SHIPPINGAMT' => $data['shipping'],
115
            ]);
116
        }
117
    }
118
    
119
    /**
120
     * Set shipping discount if available.
121
     *
122
     * @param array $data
123
     */
124
    protected function setShippingDiscount($data)
125
    {
126
        if (isset($data['shipping_discount'])) {
127
            $this->post = $this->post->merge([
128
                'PAYMENTREQUEST_0_SHIPDISCAMT' => $data['shipping_discount'] * -1,
129
            ]);
130
        }
131
    }
132
133
    /**
134
     * Perform a SetExpressCheckout API call on PayPal.
135
     *
136
     * @param array $data
137
     * @param bool  $subscription
138
     *
139
     * @throws \Exception
140
     *
141
     * @return array|\Psr\Http\Message\StreamInterface
142
     */
143
    public function setExpressCheckout($data, $subscription = false)
144
    {
145
        $this->setItemSubTotal($data);
146
147
        $this->post = $this->setCartItems($data['items'])->merge([
148
            'PAYMENTREQUEST_0_ITEMAMT'       => $this->subtotal,
149
            'PAYMENTREQUEST_0_AMT'           => $data['total'],
150
            'PAYMENTREQUEST_0_PAYMENTACTION' => $this->paymentAction,
151
            'PAYMENTREQUEST_0_CURRENCYCODE'  => $this->currency,
152
            'PAYMENTREQUEST_0_DESC'          => $data['invoice_description'],
153
            'PAYMENTREQUEST_0_INVNUM'        => $data['invoice_id'],
154
            'NOSHIPPING'                     => 1,
155
            'RETURNURL'                      => $data['return_url'],
156
            'CANCELURL'                      => $data['cancel_url'],
157
            'LOCALE'                         => $this->locale,
158
        ]);
159
160
        $this->setShippingAmount($data);
161
        $this->setShippingDiscount($data);
162
163
        $this->setExpressCheckoutRecurringPaymentConfig($data, $subscription);
164
165
        $response = $this->doPayPalRequest('SetExpressCheckout');
166
167
        return collect($response)->merge([
168
            'paypal_link' => !empty($response['TOKEN']) ? $this->config['gateway_url'].'/webscr?cmd=_express-checkout&token='.$response['TOKEN'] : null,
169
        ])->toArray();
170
    }
171
172
    /**
173
     * Perform a GetExpressCheckoutDetails API call on PayPal.
174
     *
175
     * @param string $token
176
     *
177
     * @throws \Exception
178
     *
179
     * @return array|\Psr\Http\Message\StreamInterface
180
     */
181
    public function getExpressCheckoutDetails($token)
182
    {
183
        $this->setRequestData([
184
            'TOKEN' => $token,
185
        ]);
186
187
        return $this->doPayPalRequest('GetExpressCheckoutDetails');
188
    }
189
190
    /**
191
     * Perform DoExpressCheckoutPayment API call on PayPal.
192
     *
193
     * @param array  $data
194
     * @param string $token
195
     * @param string $payerid
196
     *
197
     * @throws \Exception
198
     *
199
     * @return array|\Psr\Http\Message\StreamInterface
200
     */
201
    public function doExpressCheckoutPayment($data, $token, $payerid)
202
    {
203
        $this->setItemSubTotal($data);
204
205
        $this->post = $this->setCartItems($data['items'])->merge([
206
            'TOKEN'                          => $token,
207
            'PAYERID'                        => $payerid,
208
            'PAYMENTREQUEST_0_ITEMAMT'       => $this->subtotal,
209
            'PAYMENTREQUEST_0_AMT'           => $data['total'],
210
            'PAYMENTREQUEST_0_PAYMENTACTION' => !empty($this->config['payment_action']) ? $this->config['payment_action'] : 'Sale',
211
            'PAYMENTREQUEST_0_CURRENCYCODE'  => $this->currency,
212
            'PAYMENTREQUEST_0_DESC'          => $data['invoice_description'],
213
            'PAYMENTREQUEST_0_INVNUM'        => $data['invoice_id'],
214
            'PAYMENTREQUEST_0_NOTIFYURL'     => $this->notifyUrl,
215
        ]);
216
217
        $this->setShippingAmount($data);
218
219
        return $this->doPayPalRequest('DoExpressCheckoutPayment');
220
    }
221
222
    /**
223
     * Perform a DoAuthorization API call on PayPal.
224
     *
225
     * @param string $authorization_id Transaction ID
226
     * @param float  $amount           Amount to capture
227
     * @param array  $data             Optional request fields
228
     *
229
     * @throws \Exception
230
     *
231
     * @return array|\Psr\Http\Message\StreamInterface
232
     */
233
    public function doAuthorization($authorization_id, $amount, $data = [])
234
    {
235
        $this->setRequestData(
236
            array_merge($data, [
237
                'AUTHORIZATIONID' => $authorization_id,
238
                'AMT'             => $amount,
239
            ])
240
        );
241
242
        return $this->doPayPalRequest('DoAuthorization');
243
    }
244
245
    /**
246
     * Perform a DoCapture API call on PayPal.
247
     *
248
     * @param string $authorization_id Transaction ID
249
     * @param float  $amount           Amount to capture
250
     * @param string $complete         Indicates whether or not this is the last capture.
251
     * @param array  $data             Optional request fields
252
     *
253
     * @throws \Exception
254
     *
255
     * @return array|\Psr\Http\Message\StreamInterface
256
     */
257
    public function doCapture($authorization_id, $amount, $complete = 'Complete', $data = [])
258
    {
259
        $this->setRequestData(
260
            array_merge($data, [
261
                'AUTHORIZATIONID' => $authorization_id,
262
                'AMT'             => $amount,
263
                'COMPLETETYPE'    => $complete,
264
                'CURRENCYCODE'    => $this->currency,
265
            ])
266
        );
267
268
        return $this->doPayPalRequest('DoCapture');
269
    }
270
271
    /**
272
     * Perform a DoReauthorization API call on PayPal to reauthorize an existing authorization transaction.
273
     *
274
     * @param string $authorization_id
275
     * @param float  $amount
276
     * @param array  $data
277
     *
278
     * @throws \Exception
279
     *
280
     * @return array|\Psr\Http\Message\StreamInterface
281
     */
282
    public function doReAuthorization($authorization_id, $amount, $data = [])
283
    {
284
        $this->setRequestData(
285
            array_merge($data, [
286
                'AUTHORIZATIONID' => $authorization_id,
287
                'AMOUNT'          => $amount,
288
            ])
289
        );
290
291
        return $this->doPayPalRequest('DoReauthorization');
292
    }
293
294
    /**
295
     * Perform a DoVoid API call on PayPal.
296
     *
297
     * @param string $authorization_id Transaction ID
298
     * @param array  $data             Optional request fields
299
     *
300
     * @throws \Exception
301
     *
302
     * @return array|\Psr\Http\Message\StreamInterface
303
     */
304
    public function doVoid($authorization_id, $data = [])
305
    {
306
        $this->setRequestData(
307
            array_merge($data, [
308
                'AUTHORIZATIONID' => $authorization_id,
309
            ])
310
        );
311
312
        return $this->doPayPalRequest('DoVoid');
313
    }
314
315
    /**
316
     * Perform a CreateBillingAgreement API call on PayPal.
317
     *
318
     * @param string $token
319
     *
320
     * @throws \Exception
321
     *
322
     * @return array|\Psr\Http\Message\StreamInterface
323
     */
324
    public function createBillingAgreement($token)
325
    {
326
        $this->setRequestData([
327
            'TOKEN' => $token,
328
        ]);
329
330
        return $this->doPayPalRequest('CreateBillingAgreement');
331
    }
332
333
    /**
334
     * Perform a CreateRecurringPaymentsProfile API call on PayPal.
335
     *
336
     * @param array  $data
337
     * @param string $token
338
     *
339
     * @throws \Exception
340
     *
341
     * @return array|\Psr\Http\Message\StreamInterface
342
     */
343
    public function createRecurringPaymentsProfile($data, $token)
344
    {
345
        $this->post = $this->setRequestData($data)->merge([
346
            'TOKEN' => $token,
347
        ]);
348
349
        return $this->doPayPalRequest('CreateRecurringPaymentsProfile');
350
    }
351
352
    /**
353
     * Perform a GetRecurringPaymentsProfileDetails API call on PayPal.
354
     *
355
     * @param string $id
356
     *
357
     * @throws \Exception
358
     *
359
     * @return array|\Psr\Http\Message\StreamInterface
360
     */
361
    public function getRecurringPaymentsProfileDetails($id)
362
    {
363
        $this->setRequestData([
364
            'PROFILEID' => $id,
365
        ]);
366
367
        return $this->doPayPalRequest('GetRecurringPaymentsProfileDetails');
368
    }
369
370
    /**
371
     * Perform a UpdateRecurringPaymentsProfile API call on PayPal.
372
     *
373
     * @param array  $data
374
     * @param string $id
375
     *
376
     * @throws \Exception
377
     *
378
     * @return array|\Psr\Http\Message\StreamInterface
379
     */
380
    public function updateRecurringPaymentsProfile($data, $id)
381
    {
382
        $this->post = $this->setRequestData($data)->merge([
383
            'PROFILEID' => $id,
384
        ]);
385
386
        return $this->doPayPalRequest('UpdateRecurringPaymentsProfile');
387
    }
388
389
    /**
390
     * Change Recurring payment profile status on PayPal.
391
     *
392
     * @param string $id
393
     * @param string $status
394
     *
395
     * @throws \Exception
396
     *
397
     * @return array|\Psr\Http\Message\StreamInterface
398
     */
399
    protected function manageRecurringPaymentsProfileStatus($id, $status)
400
    {
401
        $this->setRequestData([
402
            'PROFILEID' => $id,
403
            'ACTION'    => $status,
404
        ]);
405
406
        return $this->doPayPalRequest('ManageRecurringPaymentsProfileStatus');
407
    }
408
409
    /**
410
     * Perform a ManageRecurringPaymentsProfileStatus API call on PayPal to cancel a RecurringPaymentsProfile.
411
     *
412
     * @param string $id
413
     *
414
     * @throws \Exception
415
     *
416
     * @return array|\Psr\Http\Message\StreamInterface
417
     */
418
    public function cancelRecurringPaymentsProfile($id)
419
    {
420
        return $this->manageRecurringPaymentsProfileStatus($id, 'Cancel');
421
    }
422
423
    /**
424
     * Perform a ManageRecurringPaymentsProfileStatus API call on PayPal to suspend a RecurringPaymentsProfile.
425
     *
426
     * @param string $id
427
     *
428
     * @throws \Exception
429
     *
430
     * @return array|\Psr\Http\Message\StreamInterface
431
     */
432
    public function suspendRecurringPaymentsProfile($id)
433
    {
434
        return $this->manageRecurringPaymentsProfileStatus($id, 'Suspend');
435
    }
436
437
    /**
438
     * Perform a ManageRecurringPaymentsProfileStatus API call on PayPal to reactivate a RecurringPaymentsProfile.
439
     *
440
     * @param string $id
441
     *
442
     * @throws \Exception
443
     *
444
     * @return array|\Psr\Http\Message\StreamInterface
445
     */
446
    public function reactivateRecurringPaymentsProfile($id)
447
    {
448
        return $this->manageRecurringPaymentsProfileStatus($id, 'Reactivate');
449
    }
450
}
451