Plugin Directory

Changeset 3191185


Ignore:
Timestamp:
11/18/2024 11:48:14 AM (17 months ago)
Author:
ampacash
Message:

Committed user details validations during checkout with VEPRAP

Location:
ampacash-payment-method/trunk
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • ampacash-payment-method/trunk/ampacash-veprap-payment-wp.php

    r3171179 r3191185  
    33 * Plugin Name: AmpaCash Veprap Payment
    44 * Description: AmpaCash Veprap Payment Method for user to pay for merchandise.
    5  * Version: 2.5
     5 * Version: 2.7
    66 * Author: AmpaCash
    77 * License: GPLv2 or later
  • ampacash-payment-method/trunk/js/script.js

    r3171179 r3191185  
    1 
    21setTimeout(function() {
    3 // Ensure the variables are properly defined
    4 var paymentMethodVar = typeof ampaCashVars !== 'undefined' ? ampaCashVars.paymentMethodVar : 'ampacash_veprap';
    5 var isUserLoggedInVar = typeof ampaCashVars !== 'undefined' ? ampaCashVars.isUserLoggedInVar : '';
    6 var merchantIdVar = typeof ampaCashVars !== 'undefined' ? ampaCashVars.merchantIdVar : '';
    7 
    8 // Function to show/hide the order button
    9 function toggleOrderButton(display) {
    10     console.log("place-order button visibility:", display);
    11     document.getElementById("place_order").style.display = display;
    12     document.getElementById("def").style.display = !display;
    13 }
    14 
    15 // Function to validate billing details
    16 function validateBillingDetails() {
    17     console.log("validating...");
    18     var isValid = true;
    19 
    20     // Clear previous errors
    21     jQuery("#ampa-cash-errors").html("");
    22 
    23     // Check all required fields with class "validate-required" and without style="display: none;"
    24     jQuery(".validate-required:visible").each(function () {
    25         var fieldId = jQuery(this).find("input, select, textarea").attr("id");
    26         var fieldValue = jQuery(this).find("input, select, textarea").val();
    27        
    28         // Custom validation for ZIP code format
    29         if (fieldId === "billing_postcode") {
    30             if (!isValidZIP(fieldValue)) {
     2    // Ensure the variables are properly defined
     3    var paymentMethodVar = typeof ampaCashVars !== 'undefined' ? ampaCashVars.paymentMethodVar : 'ampacash_veprap';
     4    var isUserLoggedInVar = typeof ampaCashVars !== 'undefined' ? ampaCashVars.isUserLoggedInVar : '';
     5    var merchantIdVar = typeof ampaCashVars !== 'undefined' ? ampaCashVars.merchantIdVar : '';
     6   
     7    // Function to show/hide the order button
     8    function toggleOrderButton(display) {
     9        console.log("place-order button visibility:", display);
     10        document.getElementById("place_order").style.display = display;
     11        document.getElementById("def").style.display = !display;
     12    }
     13   
     14    // Function to validate billing details
     15    function validateBillingDetails() {
     16        console.log("validating...");
     17        var isValid = true;
     18   
     19        // Clear previous errors
     20        jQuery("#ampa-cash-errors").html("");
     21   
     22        // Check all required fields with class "validate-required" and without style="display: none;"
     23        jQuery(".validate-required:visible").each(function () {
     24            var fieldId = jQuery(this).find("input, select, textarea").attr("id");
     25            var fieldValue = jQuery(this).find("input, select, textarea").val();
     26           
     27            // Custom validation for ZIP code format
     28            if (fieldId === "billing_postcode") {
     29                if (!isValidZIP(fieldValue)) {
     30                    isValid = false;
     31                    var errorMessage = "<div class='wc-block-components-notice-banner is-error' role='alert'><div class='wc-block-components-notice-banner__content'>Billing ZIP Code is not a valid postcode / ZIP.</div></div>";
     32                    jQuery("#ampa-cash-errors").append(errorMessage);
     33                }
     34            }
     35   
     36            if (!fieldValue) {
     37                console.log("invalid fields found...");
    3138                isValid = false;
    32                 var errorMessage = "<div class='wc-block-components-notice-banner is-error' role='alert'><div class='wc-block-components-notice-banner__content'>Billing ZIP Code is not a valid postcode / ZIP.</div></div>";
     39   
     40                // Display the error message
     41                var errorMessage = "<div class='wc-block-components-notice-banner is-error' role='alert'><div class='wc-block-components-notice-banner__content'><strong>" + fieldId + "</strong> is a required field.</div></div>";
    3342                jQuery("#ampa-cash-errors").append(errorMessage);
    3443            }
     44        });
     45   
     46        return isValid;
     47    }
     48   
     49    // Function to validate ZIP code format
     50    function isValidZIP(zip) {
     51        var zipRegex = /^[a-zA-Z0-9]{5,6}$/;
     52        return zipRegex.test(zip);
     53    }
     54   
     55    // Function to check if the user is logged in
     56    function isUserLoggedIn() {
     57        return isUserLoggedInVar;
     58    }
     59   
     60    jQuery(function ($) {
     61        paymentMethodVar = $("input[name='payment_method']:checked").val(); // Get the initially selected payment method
     62        console.log("Get the initially selected payment method", paymentMethodVar);
     63       
     64        // Check local storage for payment success status
     65        if (localStorage.getItem("paymentStatus") === "success") {
     66            document.getElementById("success_def").innerHTML = "Payment Received.";
     67            // toggleOrderButton("block");
     68        } else {
     69            // Hide the order button by default if the payment method is veprap
     70            if (paymentMethodVar === "ampacash_veprap") {
     71                toggleOrderButton("none");
     72                console.log("VEPRAP is selected by default", paymentMethodVar);
     73            }
     74            else {
     75                setTimeout(() => {toggleOrderButton("block")}, 1000);
     76                console.log("Different payment method is selected by default", paymentMethodVar);
     77            }
    3578        }
    36 
    37         if (!fieldValue) {
    38             console.log("invalid fields found...");
    39             isValid = false;
    40 
    41             // Display the error message
    42             var errorMessage = "<div class='wc-block-components-notice-banner is-error' role='alert'><div class='wc-block-components-notice-banner__content'><strong>" + fieldId + "</strong> is a required field.</div></div>";
    43             jQuery("#ampa-cash-errors").append(errorMessage);
    44         }
     79   
     80        // Handle payment method change event
     81        $(document.body).on("change", "input[name='payment_method']", function () {
     82            paymentMethodVar = $(this).val(); // Update the variable when payment method changes
     83                   
     84            console.log("paymentMethodVar: ", paymentMethodVar);
     85            console.log("paymentMethodVar === 'ampacash_veprap'?: ", paymentMethodVar === "ampacash_veprap");
     86            toggleOrderButton(paymentMethodVar === "ampacash_veprap" && $("#success_def").html().trim() === "" ? "none" : "block");
     87        });
     88   
     89        // Handle AmpaCash button hover event (onmouseover)
     90        $(document.body).on("mouseover", "#def a", function () {
     91            // Validate billing details
     92            if (validateBillingDetails() && isUserLoggedIn()) {
     93                // Get the required data from fields
     94                var phone_number = $("#billing_phone").val();
     95                var first_name = $("#billing_first_name").val();
     96                var last_name = $("#billing_last_name").val();
     97                var full_name = first_name + " " + last_name;
     98       
     99                // Prepare the API payload
     100                var apiPayload = {
     101                    lookUpTypes: ["FULL_NAME"],
     102                    phoneNumber: phone_number,
     103                    fullName: full_name
     104                };
     105       
     106                // Make the API call
     107                $.ajax({
     108                    url: "https://api-dev.ampacash.com/user-service/v2/lookupData",
     109                    method: "POST",
     110                    contentType: "application/json",
     111                    headers: {
     112                        "platform": "web",
     113                        "env": "dev"
     114                    },
     115                    data: JSON.stringify(apiPayload),
     116                    success: function (response) {
     117                        console.log("API response:", response);
     118       
     119                        if (response.error === true) {
     120                            var errorMessage = response.errorMsg || "Validation failed. Please check your details.";
     121                            var errorHTML = `<div class='wc-block-components-notice-banner is-error' role='alert'>
     122                                <div class='wc-block-components-notice-banner__content'>${errorMessage}</div>
     123                            </div>`;
     124                            $("#ampa-cash-errors").html(errorHTML);
     125                            $("#def").removeAttr("merchantid"); // Remove merchant ID if validation fails
     126                        } else {
     127                            // If successful, set merchant ID or take other actions
     128                            var merchantId = merchantIdVar;
     129                            $("#def").attr("merchantid", merchantId);
     130                        }
     131                    },
     132                    error: function (xhr, status, error) {
     133                        console.error("API call failed:", error);
     134                        var errorHTML = `<div class='wc-block-components-notice-banner is-error' role='alert'>
     135                            <div class='wc-block-components-notice-banner__content'>There was an issue validating your information. Please try again.</div>
     136                        </div>`;
     137                        $("#ampa-cash-errors").html(errorHTML);
     138                        $("#def").removeAttr("merchantid");
     139                    }
     140                });
     141            } else {
     142                // If validation fails or user is not logged in
     143                $("#def").removeAttr("merchantid");
     144                if (!isUserLoggedIn()) {
     145                    var errorMessage = "<div class='wc-block-components-notice-banner is-error' role='alert'><div class='wc-block-components-notice-banner__content'>You must be logged in to use this payment method.</div></div>";
     146                    jQuery("#ampa-cash-errors").append(errorMessage);
     147                }
     148            }
     149        });       
     150   
     151        // Reset payment status on page load
     152        $(window).on('load', function() {
     153            localStorage.removeItem("paymentStatus");
     154            document.getElementById("success_def").innerHTML = "";
     155           
     156            if ($("input[name='payment_method']:checked").val() !== "ampacash_veprap") {
     157                toggleOrderButton("block");
     158                console.log("Resetting Order button to block");
     159            } else {
     160                toggleOrderButton("none");
     161                console.log("Resetting Order button to none");
     162            }
     163        });
    45164    });
    46 
    47     return isValid;
    48 }
    49 
    50 // Function to validate ZIP code format
    51 function isValidZIP(zip) {
    52     var zipRegex = /^[a-zA-Z0-9]{5,6}$/;
    53     return zipRegex.test(zip);
    54 }
    55 
    56 // Function to check if the user is logged in
    57 function isUserLoggedIn() {
    58     return isUserLoggedInVar;
    59 }
    60 
    61 jQuery(function ($) {
    62     paymentMethodVar = $("input[name='payment_method']:checked").val(); // Get the initially selected payment method
    63165   
    64     // Check local storage for payment success status
    65     if (localStorage.getItem("paymentStatus") === "success") {
    66         document.getElementById("success_def").innerHTML = "Payment Received.";
    67         // toggleOrderButton("block");
    68     } else {
    69         // Hide the order button by default if the payment method is veprap
    70         if (localStorage.getItem("paymentStatus") !== "success" && paymentMethodVar === "ampacash_veprap") {
    71             toggleOrderButton("none");
    72         }
    73     }
    74 
    75     // Handle payment method change event
    76     $(document.body).on("change", "input[name='payment_method']", function () {
    77         paymentMethodVar = $(this).val(); // Update the variable when payment method changes
    78                
    79         console.log("paymentMethodVar: ", paymentMethodVar);
    80         console.log("paymentMethodVar === 'ampacash_veprap'?: ", paymentMethodVar === "ampacash_veprap");
    81         toggleOrderButton(paymentMethodVar === "ampacash_veprap" && $("#success_def").html().trim() === "" ? "none" : "block");
    82     });
    83 
    84     // Handle AmpaCash button hover event (onmouseover)
    85     $(document.body).on("mouseover", "#def a", function () {
    86         if (validateBillingDetails() && isUserLoggedIn()) {
    87             // Get the merchant ID
    88             var merchantId = merchantIdVar;
    89             $("#def").attr("merchantid", merchantId);
     166   
     167    console.log("Script loaded");
     168    document.querySelector('#def').addEventListener("onsuccess", (event) => {
     169        console.log("event lister not initialized...");
     170        if (event.detail.data.data["success"]) {
     171            console.log(event.detail.data.data["message"]);
     172            if (document.getElementById("success_def").innerHTML !== "Payment Received.") {
     173                document.getElementById("success_def").innerHTML = "Payment Received.";
     174                // toggleOrderButton("block");
     175            }
     176            document.getElementById("ampa-cash-errors").style.display = "none";
     177            document.getElementById("error_def").innerHTML = "";
     178   
     179            // Set payment status to success in local storage
     180            localStorage.setItem("paymentStatus", "success");
     181            // Automatically submit the order form
     182            setTimeout(function() {
     183                jQuery('form.checkout').submit();
     184            }, 100);
     185           
    90186        } else {
    91             $("#def").removeAttr("merchantid");
    92             if (!isUserLoggedIn()) {
    93                 var errorMessage = "<div class='wc-block-components-notice-banner is-error' role='alert'><div class='wc-block-components-notice-banner__content'>You must be logged in to use this payment method.</div></div>";
    94                 jQuery("#ampa-cash-errors").append(errorMessage);
     187            console.log("error has been logged: ", event.detail.data.data["message"]);
     188            if (document.getElementById("success_def").innerHTML !== "Payment Received.") {
     189                document.getElementById("success_def").innerHTML = "";
     190                document.getElementById("ampa-cash-errors").style.display = "block";
     191                document.getElementById("error_def").innerHTML = event.detail.data.data["message"];
    95192            }
    96193        }
    97194    });
    98 
    99     // Reset payment status on page load
    100     $(window).on('load', function() {
    101         localStorage.removeItem("paymentStatus");
    102         document.getElementById("success_def").innerHTML = "";
    103        
    104         if ($("input[name='payment_method']:checked").val() !== "ampacash_veprap") {
    105             toggleOrderButton("block");
    106         } else {
    107             toggleOrderButton("none");
    108         }
    109     });
    110 });
    111 
    112 
    113 console.log("Script loaded");
    114 document.querySelector('#def').addEventListener("onsuccess", (event) => {
    115     console.log("event lister not initialized...");
    116     if (event.detail.data.data["success"]) {
    117         console.log(event.detail.data.data["message"]);
    118         if (document.getElementById("success_def").innerHTML !== "Payment Received.") {
    119             document.getElementById("success_def").innerHTML = "Payment Received.";
    120             // toggleOrderButton("block");
    121         }
    122         document.getElementById("ampa-cash-errors").style.display = "none";
    123         document.getElementById("error_def").innerHTML = "";
    124 
    125         // Set payment status to success in local storage
    126         localStorage.setItem("paymentStatus", "success");
    127         // Automatically submit the order form
    128         setTimeout(function() {
    129             jQuery('form.checkout').submit();
    130         }, 100);
    131        
    132     } else {
    133         console.log("error has been logged: ", event.detail.data.data["message"]);
    134         if (document.getElementById("success_def").innerHTML !== "Payment Received.") {
    135             document.getElementById("success_def").innerHTML = "";
    136             document.getElementById("ampa-cash-errors").style.display = "block";
    137             document.getElementById("error_def").innerHTML = event.detail.data.data["message"];
    138         }
    139     }
    140 });
    141 }, 1000);
     195    }, 1000);
     196   
  • ampacash-payment-method/trunk/readme.txt

    r3171179 r3191185  
    44Requires at least: 4.7
    55Tested up to: 6.5
    6 Stable tag: 2.5
     6Stable tag: 2.7
    77Requires PHP: 7.0
    88License: GPLv2 or later
     
    101101== Changelog ==
    102102
     103= 2.7 =
     104* Added error validation: Users must ensure the phone number and name entered match exactly with the details registered in their AmpaCash account.
     105
     106= 2.6 =
     107* Fixed compatibility with other payment plugins.
     108
    103109= 2.5 =
    104110* Fixed compatibility with other payment plugins.
Note: See TracChangeset for help on using the changeset viewer.