Using Secure Pay JavaScript Library

'Direct API with Secure Pay JavaScript Library' allows merchants to integrate to 2C2P Payment Gateway within the merchants' own web page and to encrypt sensitive card input field elements directly on the customer's browser. It provides a seamless and secure payment flow to the customer.

This guide will walk you through the process of implementing SecurePay JavaScript library in your web application, allowing you to collect payment information securely.

Step 1 : Include the required libraries

Import 2C2P Secure Pay JavaScript into the payment page

<head>
<script type="text/javascript" src="https://t.2c2p.com/2C2PFrontEnd/SecurePayment/api/my2c2p.1.7.6.min.js"></script>
</head>

Step 2: Create Your Payment Form

Design a payment form that captures the necessary card information.

<form id="paymentForm" method="POST" action="">
    <div class="form-group">
        <label for="cardnumber">Credit Card Number:</label>
        <input type="text" id="cardnumber" maxlength="19" placeholder="Credit Card Number" data-encrypt="cardnumber" required>
        <span class="PaymentFieldError" id="Error-cardnumber"></span>
    </div>
    
    <div class="form-group">
        <label for="month">Expiry Month :</label>
        <input type="text" id="month" maxlength="2" placeholder="MM" data-encrypt="month" required>
        <span class="PaymentFieldError" id="Error-month"></span>
    </div>
    
    <div class="form-group">
        <label for="year">Expiry Year:</label>
        <input type="text" id="year" maxlength="4" placeholder="YYYY" data-encrypt="year" required>
        <span class="PaymentFieldError" id="Error-year"></span>
    </div>
    
    <div class="form-group">
        <label for="cvv">CVV:</label>
        <input type="text" id="cvv" maxlength="4" placeholder="CVV2/CVC2" autoComplete="off" data-encrypt="cvv" required>
    </div>
    <button type="submit" id="submitBtn">Continue to Payment</button>
</form>

Step 3: Implement the Form Submission Logic

Merchant could use the provided error fields added beside each card information field and handle the form submission and encryption process

