Completed
Push — master ( c21037...aa55db )
by Raza
01:57
created

ExpressCheckout::setShippingAmount()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 2
eloc 4
nc 2
nop 1
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
     * Perform a SetExpressCheckout API call on PayPal.
121
     *
122
     * @param array $data
123
     * @param bool  $subscription
124
     *
125
     * @return array|\Psr\Http\Message\StreamInterface
126
     *
127
     * @throws \Exception
128
     */
129
    public function setExpressCheckout($data, $subscription = false)
130
    {
131
        $this->setItemSubTotal($data);
132
133
        $this->post = $this->setCartItems($data['items'])->merge([
134
            'PAYMENTREQUEST_0_ITEMAMT'       => $this->subtotal,
135
            'PAYMENTREQUEST_0_AMT'           => $data['total'],
136
            'PAYMENTREQUEST_0_PAYMENTACTION' => $this->paymentAction,
137
            'PAYMENTREQUEST_0_CURRENCYCODE'  => $this->currency,
138
            'PAYMENTREQUEST_0_DESC'          => $data['invoice_description'],
139
            'PAYMENTREQUEST_0_INVNUM'        => $data['invoice_id'],
140
            'NOSHIPPING'                     => 1,
141
            'RETURNURL'                      => $data['return_url'],
142
            'CANCELURL'                      => $data['cancel_url'],
143
            'LOCALE'                         => $this->locale,
144
        ]);
145
146
        $this->setShippingAmount($data);
147
148
        $this->setExpressCheckoutRecurringPaymentConfig($data, $subscription);
149
150
        $response = $this->doPayPalRequest('SetExpressCheckout');
151
152
        return collect($response)->merge([
153
            'paypal_link' => !empty($response['TOKEN']) ? $this->config['gateway_url'].'/webscr?cmd=_express-checkout&token='.$response['TOKEN'] : null,
154
        ])->toArray();
155
    }
156
157
    /**
158
     * Perform a GetExpressCheckoutDetails API call on PayPal.
159
     *
160
     * @param string $token
161
     *
162
     * @return array|\Psr\Http\Message\StreamInterface
163
     *
164
     * @throws \Exception
165
     */
166
    public function getExpressCheckoutDetails($token)
167
    {
168
        $this->setRequestData([
169
            'TOKEN' => $token,
170
        ]);
171
172
        return $this->doPayPalRequest('GetExpressCheckoutDetails');
173
    }
174
175
    /**
176
     * Perform DoExpressCheckoutPayment API call on PayPal.
177
     *
178
     * @param array  $data
179
     * @param string $token
180
     * @param string $payerid
181
     *
182
     * @return array|\Psr\Http\Message\StreamInterface
183
     *
184
     * @throws \Exception
185
     */
186
    public function doExpressCheckoutPayment($data, $token, $payerid)
187
    {
188
        $this->post = $this->setCartItems($data['items'])->merge([
189
            'TOKEN'                          => $token,
190
            'PAYERID'                        => $payerid,
191
            'PAYMENTREQUEST_0_ITEMAMT'       => $data['total'],
192
            'PAYMENTREQUEST_0_AMT'           => $data['total'],
193
            'PAYMENTREQUEST_0_PAYMENTACTION' => !empty($this->config['payment_action']) ? $this->config['payment_action'] : 'Sale',
194
            'PAYMENTREQUEST_0_CURRENCYCODE'  => $this->currency,
195
            'PAYMENTREQUEST_0_DESC'          => $data['invoice_description'],
196
            'PAYMENTREQUEST_0_INVNUM'        => $data['invoice_id'],
197
            'PAYMENTREQUEST_0_NOTIFYURL'     => $this->notifyUrl,
198
        ]);
199
200
        return $this->doPayPalRequest('DoExpressCheckoutPayment');
201
    }
202
203
    /**
204
     * Perform a DoAuthorization API call on PayPal.
205
     *
206
     * @param string $authorization_id Transaction ID
207
     * @param float  $amount           Amount to capture
208
     * @param array  $data             Optional request fields
209
     *
210
     * @return array|\Psr\Http\Message\StreamInterface
211
     *
212
     * @throws \Exception
213
     */
214
    public function doAuthorization($authorization_id, $amount, $data = [])
215
    {
216
        $this->setRequestData(
217
            array_merge($data, [
218
                'AUTHORIZATIONID' => $authorization_id,
219
                'AMT'             => $amount,
220
            ])
221
        );
222
223
        return $this->doPayPalRequest('DoAuthorization');
224
    }
225
226
    /**
227
     * Perform a DoCapture API call on PayPal.
228
     *
229
     * @param string $authorization_id Transaction ID
230
     * @param float  $amount           Amount to capture
231
     * @param string $complete         Indicates whether or not this is the last capture.
232
     * @param array  $data             Optional request fields
233
     *
234
     * @return array|\Psr\Http\Message\StreamInterface
235
     *
236
     * @throws \Exception
237
     */
238
    public function doCapture($authorization_id, $amount, $complete = 'Complete', $data = [])
239
    {
240
        $this->setRequestData(
241
            array_merge($data, [
242
                'AUTHORIZATIONID' => $authorization_id,
243
                'AMT'             => $amount,
244
                'COMPLETETYPE'    => $complete,
245
                'CURRENCYCODE'    => $this->currency,
246
            ])
247
        );
248
249
        return $this->doPayPalRequest('DoCapture');
250
    }
