Drupal 8.x module CyberSource payment gateway processor

WordPress migration script that takes JSON values from a Drupal source. The scripts will automatically creates equivalent fields, slugs, taxonomies, slugs and path to ensure that the new migrated content is an exact replica from the source.

<?php

/**
 * @file
 * Contains \Drupal\cud_payment\Controller\APIDirectPaymentController.
 */

namespace Drupal\cud_payment\Controller;

use Drupal\Core\Controller\ControllerBase;

define('HMAC_SHA256', 'sha256');
define('SECRET_KEY', 'secret-key-hash');

class APIDirectPaymentController extends ControllerBase
{

    private function if_request_set(&$value, $default = null)
    {
        return isset($value) ? $value : $default;
    }

    private function sign($params)
    {
        return $this->signData($this->buildDataToSign($params), SECRET_KEY);
    }

    private function signData($data, $secretKey)
    {
        return base64_encode(hash_hmac('sha256', $data, $secretKey, true));
    }

    private function buildDataToSign($params)
    {
        $signedFieldNames = explode(",", $params["signed_field_names"]);
        foreach ($signedFieldNames as $field) {
            $dataToSign[] = $field . "=" . $params[$field];
        }
        return $this->commaSeparate($dataToSign);
    }

    private function commaSeparate($dataToSign)
    {
        return implode(",", $dataToSign);
    }

    public function process_submit_api()
    {

        \Drupal::service('page_cache_kill_switch')->trigger();

        // redirect URL
        // needs to be whitelisted by the CBD Bank Gateway
        // done by the bank's end
        $config = \Drupal::config('cud.settings');

        $output['container'] =
            array(
                '#type' => 'container',
                '#attributes' => array(
                    'class' => 'my-3',
                ),
            );

        $str_table = "";

        $amount = \Drupal::request()->query->get('amount');
        $first_name = \Drupal::request()->query->get('firstname');
        $middle_name = \Drupal::request()->query->get('middlename');
        $last_name = \Drupal::request()->query->get('lastname');
        $email = \Drupal::request()->query->get('email');
        $phone = \Drupal::request()->query->get('phone');
        $redirecturl = \Drupal::request()->query->get('redirecturl');
        $origin = \Drupal::request()->query->get('origin');
        $program = \Drupal::request()->query->get('program');

        if ($origin == "corporate_training") {

            $str_table .= "<tr><td>Type</td><td>Corporate Training</td></tr>";

        }

        /* if ($redirecturl) {
            $str_table .= "<tr><td>Redirect URL</td><td>$redirecturl</td></tr>";
        } */

        if ($amount) {
            $str_table .= "<tr><td>Amount</td><td>" . (string)number_format($amount, 2, ".", ",") . "</td></tr>";
        }

        if ($first_name) {
            $str_table .= "<tr><td>First Name</td><td>$first_name</td></tr>";
        }

        if ($middle_name) {
            $str_table .= "<tr><td>Middle Name</td><td>$middle_name</td></tr>";
        }

        if ($last_name) {
            $str_table .= "<tr><td>Last Name</td><td>$last_name</td></tr>";
        }

        if ($email) {
            $str_table .= "<tr><td>Email</td><td>" . $email . "</td></tr>";
        }

        if ($phone) {
            $str_table .= "<tr><td>Phone</td><td>" . $phone . "</td></tr>";
        }

        if ($program) {
            $str_table .= "<tr><td>Program</td><td>" . $program . "</td></tr>";
        }


        if ($origin) {
            $str_table .= "<tr><td>Source origin</td><td>" . $origin . "</td></tr>";
        }

        $output['container']['table'] =
            array(
                '#type' => 'markup',
                '#markup' => "<div class='info bg-white cud fw-500'>
               <table class='table table-bordered text-dark'>
               <thead>
                    <tr class='table-active bg-secondary text-primary'>
                    <th scope='col'>Field</th>
                    <th scope='col'>Data</th>
                    </tr>
                </thead>$str_table</table>
               </div>",
            );

        $migs_result_form = \Drupal::formBuilder()->getForm('Drupal\cud_payment\Form\SubmitToAPIGatewayForm');

        $output['container']['form'] = $migs_result_form;

        $output['#cache'] = ['max-age' => 0];


        return $output;
    }

