Commit d2c78939 authored by Kostia Bohach's avatar Kostia Bohach Committed by Vadym Abramchuk
Browse files

Issue #3318942 by _shY, abramm: Handle Omise events

parent a53fb5d8
Loading
Loading
Loading
Loading
+56 −3
Original line number Diff line number Diff line
@@ -14,12 +14,14 @@ use Drupal\commerce_payment\Plugin\Commerce\PaymentGateway\OnsitePaymentGatewayB
use Drupal\commerce_price\MinorUnitsConverterInterface;
use Drupal\commerce_price\Price;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\user\UserInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Provides the Omise payment gateway.
@@ -389,7 +391,7 @@ class Omise extends OnsitePaymentGatewayBase implements OmiseInterface {
   * {@inheritdoc}
   */
  public function updateRemotePaymentStatus(PaymentInterface $payment) {
    $this->assertPaymentState($payment, ['new']);
    $this->assertPaymentState($payment, ['new', 'authorization']);

    try {
      $charge = \OmiseCharge::retrieve(
@@ -580,8 +582,59 @@ class Omise extends OnsitePaymentGatewayBase implements OmiseInterface {
   * {@inheritdoc}
   */
  public function onNotify(Request $request) {
    // This may change later if we implement Webhooks support.
    throw new \LogicException('Omise payment gateway does not support Notify method');
    $content = $request->getContent() ? Json::decode($request->getContent()) : [];
    if (
      empty($content)
      || empty($remoteId = $content['data']['id'])
      || empty($status = $content['data']['status'])
    ) {
      return new Response('', 401);
    }

    $payment = $this->entityTypeManager
      ->getStorage('commerce_payment')
      ->loadByRemoteId($remoteId);

    if (!$payment instanceof PaymentInterface) {
      return new Response('', 404);
    }

    $payment->setState($this->getStateByPaymentStatus($status));
    $payment->save();

    return NULL;
  }

  /**
   * Gets the payment state depends on charge status.
   *
   * @param string $status
   *   Charge status.
   *   According to the Omise API we can receive one of those: failed, expired,
   *   pending, reversed or successful.
   *
   * @see https://www.omise.co/charges-api
   *
   * @return string
   *   Returns payment state.
   */
  protected function getStateByPaymentStatus(string $status) {
    switch ($status) {
      case 'successful':
        return 'completed';

      case 'failed':
        return 'authorization_voided';

      case 'expired':
        return 'authorization_expired';

      case 'pending':
        return 'authorization';

      case 'reversed':
        return 'refunded';
    }
  }

  /**