-
Notifications
You must be signed in to change notification settings - Fork 225
/
PaymentMethodGateway.php
359 lines (328 loc) · 11.4 KB
/
PaymentMethodGateway.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
<?php
namespace Braintree;
use InvalidArgumentException;
/**
* Creates and manages Braintree PaymentMethods
*
* For more detailed information on PaymentMethods, see {@link https://developer.paypal.com/braintree/docs/reference/response/payment-method/php our developer docs}. <br />
*/
class PaymentMethodGateway
{
private $_gateway;
private $_config;
private $_http;
// phpcs:ignore PEAR.Commenting.FunctionComment.Missing
public function __construct($gateway)
{
$this->_gateway = $gateway;
$this->_config = $gateway->config;
$this->_config->assertHasAccessTokenOrKeys();
$this->_http = new Http($gateway->config);
}
/**
* Attempts the create operation
* returns a Result on success or an Error on failure
*
* @param array $attribs containing request parameterss
*
* @throws Exception\ValidationError
*
* @return Result\Successful|Result\Error
*/
public function create($attribs)
{
Util::verifyKeys(self::createSignature(), $attribs);
return $this->_doCreate('/payment_methods', ['payment_method' => $attribs]);
}
/**
* Find a PaymentMethod by token
*
* @param string $token payment method unique id
*
* @throws Exception\NotFound
*
* @return CreditCard|PayPalAccount
*/
public function find($token)
{
$this->_validateId($token);
try {
$path = $this->_config->merchantPath() . '/payment_methods/any/' . $token;
$response = $this->_http->get($path);
return PaymentMethodParser::parsePaymentMethod($response);
} catch (Exception\NotFound $e) {
throw new Exception\NotFound(
'payment method with token ' . $token . ' not found'
);
}
}
/**
* Updates the payment method's record
*
* @param string $token payment method identifier
* @param array $attribs containing request parameters
*
* @return Result\Successful|Result\Error
*/
public function update($token, $attribs)
{
Util::verifyKeys(self::updateSignature(), $attribs);
$this->_checkForDeprecatedAttributes($attribs);
return $this->_doUpdate('/payment_methods/any/' . $token, ['payment_method' => $attribs]);
}
/**
* Delete a payment method record
*
* @param string $token payment method identifier
* @param mixed $options containing optional parameters
*
* @return Result
*/
public function delete($token, $options = [])
{
Util::verifyKeys(self::deleteSignature(), $options);
$this->_validateId($token);
$queryString = "";
if (!empty($options)) {
$queryString = "?" . http_build_query(Util::camelCaseToDelimiterArray($options, '_'));
}
return $this->_doDelete('/payment_methods/any/' . $token . $queryString);
}
/**
* Grant a payment method record
*
* See our {@link https://developer.paypal.com/braintree/docs/reference/request/payment-method/grant developer docs} for more info on the Grant API.
*
* @param string $sharedPaymentMethodToken payment method identifier
* @param mixed $attribs containing request parameters
*
* @return Result
*/
public function grant($sharedPaymentMethodToken, $attribs = [])
{
if (is_bool($attribs) === true) {
$attribs = ['allow_vaulting' => $attribs];
}
$options = [ 'shared_payment_method_token' => $sharedPaymentMethodToken ];
return $this->_doGrant(
'/payment_methods/grant',
[
'payment_method' => array_merge($attribs, $options)
]
);
}
/**
* Deletes the version of a granted payment method from the receiving merchant's vault.
*
* See our {@link https://developer.paypal.com/braintree/docs/reference/request/payment-method/revoke developer docs} for more info on the Grant API.
*
* @param string $sharedPaymentMethodToken payment method identifier
*
* @return Result
*/
public function revoke($sharedPaymentMethodToken)
{
return $this->_doRevoke(
'/payment_methods/revoke',
[
'payment_method' => [
'shared_payment_method_token' => $sharedPaymentMethodToken
]
]
);
}
private static function baseSignature()
{
$billingAddressSignature = AddressGateway::createSignature();
$optionsSignature = [
'failOnDuplicatePaymentMethod',
'makeDefault',
'skipAdvancedFraudChecking',
'usBankAccountVerificationMethod',
'verificationAccountType',
'verificationAddOns',
'verificationAmount',
'verificationMerchantAccountId',
'verifyCard',
['paypal' => [
'payee_email',
'payeeEmail',
'order_id',
'orderId',
'custom_field',
'customField',
'description',
'amount',
['shipping' =>
[
'firstName', 'lastName', 'company', 'countryName',
'countryCodeAlpha2', 'countryCodeAlpha3', 'countryCodeNumeric',
'extendedAddress', 'locality', 'postalCode', 'region',
'streetAddress', 'phoneNumber', ['internationalPhone' => ['countryCode', 'nationalNumber']]],
],
]],
];
return [
'billingAddressId',
'cardholderName',
'cvv',
'deviceData',
'expirationDate',
'expirationMonth',
'expirationYear',
'number',
'paymentMethodNonce',
'token',
['options' => $optionsSignature],
['billingAddress' => $billingAddressSignature]
];
}
// phpcs:ignore PEAR.Commenting.FunctionComment.Missing
public static function createSignature()
{
$signature = array_merge(self::baseSignature(), [
'customerId',
'paypalRefreshToken',
CreditCardGateway::threeDSecurePassThruSignature()
]);
return $signature;
}
// phpcs:ignore PEAR.Commenting.FunctionComment.Missing
public static function updateSignature()
{
$billingAddressSignature = AddressGateway::updateSignature();
array_push($billingAddressSignature, [
'options' => [
'updateExisting'
]
]);
$threeDSPassThruSignature = [
'authenticationResponse',
'cavv',
'cavvAlgorithm',
'directoryResponse',
'dsTransactionId',
'eciFlag',
'threeDSecureVersion',
'xid'
];
// NEXT_MAJOR_VERSION Remove venmoSdkPaymentMethodCode
$signature = array_merge(self::baseSignature(), [
'venmoSdkPaymentMethodCode', // Deprecated
['billingAddress' => $billingAddressSignature],
['threeDSecurePassThru' => $threeDSPassThruSignature]
]);
return $signature;
}
private static function deleteSignature()
{
return ['revokeAllGrants'];
}
// phpcs:ignore PEAR.Commenting.FunctionComment.Missing
public function _doCreate($subPath, $params)
{
$fullPath = $this->_config->merchantPath() . $subPath;
$response = $this->_http->post($fullPath, $params);
return $this->_verifyGatewayResponse($response);
}
// phpcs:ignore PEAR.Commenting.FunctionComment.Missing
public function _doGrant($subPath, $params)
{
$fullPath = $this->_config->merchantPath() . $subPath;
$response = $this->_http->post($fullPath, $params);
return $this->_verifyGrantResponse($response);
}
// phpcs:ignore PEAR.Commenting.FunctionComment.Missing
public function _doRevoke($subPath, $params)
{
$fullPath = $this->_config->merchantPath() . $subPath;
$response = $this->_http->post($fullPath, $params);
return $this->_verifyRevokeResponse($response);
}
// phpcs:ignore PEAR.Commenting.FunctionComment.Missing
public function _doUpdate($subPath, $params)
{
$fullPath = $this->_config->merchantPath() . $subPath;
$response = $this->_http->put($fullPath, $params);
return $this->_verifyGatewayResponse($response);
}
// phpcs:ignore PEAR.Commenting.FunctionComment.Missing
public function _doDelete($subPath)
{
$fullPath = $this->_config->merchantPath() . $subPath;
$this->_http->delete($fullPath);
return new Result\Successful();
}
/**
* Generic method for validating incoming gateway responses
*
* Creates a new CreditCard or PayPalAccount object
* and encapsulates it inside a Result\Successful object, or
* encapsulates a Errors object inside a Result\Error
* alternatively, throws an Unexpected exception if the response is invalid.
*/
private function _verifyGatewayResponse($response)
{
if (isset($response['apiErrorResponse'])) {
return new Result\Error($response['apiErrorResponse']);
} elseif (($response)) {
return new Result\Successful(
PaymentMethodParser::parsePaymentMethod($response),
'paymentMethod'
);
} else {
throw new Exception\Unexpected(
'Expected payment method or apiErrorResponse'
);
}
}
private function _verifyGrantResponse($response)
{
if (isset($response['apiErrorResponse'])) {
return new Result\Error($response['apiErrorResponse']);
} elseif (isset($response['paymentMethodNonce'])) {
return new Result\Successful(
PaymentMethodNonce::factory($response['paymentMethodNonce']),
'paymentMethodNonce'
);
} else {
throw new Exception\Unexpected(
'Expected paymentMethodNonce or apiErrorResponse'
);
}
}
private function _verifyRevokeResponse($response)
{
if (isset($response['apiErrorResponse'])) {
return new Result\Error($response['apiErrorResponse']);
} elseif (isset($response['success'])) {
return new Result\Successful();
} else {
throw new Exception\Unexpected(
'Expected success or apiErrorResponse'
);
}
}
/**
* Verifies that a valid payment method identifier is being used
*/
private function _validateId($identifier = null, $identifierType = 'token')
{
if (empty($identifier)) {
throw new InvalidArgumentException(
'expected payment method id to be set'
);
}
if (!preg_match('/^[0-9A-Za-z_-]+$/', $identifier)) {
throw new InvalidArgumentException(
$identifier . ' is an invalid payment method ' . $identifierType . '.'
);
}
}
private function _checkForDeprecatedAttributes($attributes)
{
if (isset($attributes['venmoSdkPaymentMethodCode'])) {
trigger_error('The Venmo SDK integration is Unsupported. Please update your integration to use Pay with Venmo instead.', E_USER_DEPRECATED);
}
}
}