Completed
Push — master ( 9dbcbe...23c988 )
by Raza
02:13
created

AdaptivePayments::createRequestPayload()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 6
rs 9.4285
1
<?php
2
3
namespace Srmklive\PayPal\Services;
4
5
use Srmklive\PayPal\Traits\PayPalRequest as PayPalAPIRequest;
6
7
class AdaptivePayments
8
{
9
    use PayPalAPIRequest;
10
11
    /**
12
     * PayPal Processor Constructor.
13
     */
14
    public function __construct()
15
    {
16
        // Setting PayPal API Credentials
17
        $this->setConfig();
18
    }
19
20
    /**
21
     * Set AdaptivePayments API endpoints & options.
22
     *
23
     * @return void
24
     */
25
    public function setAdaptivePaymentsOptions()
26
    {
27
        if ($this->mode == 'sandbox') {
28
            $this->config['api_url'] = 'https://svcs.sandbox.paypal.com/AdaptivePayments';
29
            $this->config['gateway_url'] = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
30
        } else {
31
            $this->config['api_url'] = 'https://svcs.paypal.com/AdaptivePayments';
32
            $this->config['gateway_url'] = 'https://www.paypal.com/cgi-bin/webscr';
33
        }
34
    }
35
36
    /**
37
     * Set Adaptive Payments API request headers.
38
     *
39
     * @return array
40
     */
41
    private function setHeaders()
42
    {
43
        $headers = [
44
            'X-PAYPAL-SECURITY-USERID'      => $this->config['username'],
45
            'X-PAYPAL-SECURITY-PASSWORD'    => $this->config['password'],
46
            'X-PAYPAL-SECURITY-SIGNATURE'   => $this->config['signature'],
47
            'X-PAYPAL-REQUEST-DATA-FORMAT'  => 'JSON',
48
            'X-PAYPAL-RESPONSE-DATA-FORMAT' => 'JSON',
49
            'X-PAYPAL-APPLICATION-ID'       => $this->config['app_id'],
50
        ];
51
52
        return $headers;
53
    }
54
55
    /**
56
     * Set Adaptive Payments API request envelope.
57
     *
58
     * @return array
59
     */
60
    private function setEnvelope()
61
    {
62
        $envelope = [
63
            'errorLanguage' => 'en_US',
64
            'detailLevel'   => 'ReturnAll',
65
        ];
66
67
        return $envelope;
68
    }
69
70
    /**
71
     * Function to perform Adaptive Payments API's PAY operation.
72
     *
73
     * @param array $data
74
     *
75
     * @throws \Exception
76
     *
77
     * @return array
78
     */
79
    public function createPayRequest($data)
80
    {
81
        if (empty($data['return_url']) && empty($data['cancel_url'])) {
82
            throw new \Exception('Return & Cancel URL should be specified');
83
        }
84
85
        $this->setRequestData([
86
            'actionType'        => 'PAY',
87
            'currencyCode'      => $this->currency,
88
            'receiverList'      => [
89
                'receiver'      => $data['receivers'],
90
            ],
91
            'returnUrl'         => $data['return_url'],
92
            'cancelUrl'         => $data['cancel_url'],
93
            'requestEnvelope'   => $this->setEnvelope(),
94
            'feesPayer'         => $data['payer'],
95
        ])->filter(function ($value, $key) use ($data) {
96
            return (($key === 'feesPayer') && empty($value)) ?: $value;
97
        });
98
99
        return $this->doPayPalRequest('Pay');
100
    }
101
102
    /**
103
     * Function to perform Adaptive Payments API's SetPaymentOptions operation.
104
     *
105
     * @param string $payKey
106
     * @param array  $receivers
107
     *
108
     * @return array
109
     */
110
    public function setPaymentOptions($payKey, $receivers)
111
    {
112
        $this->setRequestData([
113
            'requestEnvelope' => $this->setEnvelope(),
114
            'payKey'          => $payKey,
115
        ]);
116
117
        $receiverOptions = collect($receivers)->map(function ($receiver) {
118
            $item = [];
119
120
            $item['receiver'] = [
121
                'email' => $receiver['email'],
122
            ];
123
124
            $item['invoiceData']['item'] = collect($receiver['invoice_data'])->map(function ($invoice) {
125
                return $invoice;
126
            })->toArray();
127
128
            $item['description'] = $receiver['description'];
129
130
            return $item;
131
        })->toArray();
132
133
        $this->post = $this->post->merge([
134
            'receiverOptions' => $receiverOptions
135
        ]);
136
137
        return $this->doPayPalRequest('SetPaymentOptions');
138
    }
139
140
    /**
141
     * Function to perform Adaptive Payments API's GetPaymentOptions operation.
142
     *
143
     * @param string $payKey
144
     * @param bool   $details
145
     *
146
     * @return array
147
     */
148
    public function getPaymentOptions($payKey, $details = false)
149
    {
150
        $operation = ($details) ? 'PaymentDetails' : 'GetPaymentOptions';
151
152
        $this->setRequestData([
153
            'requestEnvelope' => $this->setEnvelope(),
154
            'payKey'          => $payKey,
155
        ]);
156
157
        return $this->doPayPalRequest($operation);
158
    }
159
160
    /**
161
     * Function to perform Adaptive Payments API's PaymentDetails operation.
162
     *
163
     * @param string $payKey
164
     *
165
     * @return array
166
     */
167
    public function getPaymentDetails($payKey)
168
    {
169
        return $this->getPaymentOptions($payKey, true);
170
    }
171
172
    /**
173
     * Get PayPal redirect url for processing payment.
174
     *
175
     * @param string $option
176
     * @param string $payKey
177
     *
178
     * @return string
179
     */
180
    public function getRedirectUrl($option, $payKey)
181
    {
182
        $url = $this->config['gateway_url'].'?cmd=';
183
184
        if ($option == 'approved') {
185
            $url .= '_ap-payment&paykey='.$payKey;
186
        } elseif ($option == 'pre-approved') {
187
            $url .= '_ap-preapproval&preapprovalkey='.$payKey;
188
        }
189
190
        return $url;
191
    }
192
193
    /**
194
     * Create request payload to be sent to PayPal.
195
     *
196
     * @param string $method
197
     */
198
    private function createRequestPayload($method)
199
    {
200
        $this->apiUrl = $this->config['api_url'].'/'.$method;
201
202
        $this->post = $this->post->merge($this->options);
203
    }
204
205
    /**
206
     * Perform PayPal API request & return response.
207
     *
208
     * @throws \Exception
209
     *
210
     * @return \Psr\Http\Message\StreamInterface
211
     */
212
    private function makeHttpRequest()
213
    {
214
        try {
215
            return $this->client->post($this->apiUrl, [
216
                'json'    => $this->post->toArray(),
217
                'headers' => $this->setHeaders(),
218
            ])->getBody();
219
        } catch (\GuzzleHttp\Exception\ClientException $e) {
220
            throw new \Exception(collect($e->getTrace())->implode('\n'));
221
        } catch (\GuzzleHttp\Exception\ServerException $e) {
222
            throw new \Exception(collect($e->getTrace())->implode('\n'));
223
        } catch (\GuzzleHttp\Exception\BadResponseException $e) {
224
            throw new \Exception(collect($e->getTrace())->implode('\n'));
225
        }
226
    }
227
228
    /**
229
     * Function To Perform PayPal API Request.
230
     *
231
     * @param string $method
232
     *
233
     * @throws \Exception
234
     *
235
     * @return array|mixed|\Psr\Http\Message\StreamInterface
236
     */
237
    private function doPayPalRequest($method)
238
    {
239
        // Setup PayPal API Request Payload
240
        $this->createRequestPayload($method);
241
242
        try {
243
            $response = $this->makeHttpRequest();
244
245
            return \GuzzleHttp\json_decode($response, true);
246
        } catch (\Exception $e) {
247
            $message = $e->getMessage();
248
        }
249
250
        return [
251
            'type'      => 'error',
252
            'message'   => $message,
253
        ];
254
    }
255
}
256