251
252
    /**
253
     * Perform a DoReauthorization API call on PayPal to reauthorize an existing authorization transaction.
254
     *
255
     * @param string $authorization_id
256
     * @param float  $amount
257
     * @param array  $data
258
     *
259
     * @return array|\Psr\Http\Message\StreamInterface
260
     *
261
     * @throws \Exception
262
     */
263
    public function doReAuthorization($authorization_id, $amount, $data = [])
264
    {
265
        $this->setRequestData(
266
            array_merge($data, [
267
                'AUTHORIZATIONID' => $authorization_id,
268
                'AMOUNT'          => $amount,
269
            ])
270
        );
271
272
        return $this->doPayPalRequest('DoReauthorization');
273
    }
274
275
    /**
276
     * Perform a DoVoid API call on PayPal.
277
     *
278
     * @param string $authorization_id Transaction ID
279
     * @param array  $data             Optional request fields
280
     *
281
     * @return array|\Psr\Http\Message\StreamInterface
282
     *
283
     * @throws \Exception
284
     */
285
    public function doVoid($authorization_id, $data = [])
286
    {
287
        $this->setRequestData(
288
            array_merge($data, [
289
                'AUTHORIZATIONID' => $authorization_id,
290
            ])
291
        );
292
293
        return $this->doPayPalRequest('DoVoid');
294
    }
295
296
    /**
297
     * Perform a CreateBillingAgreement API call on PayPal.
298
     *
299
     * @param string $token
300
     *
301
     * @return array|\Psr\Http\Message\StreamInterface
302
     *
303
     * @throws \Exception
304
     */
305
    public function createBillingAgreement($token)
306
    {
307
        $this->setRequestData([
308
            'TOKEN' => $token,
309
        ]);
310
311
        return $this->doPayPalRequest('CreateBillingAgreement');
312
    }
313
314
    /**
315
     * Perform a CreateRecurringPaymentsProfile API call on PayPal.
316
     *
317
     * @param array  $data
318
     * @param string $token
319
     *
320
     * @return array|\Psr\Http\Message\StreamInterface
321
     *
322
     * @throws \Exception
323
     */
324
    public function createRecurringPaymentsProfile($data, $token)
325
    {
326
        $this->post = $this->setRequestData($data)->merge([
327
            'TOKEN' => $token,
328
        ]);
329
330
        return $this->doPayPalRequest('CreateRecurringPaymentsProfile');
331
    }
332
333
    /**
334
     * Perform a GetRecurringPaymentsProfileDetails API call on PayPal.
335
     *
336
     * @param string $id
337
     *
338
     * @return array|\Psr\Http\Message\StreamInterface
339
     *
340
     * @throws \Exception
341
     */
342
    public function getRecurringPaymentsProfileDetails($id)
343
    {
344
        $this->setRequestData([
345
            'PROFILEID' => $id,
346
        ]);
347
348
        return $this->doPayPalRequest('GetRecurringPaymentsProfileDetails');
349
    }
350
351
    /**
352
     * Perform a UpdateRecurringPaymentsProfile API call on PayPal.
353
     *
354
     * @param array  $data
355
     * @param string $id
356
     *
357
     * @return array|\Psr\Http\Message\StreamInterface
358
     *
359
     * @throws \Exception
360
     */
361
    public function updateRecurringPaymentsProfile($data, $id)
362
    {
363
        $this->post = $this->setRequestData($data)->merge([
364
            'PROFILEID' => $id,
365
        ]);
366
367
        return $this->doPayPalRequest('UpdateRecurringPaymentsProfile');
368
    }
369
370
    /**
371
     * Change Recurring payment profile status on PayPal.
372
     *
373
     * @param string $id
374
     * @param string $status
375
     *
376
     * @return array|\Psr\Http\Message\StreamInterface
377
     *
378
     * @throws \Exception
379
     */
380
    protected function manageRecurringPaymentsProfileStatus($id, $status)
381
    {
382
        $this->setRequestData([
383
            'PROFILEID' => $id,
384
            'ACTION'    => $status,
385
        ]);
386
387
        return $this->doPayPalRequest('ManageRecurringPaymentsProfileStatus');
388
    }
389
390
    /**
391
     * Perform a ManageRecurringPaymentsProfileStatus API call on PayPal to cancel a RecurringPaymentsProfile.
392
     *
393
     * @param string $id
394
     *
395
     * @return array|\Psr\Http\Message\StreamInterface
396
     *
397
     * @throws \Exception
398
     */
399
    public function cancelRecurringPaymentsProfile($id)
400
    {
401
        return $this->manageRecurringPaymentsProfileStatus($id, 'Cancel');
402
    }
403
404
    /**
405
     * Perform a ManageRecurringPaymentsProfileStatus API call on PayPal to suspend a RecurringPaymentsProfile.
406
     *
407
     * @param string $id
408
     *
409
     * @return array|\Psr\Http\Message\StreamInterface
410
     *
411
     * @throws \Exception
412
     */
413
    public function suspendRecurringPaymentsProfile($id)
414
    {
415
        return $this->manageRecurringPaymentsProfileStatus($id, 'Suspend');
416
    }
417
418
    /**
419
     * Perform a ManageRecurringPaymentsProfileStatus API call on PayPal to reactivate a RecurringPaymentsProfile.
420
     *
421
     * @param string $id
422
     *
423
     * @return array|\Psr\Http\Message\StreamInterface
424
     *
425
     * @throws \Exception
426
     */
427
    public function reactivateRecurringPaymentsProfile($id)
428
    {
429
        return $this->manageRecurringPaymentsProfileStatus($id, 'Reactivate');
430
    }
431
}
432