Completed
Push — master ( 10a953...06746b )
by Raza
01:55
created

AdaptivePayments::setAdaptivePaymentsOptions()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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