<script>
document.addEventListener('DOMContentLoaded', function() {
    var form = document.getElementById('paymentForm');
    
    form.addEventListener('submit', function(e) {
        e.preventDefault();
        ClearFormErrorMessage();
        
        My2c2p.getEncrypted(form, function(formData, errorCode, errorDesc) {
            if (errorCode === 0) {
                // Now you can send the encrypted data to your server
                sendToServer(formData);
            } else {
                DisplayFormErrorMessage(errorCode, errorDesc);
            }
        });
});

function sendToServer(formData) {
    // Create payment request to send backend server
    // Sample request
    const paymentRequest = {
        transactionId: 1017,
        encryptedCardInfo: formData.encryptedCardInfo
    }
    
    // Send data to your server
    fetch('/process-payment', {
        method: 'POST',
        body: paymentRequest
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            window.location.href = '/payment-success';
        } else {
            alert('Payment failed: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('An error occurred while processing your payment.');
    });
}

function DisplayFormErrorMessage(errCode, errDesc) {
        var errControl; 
        switch (errCode) { 
            case 1:
            case 2:
                errControl = document.getElementById('Error-cardnumber');
                break;
            case 3:
            case 4:
            case 8:
            case 9:
            case 11:
                errControl = document.getElementById('Error-month');
                break;
            case 5:
            case 6:
            case 7:
            case 12:
                errControl = document.getElementById('Error-year');
                break;
            case 10:
                errControl = document.getElementById('Error-cvv');
                break;
        }

        if (errControl != undefined) {
            errControl.innerHTML = errDesc;
            var inputField = errControl.previousElementSibling;
            if (inputField) {
                inputField.focus();
            }
        } 
        else { console.log(errDesc + '(' + errCode + ')'); }
    }

    function ClearFormErrorMessage() {
        var errSpans = document.getElementsByClassName('PaymentFieldError');
        for (var i = 0; i < errSpans.length; i++) {
            errSpans[i].innerHTML = "";
        }
    }
});
</script>

Optional Step: Customize the payment page to your own styling

Finally, merchant could use their own styled script to customize the Secure Field elements' look and feel.

<style>
.PaymentFieldError{
	color: red;
	font-style: italic;
	}
</style></style>

Final Step: Handle the Payment Request on your backend server

Merchant will have to create an API endpoint to accept payment request from the frontend. Then, create the payment request to 2C2P.

Direct API Flow

Refer to Payment Token Request and Do Payment API

Complete Code
Copy & Paste the code below to your working file, and put this file in your Web Server.

<!DOCTYPE html>
<html>
<head>
    <title>Payment Form</title>
	<script type="text/javascript" src="https://demo2.2c2p.com/SecurePayment/api/my2c2p.1.7.6.min.js"></script>
</head>
<body>
    <form id="paymentForm" method="POST" action="">
        <div class="form-group">
            <label for="cardnumber">Credit Card Number:</label>
            <input type="text" id="cardnumber" maxlength="19" placeholder="Credit Card Number" data-encrypt="cardnumber" required>
            <span class="PaymentFieldError" id="Error-cardnumber"></span>
        </div>
        
        <div class="form-group">
            <label for="month">Expiry Month :</label>
            <input type="text" id="month" maxlength="2" placeholder="MM" data-encrypt="month" required>
            <span class="PaymentFieldError" id="Error-month"></span>
        </div>
        
        <div class="form-group">
            <label for="year">Expiry Year:</label>
            <input type="text" id="year" maxlength="4" placeholder="YYYY" data-encrypt="year" required>
            <span class="PaymentFieldError" id="Error-year"></span>
        </div>
        
        <div class="form-group">
            <label for="cvv">CVV:</label>
            <input type="text" id="cvv" maxlength="4" placeholder="CVV2/CVC2" autoComplete="off" data-encrypt="cvv" required>
            <span class="PaymentFieldError" id="Error-cvv"></span>
        </div>
        <button type="submit" id="submitBtn">Continue to Payment</button>
    </form>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        var form = document.getElementById('paymentForm');
        
        form.addEventListener('submit', function(e) {
            e.preventDefault(); // Prevent default form submission

            ClearFormErrorMessage();
            
            // Use My2c2p to encrypt the card data
            My2c2p.getEncrypted(form, function(formData, errorCode, errorDesc) {
                if (errorCode === 0) {
                    // Success - card data encrypted
                    console.log("Card data encrypted successfully");
                    
                    // Now you can send the encrypted data to your server
                    sendToServer(formData);
                } else {
                    // Handle validation errors
                    DisplayFormErrorMessage(errorCode, errorDesc);
                    // alert("Error: " + errorDesc);
                }
            });
    });

    function sendToServer(formData) {
        // Create payment request to send backend server
        // Sample request
        const paymentRequest = {
            transactionId: 1017,
            encryptedCardInfo: formData.encryptedCardInfo
        }
        
        // Send data to your server
        fetch('/process-payment', {
            method: 'POST',
            body: paymentRequest
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                window.location.href = '/payment-success';
            } else {
                alert('Payment failed: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('An error occurred while processing your payment.');
        });
    }

    function DisplayFormErrorMessage(errCode, errDesc) {
            var errControl; 
            switch (errCode) { 
                case 1:
                case 2:
                    errControl = document.getElementById('Error-cardnumber');
                    break;
                case 3:
                case 4:
                case 8:
                case 9:
                case 11:
                    errControl = document.getElementById('Error-month');
                    break;
                case 5:
                case 6:
                case 7:
                case 12:
                    errControl = document.getElementById('Error-year');
                    break;
                case 10:
                    errControl = document.getElementById('Error-cvv');
                    break;
            }

            if (errControl != undefined) {
                errControl.innerHTML = errDesc;
                var inputField = errControl.previousElementSibling;
                if (inputField) {
                    inputField.focus();
                }
            } 
            else { console.log(errDesc + '(' + errCode + ')'); }
        }

        function ClearFormErrorMessage() {
            var errSpans = document.getElementsByClassName('PaymentFieldError');
            for (var i = 0; i < errSpans.length; i++) {
                errSpans[i].innerHTML = "";
            }
        }
    });
    </script>

    <style>
        .PaymentFieldError{
        color: red;
        font-style: italic;
        }
    </style>
</body>
</html>