    /********************************************************/
    /********************************************************/
    /*******************PROCESS******************************/
    /********************************************************/
    /********************************************************/
    public function process_redirect_completion_page()
    {

        \Drupal::service('page_cache_kill_switch')->trigger();

        // encode xmls chars
        // and gateway
        $config = \Drupal::config('cud.settings');

        $output['prefix'] = array(
            '#type' => 'markup',
            '#prefix' => '<div class="container">',
        );

        $output['container'] =
            array(
                '#type' => 'container',
                '#attributes' => array(
                    'class' => 'container col-none',
                ),
            );

        $output['title']['html'] =
            array(
                '#type' => 'markup',
                '#markup' => "<h1>I'm back here</h1>",
            );

        /* if ($payment_status == 0) {
            $output['title']['html']['status'] =
            array(
                '#type' => 'markup',
                '#markup' => "<div class='position-relative w-25 alert alert-success m-auto'><h1 class='text-align-center'><i class='fa fa-check-circle'><!-- empty --></i></h1><h4 class='text-align-center  mb-0'><strong>" . ucwords($str_payment_status) . "</strong></h4></div><div class='description text-align-center mt-3 pt-3 mb-3'><h5>Registration and Payment successful.</h5><p class='mt-3 mb-3'><strong>You will be receiving receipt and Summer School School information.<br />Check your email.<br /><br />Go back to <a href='/international-summer-school/registration'>Summer School</a> pages</strong></p></div>",
            );
        } else {
            $output['title']['html']['status_red'] =
            array(
                '#type' => 'markup',
                '#markup' => "<div class='position-relative alert w-75 alert-danger m-auto'><h1 class='text-align-center'><i class='fa fa-times-circle'><!-- empty --></i></h1><h4 class='text-align-center  mb-0'><strong>" . ucwords($str_payment_status) . "</strong></h4></div><div class='description text-align-center mt-3 pt-3 mb-3'><h5>Payment not successful.</h5><p class='mt-3 mb-3'><strong>Please retry or contact <a href='mailto:[email protected]'>[email protected]</a> and attach the registration information.<br />Check your email.<br /><br />Go back to <a href='/international-summer-school/registration'>Summer School</a> pages</strong></p></div>",
            );
        } */

        $output['suffix'] = array(
            '#type' => 'markup',
            '#suffix' => '</div>',
        );

        $output['#cache'] = ['max-age' => 0];


        return $output;
    }

    function generateQueryString($key_value)
    {

        $query_string = array();

        foreach ($key_value as $key => $value) {

            $query_string[] = urlencode($key) . '=' . urlencode($value);
        }

        return implode('&', $query_string);
    }

    /********************************************************/
    /********************************************************/
    /*******************CANCEL*******************************/
    /********************************************************/
    /********************************************************/
    public function cybersource_cancel()
    {

        \Drupal::service('page_cache_kill_switch')->trigger();

        $output['prefix'] = array(
            '#type' => 'markup',
            '#prefix' => '<div class="container p-0">',
        );

        $output['container']['title'] =
        array(
            '#type' => 'markup',
            '#markup' => "<h2 class='medium-title text-danger my-3'>Canceled</h2>",
        );

        $output['container']['content'] =
        array(
            '#type' => 'markup',
            '#markup' => "<div class='info my-3'><h3 class='mb-3'>The tranaction was cancelled.</h3><h4>Registration: <a href='/registration'>register <i class='fa fa-long-arrow-right'><!-- empty --></i></a></h4><h4>Contact us: <a href='/contact'>contact  <i class='fa fa-long-arrow-right'><!-- empty --></i></a></h4></div>",
        );


        $output['suffix'] = array(
            '#type' => 'markup',
            '#suffix' => '</div>',
        );

        $output['#cache'] = ['max-age' => 0];


        return $output;

    }

