Payment.php 13.5 KB
Newer Older
1 2 3 4 5 6
<?php

namespace Drupal\commerce_payment\Entity;

use Drupal\commerce_price\Price;
use Drupal\Core\Entity\ContentEntityBase;
7
use Drupal\Core\Entity\EntityMalformedException;
8
use Drupal\Core\Entity\EntityStorageInterface;
9 10 11 12 13 14 15 16 17
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;

/**
 * Defines the payment entity class.
 *
 * @ContentEntityType(
 *   id = "commerce_payment",
 *   label = @Translation("Payment"),
18
 *   label_collection = @Translation("Payments"),
19 20
 *   label_singular = @Translation("payment"),
 *   label_plural = @Translation("payments"),
21 22 23 24 25 26 27
 *   label_count = @PluralTranslation(
 *     singular = "@count payment",
 *     plural = "@count payments",
 *   ),
 *   bundle_label = @Translation("Payment type"),
 *   bundle_plugin_type = "commerce_payment_type",
 *   handlers = {
28
 *     "access" = "Drupal\commerce_payment\PaymentAccessControlHandler",
29
 *     "event" = "Drupal\commerce_payment\Event\PaymentEvent",
30 31
 *     "list_builder" = "Drupal\commerce_payment\PaymentListBuilder",
 *     "storage" = "Drupal\commerce_payment\PaymentStorage",
32
 *     "storage_schema" = "Drupal\commerce\CommerceContentEntityStorageSchema",
33
 *     "form" = {
34
 *       "operation" = "Drupal\commerce_payment\Form\PaymentOperationForm",
35
 *       "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm",
36
 *     },
37
 *     "views_data" = "Drupal\commerce\CommerceEntityViewsData",
38 39 40 41 42
 *     "route_provider" = {
 *       "default" = "Drupal\Core\Entity\Routing\DefaultHtmlRouteProvider",
 *     },
 *   },
 *   base_table = "commerce_payment",
43
 *   admin_permission = "administer commerce_payment",
44 45 46
 *   field_indexes = {
 *     "remote_id"
 *   },
47 48 49 50 51 52 53
 *   entity_keys = {
 *     "id" = "payment_id",
 *     "bundle" = "type",
 *     "uuid" = "uuid",
 *   },
 *   links = {
 *     "collection" = "/admin/commerce/orders/{commerce_order}/payments",
54
 *     "edit-form" = "/admin/commerce/orders/{commerce_order}/payments/commerce_payment/edit",
55
 *     "delete-form" = "/admin/commerce/orders/{commerce_order}/payments/{commerce_payment}/delete",
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
 *   },
 * )
 */
class Payment extends ContentEntityBase implements PaymentInterface {

  /**
   * {@inheritdoc}
   */
  protected function urlRouteParameters($rel) {
    $uri_route_parameters = parent::urlRouteParameters($rel);
    $uri_route_parameters['commerce_order'] = $this->getOrderId();
    return $uri_route_parameters;
  }

  /**
   * {@inheritdoc}
   */
  public function label() {
    // UIs should use the number formatter to show a more user-readable version.
    return $this->getAmount()->__toString();
  }

  /**
   * {@inheritdoc}
   */
  public function getType() {
    $payment_type_manager = \Drupal::service('plugin.manager.commerce_payment_type');
    return $payment_type_manager->createInstance($this->bundle());
  }

  /**
   * {@inheritdoc}
   */
  public function getPaymentGateway() {
    return $this->get('payment_gateway')->entity;
  }

  /**
   * {@inheritdoc}
   */
  public function getPaymentGatewayId() {
    return $this->get('payment_gateway')->target_id;
  }

100 101 102 103 104 105 106
  /**
   * {@inheritdoc}
   */
  public function getPaymentGatewayMode() {
    return $this->get('payment_gateway_mode')->value;
  }

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
  /**
   * {@inheritdoc}
   */
  public function getPaymentMethod() {
    return $this->get('payment_method')->entity;
  }

  /**
   * {@inheritdoc}
   */
  public function getPaymentMethodId() {
    return $this->get('payment_method')->target_id;
  }

  /**
   * {@inheritdoc}
   */
  public function getOrder() {
    return $this->get('order_id')->entity;
  }

  /**
   * {@inheritdoc}
   */
  public function getOrderId() {
    return $this->get('order_id')->target_id;
  }

