I face this issue when I click on the Pay button Moneris Checkout instance not initialized

I try to integrate the Payment Gateway of moneris using PHP and JSon. But When I click on the Pay button It show the error on console sometime it show moerischeckout is not a function sometime it show different error. I try many method but still face the issue. Now I face this error “Moneris Checkout instance not initialized.”

I have tried many method but always show error on the console. I attach code with my question please tell me where I do a mistake.

This is my code,

<?php
require "inc/mpgClasses.php";

// Check if the form was submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Replace with your Moneris credentials
    $store_id = 'store5'; // Test Store ID
    $api_token = 'yesguy'; // Test API Token
    $token = $_POST['token']; // Token received from Moneris Checkout

    /************************* Transactional Variables ****************************/
    $type = 'purchase';
    $order_id = 'Test' . date("dmy-G:i:s");
    $amount = $_POST['amount']; // Get amount from form
    $pan = $_POST['cardNumber']; // Card number from form
    $expdate = $_POST['expiryDate']; // Expiry date from form
    $crypt = '7'; // Encryption type (for card data)
    $dynamic_descriptor = '123'; // Optional descriptor
    $status_check = 'false'; // For status check; can be set to true if needed

    /*********************** Transactional Associative Array **********************/
    $txnArray = array(
        'type' => $type,
        'order_id' => $order_id,
        'amount' => $amount,
        'pan' => $pan,
        'expdate' => $expdate,
        'crypt_type' => $crypt,
    );

    /**************************** Transaction Object *****************************/
    $mpgTxn = new mpgTransaction($txnArray);

    /****************************** Request Object *******************************/
    $mpgRequest = new mpgRequest($mpgTxn);
    $mpgRequest->setProcCountryCode("CA"); // "US" for sending transaction to US environment
    $mpgRequest->setTestMode(true); // Set to false for production transactions

    /***************************** HTTPS Post Object *****************************/
    $mpgHttpPost = new mpgHttpsPost($store_id, $api_token, $mpgRequest);

    /******************************* Response ************************************/
    $mpgResponse = $mpgHttpPost->getMpgResponse();

    // Process the response
    if ($mpgResponse) {
        echo "<h2>Payment Response:</h2>";
        echo "<p>Card Type: " . $mpgResponse->getCardType() . "</p>";
        echo "<p>Transaction Amount: " . $mpgResponse->getTransAmount() . "</p>";
        echo "<p>Transaction Number: " . $mpgResponse->getTxnNumber() . "</p>";
        echo "<p>Receipt ID: " . $mpgResponse->getReceiptId() . "</p>";
        echo "<p>Transaction Type: " . $mpgResponse->getTransType() . "</p>";
        echo "<p>Reference Number: " . $mpgResponse->getReferenceNum() . "</p>";
        echo "<p>Response Code: " . $mpgResponse->getResponseCode() . "</p>";
        echo "<p>Message: " . $mpgResponse->getMessage() . "</p>";
        echo "<p>Auth Code: " . $mpgResponse->getAuthCode() . "</p>";
        echo "<p>Complete: " . $mpgResponse->getComplete() . "</p>";
    } else {
        echo "<p>Error processing the payment.</p>";
    }
    // Send response data to another server (e.g., your internal logging server)
    $logUrl = 'https://esqa.moneris.com/gateway2/transaction/payment.json'; // Replace with your URL
    $ch = curl_init($logUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($response));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
    ]);
    $logResponse = curl_exec($ch);
    curl_close($ch);
    
    // Optionally, handle the logging server response
    // echo "Logging server response: " . $logResponse;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Moneris Payment Integration</title>
    <script src="https://gatewayt.moneris.com/chktv2/js/chkt_v2.00.js"></script>
</head>
<body>

<h2>Moneris Payment Form</h2>
<form id="paymentForm" method="post">
    <label for="amount">Amount:</label>
    <input type="text" id="amount" name="amount" required><br>
    
    <label for="cardNumber">Card Number:</label>
    <input type="text" id="cardNumber" name="cardNumber" required><br>

    <label for="expiryDate">Expiry Date (MMYY):</label>
    <input type="text" id="expiryDate" name="expiryDate" required><br>

    <label for="cvv">CVV:</label>
    <input type="text" id="cvv" name="cvv" required><br>

    <input type="hidden" id="token" name="token">
    <button type="submit">Pay</button>
</form>

<script>
    let monerisCheckoutInstance;

    // Initialize Moneris Checkout on window load
    window.onload = function () {
        window.onbeforeunload = function (e) 
        {
            const storeId = 'store5'; // Test Store ID
            const apiKey = 'yesguy'; // Test API Key

            // Initialize Moneris Checkout
            monerisCheckoutInstance = monerisCheckout({
                checkoutId: apiKey, // Use the API Key as the checkoutId
                environment: 'qa', // Set to 'qa' for testing, use 'prod' for production
            });
        };
    };

    // Handle the form submission
    document.getElementById('paymentForm').onsubmit = function (e) {
        e.preventDefault();

        if (monerisCheckoutInstance) {
            // Tokenize card data
            monerisCheckoutInstance.tokenize({
                card: {
                    pan: document.getElementById('cardNumber').value,
                    expdate: document.getElementById('expiryDate').value,
                    cvv: document.getElementById('cvv').value
                }
            }, function (response) {
                // Handle token response
                if (response && response.token) {
                    // Set the token to the hidden input field
                    document.getElementById('token').value = response.token;
                    // Now submit the form
                    document.getElementById('paymentForm').submit();
                } else {
                    alert('Tokenization failed. Please check the entered card details.');
                }
            }, function (error) {
                console.error('Checkout error:', error);
                alert('Error during payment process. Please check the console for more details.');
            });
        } else {
            console.error('Moneris Checkout instance not initialized.');
        }
    };
</script>

</body>
</html>