    /********************************************************/
    /********************************************************/
    /*******************RECEIPT******************************/
    /********************************************************/
    /********************************************************/
    public function cybersource_receipt()
    {

        \Drupal::service('page_cache_kill_switch')->trigger();

        $output['prefix'] = array(
            '#type' => 'markup',
            '#prefix' => '<div class="container">',
        );

        $ctr = 0;
        $params = array();

        foreach ($_REQUEST as $name => $value) {
            $params[$name] = $value;

            $output['container'][$ctr] =
                array(
                    '#type' => 'markup',
                    '#markup' => "<div class='d-none info'>" . json_encode($name) . " : " . json_encode($value) . "</div>",
                );

            $ctr++;
        }

        if ($this->if_request_set($_REQUEST["auth_response"]) != null) {
            if ($auth_response = (int) $this->if_request_set($_REQUEST["auth_response"])) {

                $output['container']['title'] =
                    array(
                        '#type' => 'markup',
                        '#markup' => "<h3 class='medium-title text-success text-center mb-3'>Payment successful</h3>",
                    );

                $output['container']['title'] =
                    array(
                        '#type' => 'markup',
                        '#markup' => "<h4 class='medium-title text-center mb-3'>Receipt</h4>",
                    );

                if ($auth_response == 0) {

                    $message = $this->if_request_set($_REQUEST["message"]);
                    $transaction_id = $this->if_request_set($_REQUEST["transaction_id"]);
                    $req_amount = $this->if_request_set($_REQUEST["req_amount"]);
                    $req_bill_to_surname = $this->if_request_set($_REQUEST["req_bill_to_surname"]);
                    $req_bill_to_email = $this->if_request_set($_REQUEST["req_bill_to_email"]);
                    $req_bill_to_forename = $this->if_request_set($_REQUEST["req_bill_to_forename"]);
                    $decision = $this->if_request_set($_REQUEST["decision"]);

                    if (trim($message) != "") {
                        $message = "<p class='text-center'>$message</p>";
                    }
                    if (trim($decision) != "") {
                        $decision = "<h3 class='text-primary text-center'>$decision</h3>";
                    }


                    $table =  "<table class='table table-bordered text-white text-center'>";

                    if (trim($transaction_id) != "") {
                        $table .= "<tr><th>Transaction ID</th><td>$transaction_id</td></tr>";
                    }
                    if (trim($req_bill_to_forename) != "") {
                        $table .= "<tr><th>Firstname</th><td>$req_bill_to_forename</td></tr>";
                    }
                    if (trim($req_bill_to_surname) != "") {
                        $table .= "<tr><th>Surname</th><td>$req_bill_to_surname</td></tr>";
                    }
                    if (trim($req_bill_to_email) != "") {
                        $table .= "<tr><th>Email</th><td>$req_bill_to_email</td></tr>";
                    }
                    if (trim($req_amount) != "") {
                        $table .= "<tr><th>Amount</th><td>$req_amount</td></tr>";
                    }

                    $table .=  "</table>";

                    $signature = "False";

                    if ($this->if_request_set($_REQUEST["signature"])) {
                        if (strcmp($params["signature"], $this->sign($params)) == 0) {
                            $signature = "True";
                        }

                        $output['container']['signature_verified'] =
                        array(
                            '#type' => 'markup',
                            '#markup' => "<div class='d-none info'>" . $signature . "</div>",
                        );
                    }


                    $output['container']["auth_response"] =
                        array(
                            '#type' => 'markup',
                            '#markup' => "<div class='info'><div class='decision'>$decision</div><div class='message'>$message</div><div class='result-table'>$table</table></div>",
                        );
                } else {

                    $output['container']['title'] =
                    array(
                        '#type' => 'markup',
                        '#markup' => "<h3 class='medium-title text-danger text-center mb-3'>Payment not successful</h3>",
                    );


                    $message = $this->if_request_set($_REQUEST["message"]);
                    $transaction_id = $this->if_request_set($_REQUEST["transaction_id"]);
                    $req_amount = $this->if_request_set($_REQUEST["req_amount"]);
                    $req_bill_to_surname = $this->if_request_set($_REQUEST["req_bill_to_surname"]);
                    $req_bill_to_email = $this->if_request_set($_REQUEST["req_bill_to_email"]);
                    $req_bill_to_forename = $this->if_request_set($_REQUEST["req_bill_to_forename"]);
                    $decision = $this->if_request_set($_REQUEST["decision"]);

                    if (trim($message) != "") {
                        $message = "<p class='text-center'>$message</p>";
                    }
                    if (trim($decision) != "") {
                        $decision = "<h3 class='text-primary text-center'>$decision</h3>";
                    }

                    $table =  "<table class='table table-bordered text-white text-center'>";

                    if (trim($transaction_id) != "") {
                        $table .= "<tr><th>Transaction ID</th><td>$transaction_id</td></tr>";
                    }
                    if (trim($req_bill_to_forename) != "") {
                        $table .= "<tr><th>Firstname</th><td>$req_bill_to_forename</td></tr>";
                    }
                    if (trim($req_bill_to_surname) != "") {
                        $table .= "<tr><th>Surname</th><td>$req_bill_to_surname</td></tr>";
                    }
                    if (trim($req_bill_to_email) != "") {
                        $table .= "<tr><th>Email</th><td>$req_bill_to_email</td></tr>";
                    }
                    if (trim($req_amount) != "") {
                        $table .= "<tr><th>Amount</th><td>$req_amount</td></tr>";
                    }

                    $table .=  "</table>";

                    $signature = "False";

                    if ($this->if_request_set($_REQUEST["signature"])) {
                        if (strcmp($params["signature"], $this->sign($params)) == 0) {
                            $signature = "True";
                        }

                        $output['container']['signature_verified'] =
                        array(
                            '#type' => 'markup',
                            '#markup' => "<div class='d-none info'>" . $signature . "</div>",
                        );
                    }


                    $output['container']["auth_response"] =
                    array(
                        '#type' => 'markup',
                        '#markup' => "<div class='info'><div class='decision'>$decision</div><div class='message'>$message</div><div class='result-table'>$table</table></div>",
                    );
                }
            }
        } else {

            $message = $this->if_request_set($_REQUEST["message"]);
            $decision = $this->if_request_set($_REQUEST["decision"]);

            if (trim($message) != "") {
                $message = "<p>$message</p>";
            }
            if (trim($decision) != "") {
                $decision = "<h3 class='text-primary text-center'>$decision</h3>";
            } else {
                $decision = "<h4 class='text-primary text-center'>Something went wrong!</h4>";
            }

            $output['container']['title'] =
                array(
                    '#type' => 'markup',
                    '#markup' => "<h3 class='medium-title text-danger text-center mb-3'>Payment not successful</h3>",
                );

            $output['container']["message"] =
                array(
                    '#type' => 'markup',
                    '#markup' => "<div class='alert-info text-info bg-transparent text-center mb-5'>$decision$message</div>",
                );

            $output['container']["contact"] =
                array(
                    '#type' => 'markup',
                    '#markup' => "<div class='alert-info text-info text-center p-3 mb-5'>Please contact us, if the problem persists. Sorry for the inconvenience.</div>",
                );
        }


        $output['suffix'] = array(
            '#type' => 'markup',
            '#suffix' => '</div>',
        );

        $output['#cache'] = ['max-age' => 0];


        return $output;
    }
}