  /**
   * {@inheritdoc}
   */
  public function getRemoteId() {
    return $this->get('remote_id')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setRemoteId($remote_id) {
    $this->set('remote_id', $remote_id);
    return $this;
  }

150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
  /**
   * {@inheritdoc}
   */
  public function getRemoteState() {
    return $this->get('remote_state')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setRemoteState($remote_state) {
    $this->set('remote_state', $remote_state);
    return $this;
  }

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
  /**
   * {@inheritdoc}
   */
  public function getAvsResponseCode() {
    return $this->get('avs_response_code')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setAvsResponseCode($avs_response_code) {
    $this->set('avs_response_code', $avs_response_code);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getAvsResponseCodeLabel() {
    return $this->get('avs_response_code_label')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setAvsResponseCodeLabel($avs_response_code_label) {
    $this->set('avs_response_code_label', $avs_response_code_label);
    return $this;
  }

195 196 197 198 199
  /**
   * {@inheritdoc}
   */
  public function getBalance() {
    if ($amount = $this->getAmount()) {
200 201 202 203 204
      $balance = $amount;
      if ($refunded_amount = $this->getRefundedAmount()) {
        $balance = $balance->subtract($refunded_amount);
      }
      return $balance;
205 206 207
    }
  }

208 209 210 211
  /**
   * {@inheritdoc}
   */
  public function getAmount() {
212 213 214
    if (!$this->get('amount')->isEmpty()) {
      return $this->get('amount')->first()->toPrice();
    }
215 216 217 218 219 220 221 222 223 224 225 226 227 228
  }

  /**
   * {@inheritdoc}
   */
  public function setAmount(Price $amount) {
    $this->set('amount', $amount);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getRefundedAmount() {
229 230 231
    if (!$this->get('refunded_amount')->isEmpty()) {
      return $this->get('refunded_amount')->first()->toPrice();
    }
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
  }

  /**
   * {@inheritdoc}
   */
  public function setRefundedAmount(Price $refunded_amount) {
    $this->set('refunded_amount', $refunded_amount);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getState() {
    return $this->get('state')->first();
  }

249 250 251
  /**
   * {@inheritdoc}
   */
252 253
  public function setState($state_id) {
    $this->set('state', $state_id);
254 255 256
    return $this;
  }

257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
  /**
   * {@inheritdoc}
   */
  public function getAuthorizedTime() {
    return $this->get('authorized')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setAuthorizedTime($timestamp) {
    $this->set('authorized', $timestamp);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
275 276 277 278 279 280 281 282 283 284
  public function isExpired() {
    $expires = $this->getExpiresTime();
    return $expires > 0 && $expires <= \Drupal::time()->getRequestTime();
  }

  /**
   * {@inheritdoc}
   */
  public function getExpiresTime() {
    return $this->get('expires')->value;
285 286 287 288 289
  }

  /**
   * {@inheritdoc}
   */
290 291
  public function setExpiresTime($timestamp) {
    $this->set('expires', $timestamp);
292 293 294
    return $this;
  }

295 296 297 298 299 300 301
  /**
   * {@inheritdoc}
   */
  public function isCompleted() {
    return !$this->get('completed')->isEmpty();
  }

302 303 304
  /**
   * {@inheritdoc}
   */
305 306
  public function getCompletedTime() {
    return $this->get('completed')->value;
307 308 309 310 311
  }

  /**
   * {@inheritdoc}
   */
312 313
  public function setCompletedTime($timestamp) {
    $this->set('completed', $timestamp);
314 315 316
    return $this;
  }

317 318 319 320 321 322
  /**
   * {@inheritdoc}
   */
  public function preSave(EntityStorageInterface $storage) {
    parent::preSave($storage);

323 324 325 326 327 328 329 330 331 332 333 334 335 336
    $payment_gateway = $this->getPaymentGateway();
    if (!$payment_gateway) {
      throw new EntityMalformedException(sprintf('Required payment field "payment_gateway" is empty.'));
    }
    // Populate the payment_gateway_mode automatically.
    if ($this->get('payment_gateway_mode')->isEmpty()) {
      $this->set('payment_gateway_mode', $payment_gateway->getPlugin()->getMode());
    }
    // Initialize the refunded amount.
    $refunded_amount = $this->getRefundedAmount();
    if (!$refunded_amount) {
      $refunded_amount = new Price('0', $this->getAmount()->getCurrencyCode());
      $this->setRefundedAmount($refunded_amount);
    }
337
    // Maintain the authorized and completed timestamps.
338 339
    $state = $this->getState()->getId();
    $original_state = isset($this->original) ? $this->original->getState()->getId() : '';
340
    if ($state == 'authorization' && $original_state != 'authorization') {
341 342 343 344 345 346 347
      if (empty($this->getAuthorizedTime())) {
        $this->setAuthorizedTime(\Drupal::time()->getRequestTime());
      }
    }
    if ($state == 'completed' && $original_state != 'completed') {
      if (empty($this->getCompletedTime())) {
        $this->setCompletedTime(\Drupal::time()->getRequestTime());
348
      }
349 350 351
    }
  }

352 353 354 355
  /**
   * {@inheritdoc}
   */
  public function postSave(EntityStorageInterface $storage, $update = TRUE) {
356 357
    parent::postSave($storage, $update);

358 359 360 361
    $order = $this->getOrder();
    if ($order && $this->isCompleted()) {
      $payment_order_updater = \Drupal::service('commerce_payment.order_updater');
      $payment_order_updater->requestUpdate($order);
362 363 364 365 366 367 368 369 370
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function postDelete(EntityStorageInterface $storage, array $entities) {
    parent::postDelete($storage, $entities);

371
    $payment_order_updater = \Drupal::service('commerce_payment.order_updater');
372
    foreach ($entities as $entity) {
373 374 375
      if ($order = $entity->getOrder()) {
        $payment_order_updater->requestUpdate($order);
      }
376 377 378
    }
  }

379 380 381 382 383 384 385 386 387 388 389 390
  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);

    $fields['payment_gateway'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Payment gateway'))
      ->setDescription(t('The payment gateway.'))
      ->setRequired(TRUE)
      ->setSetting('target_type', 'commerce_payment_gateway');

391 392 393 394 395
    $fields['payment_gateway_mode'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Payment gateway mode'))
      ->setDescription(t('The payment gateway mode.'))
      ->setRequired(TRUE);

396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
    $fields['payment_method'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Payment method'))
      ->setDescription(t('The payment method.'))
      ->setSetting('target_type', 'commerce_payment_method')
      ->setReadOnly(TRUE);

    $fields['order_id'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Order'))
      ->setDescription(t('The parent order.'))
      ->setSetting('target_type', 'commerce_order')
      ->setReadOnly(TRUE);

    $fields['remote_id'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Remote ID'))
      ->setDescription(t('The remote payment ID.'))
      ->setSetting('max_length', 255)
      ->setDisplayConfigurable('view', TRUE);

414 415 416 417 418 419
    $fields['remote_state'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Remote State'))
      ->setDescription(t('The remote payment state.'))
      ->setSetting('max_length', 255)
      ->setDisplayConfigurable('view', TRUE);

420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
    $fields['amount'] = BaseFieldDefinition::create('commerce_price')
      ->setLabel(t('Amount'))
      ->setDescription(t('The payment amount.'))
      ->setRequired(TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['refunded_amount'] = BaseFieldDefinition::create('commerce_price')
      ->setLabel(t('Refunded amount'))
      ->setDescription(t('The refunded payment amount.'))
      ->setDisplayConfigurable('view', TRUE);

    $fields['state'] = BaseFieldDefinition::create('state')
      ->setLabel(t('State'))
      ->setDescription(t('The payment state.'))
      ->setRequired(TRUE)
      ->setSetting('max_length', 255)
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'type' => 'list_default',
        'weight' => 0,
      ])
      ->setDisplayConfigurable('view', TRUE)
      ->setSetting('workflow_callback', ['\Drupal\commerce_payment\Entity\Payment', 'getWorkflowId']);

    $fields['authorized'] = BaseFieldDefinition::create('timestamp')
      ->setLabel(t('Authorized'))
      ->setDescription(t('The time when the payment was authorized.'))
      ->setDisplayConfigurable('view', TRUE);

449 450 451 452 453 454 455 456 457
    $fields['expires'] = BaseFieldDefinition::create('timestamp')
      ->setLabel(t('Expires'))
      ->setDescription(t('The time when the payment expires. 0 for never.'))
      ->setDisplayConfigurable('view', TRUE)
      ->setDefaultValue(0);

    $fields['completed'] = BaseFieldDefinition::create('timestamp')
      ->setLabel(t('Completed'))
      ->setDescription(t('The time when the payment was completed.'))
458 459
      ->setDisplayConfigurable('view', TRUE);

460 461 462 463 464 465 466 467 468 469
    $fields['avs_response_code'] = BaseFieldDefinition::create('string')
      ->setLabel(t('AVS response code'))
      ->setDescription(t('The AVS response code.'))
      ->setDisplayConfigurable('view', TRUE);

    $fields['avs_response_code_label'] = BaseFieldDefinition::create('string')
      ->setLabel(t('AVS response code label'))
      ->setDescription(t('The AVS response code label.'))
      ->setDisplayConfigurable('view', TRUE);

470 471 472 473 474 475
    // These fields have been replaced by payment_gateway_mode and completed.
    // They have been temporarily kept for commerce_payment_post_update_2().
    // They are no longer used and will be removed in Commerce 2.0.
    $fields['test'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Test'))
      ->setDescription(t('Whether this is a test payment.'));
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
    $fields['captured'] = BaseFieldDefinition::create('timestamp')
      ->setLabel(t('Captured'))
      ->setDescription(t('The time when the payment was captured.'))
      ->setDisplayConfigurable('view', TRUE);

    return $fields;
  }

  /**
   * Gets the workflow ID for the state field.
   *
   * @param \Drupal\commerce_payment\Entity\PaymentInterface $payment
   *   The payment.
   *
   * @return string
   *   The workflow ID.
   */
  public static function getWorkflowId(PaymentInterface $payment) {
    return $payment->getType()->getWorkflowId();
  }

}