-
Notifications
You must be signed in to change notification settings - Fork 257
/
PaymentGatewayBase.php
405 lines (364 loc) · 12.6 KB
/
PaymentGatewayBase.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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
<?php
namespace Drupal\commerce_payment\Plugin\Commerce\PaymentGateway;
use Drupal\commerce_payment\CreditCard;
use Drupal\commerce_payment\Entity\PaymentInterface;
use Drupal\commerce_payment\Entity\PaymentMethodInterface;
use Drupal\commerce_payment\Exception\HardDeclineException;
use Drupal\commerce_payment\Exception\InvalidRequestException;
use Drupal\commerce_payment\PaymentMethodTypeManager;
use Drupal\commerce_payment\PaymentTypeManager;
use Drupal\commerce_price\Price;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Plugin\PluginBase;
use Drupal\Core\Plugin\PluginWithFormsTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides the base class for payment gateways.
*/
abstract class PaymentGatewayBase extends PluginBase implements PaymentGatewayInterface, ContainerFactoryPluginInterface {
use PluginWithFormsTrait;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The ID of the parent config entity.
*
* Not available while the plugin is being configured.
*
* @var string
*/
protected $entityId;
/**
* The payment type used by the gateway.
*
* @var \Drupal\commerce_payment\Plugin\Commerce\PaymentType\PaymentTypeInterface
*/
protected $paymentType;
/**
* The payment method types handled by the gateway.
*
* @var \Drupal\commerce_payment\Plugin\Commerce\PaymentMethodType\PaymentMethodTypeInterface[]
*/
protected $paymentMethodTypes;
/**
* Constructs a new PaymentGatewayBase object.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\commerce_payment\PaymentTypeManager $payment_type_manager
* The payment type manager.
* @param \Drupal\commerce_payment\PaymentMethodTypeManager $payment_method_type_manager
* The payment method type manager.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, PaymentTypeManager $payment_type_manager, PaymentMethodTypeManager $payment_method_type_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityTypeManager = $entity_type_manager;
if (isset($configuration['_entity_id'])) {
$this->entityId = $configuration['_entity_id'];
unset($configuration['_entity_id']);
}
// Instantiate the types right away to ensure that their IDs are valid.
$this->paymentType = $payment_type_manager->createInstance($this->pluginDefinition['payment_type']);
foreach ($this->pluginDefinition['payment_method_types'] as $plugin_id) {
$this->paymentMethodTypes[$plugin_id] = $payment_method_type_manager->createInstance($plugin_id);
}
$this->pluginDefinition['forms'] += $this->getDefaultForms();
$this->setConfiguration($configuration);
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_type.manager'),
$container->get('plugin.manager.commerce_payment_type'),
$container->get('plugin.manager.commerce_payment_method_type')
);
}
/**
* Gets the default payment gateway forms.
*
* @return array
* A list of plugin form classes keyed by operation.
*/
protected function getDefaultForms() {
$default_forms = [];
if ($this instanceof SupportsStoredPaymentMethodsInterface) {
$default_forms['add-payment-method'] = 'Drupal\commerce_payment\PluginForm\PaymentMethodAddForm';
}
if ($this instanceof SupportsUpdatingStoredPaymentMethodsInterface) {
$default_forms['edit-payment-method'] = 'Drupal\commerce_payment\PluginForm\PaymentMethodEditForm';
}
if ($this instanceof SupportsAuthorizationsInterface) {
$default_forms['capture-payment'] = 'Drupal\commerce_payment\PluginForm\PaymentCaptureForm';
}
if ($this instanceof SupportsVoidsInterface) {
$default_forms['void-payment'] = 'Drupal\commerce_payment\PluginForm\PaymentVoidForm';
}
if ($this instanceof SupportsRefundsInterface) {
$default_forms['refund-payment'] = 'Drupal\commerce_payment\PluginForm\PaymentRefundForm';
}
return $default_forms;
}
/**
* {@inheritdoc}
*/
public function getLabel() {
return $this->pluginDefinition['label'];
}
/**
* {@inheritdoc}
*/
public function getDisplayLabel() {
return $this->configuration['display_label'];
}
/**
* {@inheritdoc}
*/
public function getMode() {
return $this->configuration['mode'];
}
/**
* {@inheritdoc}
*/
public function getSupportedModes() {
return $this->pluginDefinition['modes'];
}
/**
* {@inheritdoc}
*/
public function getJsLibrary() {
$js_library = NULL;
if (!empty($this->pluginDefinition['js_library'])) {
$js_library = $this->pluginDefinition['js_library'];
}
return $js_library;
}
/**
* {@inheritdoc}
*/
public function getPaymentType() {
return $this->paymentType;
}
/**
* {@inheritdoc}
*/
public function getPaymentMethodTypes() {
// Filter out payment method types disabled by the merchant.
return array_intersect_key($this->paymentMethodTypes, array_flip($this->configuration['payment_method_types']));
}
/**
* {@inheritdoc}
*/
public function getDefaultPaymentMethodType() {
$default_payment_method_type = $this->pluginDefinition['default_payment_method_type'];
if (!isset($this->paymentMethodTypes[$default_payment_method_type])) {
throw new \InvalidArgumentException('Invalid default_payment_method_type specified.');
}
return $this->paymentMethodTypes[$default_payment_method_type];
}
/**
* {@inheritdoc}
*/
public function getCreditCardTypes() {
// @todo Allow the list to be restricted by the merchant.
return array_intersect_key(CreditCard::getTypes(), array_flip($this->pluginDefinition['credit_card_types']));
}
/**
* {@inheritdoc}
*/
public function calculateDependencies() {
return [];
}
/**
* {@inheritdoc}
*/
public function getConfiguration() {
return $this->configuration;
}
/**
* {@inheritdoc}
*/
public function setConfiguration(array $configuration) {
$this->configuration = NestedArray::mergeDeep($this->defaultConfiguration(), $configuration);
// Providing a default for payment_metod_types in defaultConfiguration()
// doesn't work because NestedArray::mergeDeep causes duplicates.
if (empty($this->configuration['payment_method_types'])) {
$this->configuration['payment_method_types'][] = 'credit_card';
}
}
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
$modes = array_keys($this->getSupportedModes());
return [
'display_label' => $this->pluginDefinition['display_label'],
'mode' => $modes ? reset($modes) : '',
'payment_method_types' => [],
];
}
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$modes = $this->getSupportedModes();
$payment_method_types = array_map(function ($payment_method_type) {
return $payment_method_type->getLabel();
}, $this->paymentMethodTypes);
$form['display_label'] = [
'#type' => 'textfield',
'#title' => $this->t('Display name'),
'#description' => t('Shown to customers during checkout.'),
'#default_value' => $this->configuration['display_label'],
];
if (count($modes) > 1) {
$form['mode'] = [
'#type' => 'radios',
'#title' => $this->t('Mode'),
'#options' => $modes,
'#default_value' => $this->configuration['mode'],
'#required' => TRUE,
];
}
else {
$mode_names = array_keys($modes);
$form['mode'] = [
'#type' => 'value',
'#value' => reset($mode_names),
];
}
if (count($payment_method_types) > 1) {
$form['payment_method_types'] = [
'#type' => 'checkboxes',
'#title' => $this->t('Payment method types'),
'#options' => $payment_method_types,
'#default_value' => $this->configuration['payment_method_types'],
'#required' => TRUE,
];
}
else {
$form['payment_method_types'] = [
'#type' => 'value',
'#value' => $payment_method_types,
];
}
return $form;
}
/**
* {@inheritdoc}
*/
public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {}
/**
* {@inheritdoc}
*/
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
if (!$form_state->getErrors()) {
$values = $form_state->getValue($form['#parents']);
$values['payment_method_types'] = array_filter($values['payment_method_types']);
$this->configuration['display_label'] = $values['display_label'];
$this->configuration['mode'] = $values['mode'];
$this->configuration['payment_method_types'] = array_keys($values['payment_method_types']);
}
}
/**
* {@inheritdoc}
*/
public function buildPaymentOperations(PaymentInterface $payment) {
$payment_state = $payment->getState()->value;
$operations = [];
if ($this instanceof SupportsAuthorizationsInterface) {
$operations['capture'] = [
'title' => $this->t('Capture'),
'page_title' => $this->t('Capture payment'),
'plugin_form' => 'capture-payment',
'access' => $payment_state == 'authorization',
];
}
if ($this instanceof SupportsVoidsInterface) {
$operations['void'] = [
'title' => $this->t('Void'),
'page_title' => $this->t('Void payment'),
'plugin_form' => 'void-payment',
'access' => $payment_state == 'authorization',
];
}
if ($this instanceof SupportsRefundsInterface) {
$operations['refund'] = [
'title' => $this->t('Refund'),
'page_title' => $this->t('Refund payment'),
'plugin_form' => 'refund-payment',
'access' => in_array($payment_state, ['capture_completed', 'capture_partially_refunded']),
];
}
return $operations;
}
/**
* Asserts that the payment state matches one of the allowed states.
*
* @param \Drupal\commerce_payment\Entity\PaymentInterface $payment
* The payment.
* @param string[] $states
* The allowed states.
*
* @throws \InvalidArgumentException
* Thrown if the payment state does not match the allowed states.
*/
protected function assertPaymentState(PaymentInterface $payment, array $states) {
$state = $payment->getState()->value;
if (!in_array($state, $states)) {
throw new \InvalidArgumentException(sprintf('The provided payment is in an invalid state ("%s").', $state));
}
}
/**
* Asserts that the payment method is neither empty nor expired.
*
* @param \Drupal\commerce_payment\Entity\PaymentMethodInterface $payment_method
* The payment method.
*
* @throws \InvalidArgumentException
* Thrown when the payment method is empty.
* @throws \Drupal\commerce_payment\Exception\HardDeclineException
* Thrown when the payment method has expired.
*/
protected function assertPaymentMethod(PaymentMethodInterface $payment_method = NULL) {
if (empty($payment_method)) {
throw new \InvalidArgumentException('The provided payment has no payment method referenced.');
}
if ($payment_method->isExpired()) {
throw new HardDeclineException('The provided payment method has expired');
}
}
/**
* Asserts that the refund amount is valid.
*
* @param \Drupal\commerce_payment\Entity\PaymentInterface $payment
* The payment.
* @param \Drupal\commerce_price\Price $refund_amount
* The allowed states.
*
* @throws \Drupal\commerce_payment\Exception\InvalidRequestException
* Thrown when the refund amount is larger than the payment balance.
*/
protected function assertRefundAmount(PaymentInterface $payment, Price $refund_amount) {
$balance = $payment->getBalance();
if ($refund_amount->greaterThan($balance)) {
throw new InvalidRequestException(sprintf("Can't refund more than %s.", $balance->__toString()));
}
}
}