paid_ads-8.x-1.x-dev/src/Controller/PaidController.php

src/Controller/PaidController.php
<?php

namespace Drupal\paid_ads\Controller;

use Drupal\Component\Serialization\Json;
use Drupal\Core\Controller\ControllerBase;
use Drupal\field\Entity\FieldConfig;
use Drupal\paid_ads\Entity\PaidPayment;
use Drupal\paid_ads\PaidService;
use Exception;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Handle payment operation routes.
 */
class PaidController extends ControllerBase {

  private $paidService;

  /**
   * Drupal log channel.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

  /**
   * PaidController constructor.
   *
   * @param \Drupal\paid_ads\PaidService $paidService
   *   Injection PaidService.
   */
  public function __construct(PaidService $paidService) {
    $this->paidService = $paidService;
    $this->logger = $this->getLogger('paid_ads');
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    /* @var $paidService \Drupal\paid_ads\PaidService */
    $paidService = $container->get('paid_ads.service');

    return new static($paidService);
  }

  /**
   * Handle creating a payment route.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   Request from client.
   *
   * @return \Symfony\Component\HttpFoundation\Response
   *   Response as JSON.
   */
  public function createPayment(Request $request) {
    $options = Json::decode($request->get('options'));
    try {
      $this->logger->debug($this->t('Start creating payment'));
      $plugin = $this->paidService->getInstance($request->get('type'));
      $field_id = $options['data_entity_type'] . '.' . $options['data_bundle'] . '.' . $options['data_field'];
      $fieldConfig = FieldConfig::load($field_id);
      $amount = $this->paidService->getAmountByFieldClass($fieldConfig->getSetting('class'), ['field_id' => $field_id]);
      if ($plugin && $amount) {

        $payment = PaidPayment::create()
          ->setPaymentMethod($plugin)
          ->setAmount($amount)
          ->setOptions([
            'onSuccess' => [
              [$fieldConfig->getSetting('class'), 'onSuccess'],
              $options,
            ],
          ]);
        // @todo Saving a entity before requesting PayPal is not really good.
        $payment->save();
        $this->logger->info($this->t('Payment @id created', ['@id' => $payment->getId()]));
        $response = $plugin->onCreatePayment([
          'request' => $request,
          'payment' => $payment,
        ]);
        if ($response->getStatusCode() === 200) {
          $payment->save();
        }
        return $response;
      }
      else {
        $this->logger->error($this->t('Trying to create payment without plugin or amount found for type: @type and options: @options', [
          '@type' => (string) $request->get('type', ''),
          '@options' => (string) $request->get('options', 'None'),
        ]));
      }
    }
    catch (Exception $exception) {
      $this->logger->error($this->t('Payment creation failed with message @msg in @file, @line for type: @type an options: @options', [
        '@msg' => $exception->getMessage(),
        '@file' => $exception->getFile(),
        '@line' => $exception->getLine(),
        '@type' => (string) $request->get('type', ''),
        '@options' => (string) $request->get('options', 'None'),
      ]));
    }

    return $this->sendErrorResponse();
  }

  /**
   * Handle execution payment route.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   Request from client.
   *
   * @return \Symfony\Component\HttpFoundation\Response
   *   Response as JSON.
   */
  public function executePayment(Request $request) {
    // @todo Add validation checks.
    try {
      $this->logger->debug($this->t('Start executing payment'));
      $plugin = $this->paidService->getInstance($request->get('type'));
      if ($plugin) {
        return $plugin->onApprovePayment(['request' => $request]);
      }
    }
    catch (Exception $exception) {
      $this->logger->error($this->t('Payment execution failed with message @msg in @file, @line', [
        '@msg' => $exception->getMessage(),
        '@file' => $exception->getFile(),
        '@line' => $exception->getLine(),
      ]));
    }

    return $this->sendErrorResponse();
  }

  /**
   * Return response with 500 error code.
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   *   Response as JSON with 500 error.
   */
  public function sendErrorResponse() {
    return JsonResponse::create(['status' => 'error'], 500);
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc