khalti-1.0.2/src/Controller/KhaltiController.php

src/Controller/KhaltiController.php
<?php

namespace Drupal\khalti\Controller;

use Drupal\commerce_order\Entity\OrderInterface;
use Drupal\commerce_payment\Entity\PaymentInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Url;
use Drupal\khalti\Entity\KhaltiTransaction;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;

/**
 * Defines KhaltiController class.
 */
class KhaltiController extends ControllerBase {

  /**
   * Callback URL handling for Sendinblue API API.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   Request.
   *
   * @return array
   *   Return markup for the page.
   */
  public function payment_success($token) {
    $pidx = \Drupal::request()->query->get('pidx');
    $txnId = \Drupal::request()->query->get('txnId');
    $amount = \Drupal::request()->query->get('amount');
    $total_amount = \Drupal::request()->query->get('total_amount');
    $status = \Drupal::request()->query->get('status');
    $status = strtolower($status);
    $mobile = \Drupal::request()->query->get('mobile');
    $tidx = \Drupal::request()->query->get('tidx');
    $purchase_order_id = \Drupal::request()->query->get('purchase_order_id');
    $purchase_order_name = \Drupal::request()->query->get('purchase_order_name');
    $transaction_id = \Drupal::request()->query->get('transaction_id');

    $khalti_sess = khalti_get_session_data('khalti_sess');

    $get_khalti_payment = $khalti_sess['khalti_payment'];
    $get_khalti_order = $khalti_sess['khalti_order'];
    $get_khalti_mode = $khalti_sess['mode'];
    $get_token = $khalti_sess['token'];
    if ($get_token != $token) {
      return new Response('Invalid token', 403);
    }

    if ($get_khalti_order instanceof OrderInterface && $get_khalti_payment instanceof PaymentInterface) {
      try {
        $message = '';
        // Invoke the custom hook for success message.
        \Drupal::moduleHandler()->invokeAll('khalti_success_message', [&$message]);

        $payment_gateway_plugin = $get_khalti_payment->getPaymentGateway()->getPlugin();
        $configuration = $payment_gateway_plugin->getConfiguration();

        if ($get_khalti_mode == 'live') {
          $secret_key = $configuration['secret_key'] ?? '';
        } else {
          $secret_key = $configuration['test_secret_key'] ?? '';
        }

        $khalti = \Drupal::service('khalti.khalti');

        $khalti->setSecretKey($secret_key);

        if ($get_khalti_mode == 'live') {
          $response = $khalti->validate($pidx, TRUE);
        }
        else {
          $response = $khalti->validate($pidx);
        }

        if ($response) {
          $response_data = json_decode($response);
          $pidx = $response_data->pidx;
          $total_amount = $response_data->total_amount;
          $status = $response_data->status;
          $transaction_id = $response_data->transaction_id;
          $fee = $response_data->fee;
          $refunded = $response_data->refunded;
          $status = strtolower($status);

          $khalti_transaction = KhaltiTransaction::create([
            'transaction_id' => $transaction_id,
            'status' => $status,
            'pidx' => $pidx,
            'order_id' => $get_khalti_order->id(),
            'mode' => $get_khalti_mode,
          ]);
          $khalti_transaction->save();

          switch ($status) {
            case 'completed':
              khalti_change_payment_status_completed($get_khalti_payment, $get_khalti_order);
              if ($message == '') {
                $message = '<strong>Success!</strong> Your payment has been successfully processed.';
              }
              break;

            case 'user canceled':
            case 'expired':
            case 'canceled':
              khalti_change_payment_status_cancelled($get_khalti_order);
              if ($message == '') {
                $message = '<strong>Payment Canceled!</strong> Your transaction has been canceled.';
              }
              break;

            case 'pending':
            case 'initiated':
              khalti_change_payment_status_pending($get_khalti_order);
              if ($message == '') {
                $message = '<strong>Payment Canceled!</strong> Your transaction has been canceled.';
              }
              break;

            default:
              khalti_change_payment_status_cancelled($get_khalti_order);
              if ($message == '') {
                $message = '<strong>Payment Canceled!</strong> Your transaction has been canceled.';
              }
              break;
          }

          \Drupal::messenger()->addMessage($this->t($message));

          khalti_remove_session_data();

          $url = Url::fromRoute('commerce_checkout.form', ['commerce_order' => $get_khalti_order->id()]);

          $response = new RedirectResponse($url->toString());
          // $response->send();
          return $response;
        }
        else {
          $message = "Error: Invalid response from Khalti API.";
          \Drupal::messenger()->addError(t($message));
          log_khalti_messages('alert', $message);
          return $this->redirect_homepage();
        }
      }
      catch (\Exception $e) {
        $message = $e->getMessage();
        \Drupal::messenger()->addError(t($message));
        log_khalti_messages('alert', $message);
        return $this->redirect_homepage();
      }
    }
    else {
      return $this->redirect_homepage();
    }
  }

  /**
   * Callback URL handling for Sendinblue API API.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   Request.
   *
   * @return array
   *   Return markup for the page.
   */
  public function payment_cancel() {
    $get_khalti_order = $this->get_khalti_order();

    if ($get_khalti_order instanceof OrderInterface) {
      khalti_change_payment_status_cancelled($get_khalti_order);
      khalti_remove_session_data();

      $message = '';

      // Invoke the custom hook for failure message.
      \Drupal::moduleHandler()->invokeAll('khalti_failure_message', [&$message]);

      if ($message == '') {
        $message = '<strong>Payment Canceled!</strong> Your transaction has been canceled.';
      }

      \Drupal::messenger()->addMessage($this->t($message));
    }

    return $this->redirect_homepage();
  }

  /**
   * Redirect to homepage.
   */
  public function redirect_homepage() {
    $redirect_url = Url::fromRoute('<front>', [], ['absolute' => TRUE])->toString();
    $response = new RedirectResponse($redirect_url);
    // $response->send();
    return $response;
  }

  /**
   * Route title callback.
   *
   * @param \Drupal\khalti\KhaltiTransactionInterface $khalti_transaction
   *   The khalti_transaction entity.
   *
   * @return string
   *   The khalti_transaction label.
   */
  public function khalti_transaction_title(KhaltiTransaction $khalti_transaction) {
    return $khalti_transaction->label();
  }

}

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

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