I am trying to integrate a payment system into my Ionic/Angular android app and I cannot figure out how to use the JavaScript script they sent me that is supposed to be used to create the payment frame.
I have linked the js file in the angular.json file. But what I cannot figure out is how to actually use the script in my component.
I have already tried adding a typings.d.ts to the src folder. In which I added:
declare let ozow: any;
ozow being the function that is being exported, I then proceeded to add:
import * as variable from ozow
but this also did not work.
I also tried adding the following to my component:
declare let ozow:any
but that also did not work.
Here is the javascript file I am trying to make use of in my angular project:
var ozow = (function(e, t, a) {
var n = e.addEventListener ? "addEventListener" : "attachEvent",
r = "/payment/iframeredirect?redirecturl=",
o = "Payment could not be completed, please contact the site administrator";
function l(e) {
return (
e.CancelUrl &&
e.CancelUrl.length > 0 &&
(e.CancelUrl = r + encodeURI(e.CancelUrl)),
e.ErrorUrl &&
e.ErrorUrl.length > 0 &&
(e.ErrorUrl = r + encodeURI(e.ErrorUrl)),
e.SuccessUrl &&
e.SuccessUrl.length > 0 &&
(e.SuccessUrl = r + encodeURI(e.SuccessUrl)),
e
);
}
return (
(0, e[n])(
"attachEvent" == n ? "onmessage" : "message",
function(a) {
if (
a.data &&
a.data.event &&
("ozowMessage" == a.data.event || "ozowResize" == a.data.event)
)
if ("ozowMessage" == a.data.event) {
var n = Object.keys(a.data.postData)
.map(function(e) {
return (
encodeURIComponent(e) +
"=" +
encodeURIComponent(a.data.postData[e])
);
})
.join("&");
e.location =
a.data.url +
(-1 == a.data.url.indexOf("?") ? "?" : "&") +
(n || {});
} else
"ozowResize" == a.data.event &&
(t.getElementById("paymentFrame").style.height =
a.data.height + "px");
},
!1
),
function() {
var e = this;
(e.createPaymentFrame = function(e, a, n) {
if (!e || "" == e || 0 == e.length)
return (
console.log(
"The createPaymentFrame method parameter elementSelector cannot be empty or null."
),
void alert(o)
);
if (!a || "" == a || 0 == a.length)
return (
console.log(
"The createPaymentFrame method parameter paymentUrl cannot be empty or null."
),
void alert(o)
);
if (t.getElementById("paymentFrame")) {
var r = t.getElementById("paymentFrame");
r.parentNode.removeChild(r);
}
if ("object" == typeof n) {
l(n),
(a =
a +
"?viewName=JsInjection&" +
Object.keys(n)
.map(function(e) {
return encodeURIComponent(e) + "=" + encodeURIComponent(n[e]);
})
.join("&"));
var i = t.createElement("iframe");
i.setAttribute("id", "paymentFrame"),
i.setAttribute("src", a),
i.setAttribute("frameborder", "0"),
i.setAttribute("scrolling", "no"),
i.setAttribute("height", "100%"),
i.setAttribute("width", "100%"),
(i.style.overflow = "hidden"),
(i.style.height = "100%"),
(i.style.width = "100%"),
t.getElementById(e).appendChild(i);
} else
console.log(
"The createPaymentFrame method expects a JSON object for the postData parameter."
),
alert(o);
}),
(e.createPaymentModal = function(e, a) {
if (!e || "" == e || 0 == e.length)
return (
console.log(
"The createPaymentModal method parameter paymentUrl cannot be empty or null."
),
void alert(o)
);
if (t.getElementById("paymentFrame")) {
var n = t.getElementById("paymentFrame");
n.parentNode.removeChild(n);
}
if ("object" == typeof a) {
l(a),
(e =
e +
"?viewName=JsPopup&" +
Object.keys(a)
.map(function(e) {
return (
encodeURIComponent(e) + "=" + encodeURIComponent(a[e])
);
})
.join("&"));
var r = t.createElement("iframe");
r.setAttribute("id", "paymentFrame"),
r.setAttribute("src", e),
r.setAttribute("frameborder", "0"),
r.setAttribute("scrolling", "no"),
(r.style.position = "fixed"),
(r.style.left = "0"),
(r.style.right = "0"),
(r.style.bottom = "0"),
(r.style.top = "0"),
(r.style.width = "100%"),
(r.style.height = "175%"),
t.body.appendChild(r);
} else
console.log(
"The createPaymentModal method expects a JSON object for the postData parameter."
),
alert(o);
}),
(e.cancelFramePayment = function() {
t.getElementById("paymentFrame").contentWindow.postMessage({
event: "ozowCancelPayment"
},
"*"
);
});
}
);
})(window, document);
Please note this is a file that was sent to me by them directly. The function that the instructions said to call is ozow.createPaymentFrame but I cannot get to the point where I can successfully call this function.
Below are the instructions found in the README.md
1. Add a container element onto your page and assign it a unique id value, i.e. a div etc., this element will be the container for the Ozow payment iframe.
Eg. <div id="paymentContainer"></div>
2. Add a trigger element onto your page and assign it a unique id value, i.e. a radio button, button etc., the element will be a option that displays pay using Ozow and will also trigger the Ozow payment frame.
Eg. <input type="radio" id="payUsingOzow" value="Ozow"> Ozow
3. Add cancel element onto your your page and assign it a unique id value, i.e. button etc., this element will be used to cancel payment using the Ozow payment frame.
Eg. <input type="button" id="cancelOzowPayment" name="cancelOzowPayment" value="Cancel Payment">
4. Inside an existing or new JavaScript script block on your page instantiate the ozow jsintegration module and assign it to a variable.
Eg. <script>
var ozow = new Ozow();
</script>
5. Create an event listener for the trigger element and add code inside the event listener to load the Ozow payment frame, i.e. onclick, onchange etc.
Eg. JavaScript: trigger_element_id.onclick = function(){
var containerElement = document.getElementById('container_element_id'); //The container element where Ozow payment frame will be loaded
var paymentUrl = 'https://pay.ozow.com/'; //The URL to process Ozow payments
var postData = {}; //The form data, which should contain all the required Ozow post variables, serialized as JSON object
ozow.createPaymentFrame(containerElement, paymentUrl, postData); //The method that initiate loading the Ozow payment frame
}; or
jQuery: $('trigger_element_id').click(function(){
var containerElement = $('container_element_id'); //The container element where Ozow payment frame will be loaded
var paymentUrl = 'https://pay.ozow.com/'; //The URL to process Ozow payments
var postData = {}; //The form data, which should contain all the required Ozow post variables, serialized as JSON object
ozow.createPaymentFrame(containerElement, paymentUrl, postData); //The method that initiate loading the Ozow payment frame
});
6. Create event listener for the cancel element and add code inside the event listener to cancel the Ozow payment, i.e. onclick, onchange etc.
Eg. JavaScript: cancel_element_id.onclick = function(){
ozow.cancelFramePayment(); //The method that will call and instruct Ozow to cancel the payment
}; or
jQuery: $('cancel_element_id').click(function(){
ozow.cancelFramePayment(); //The method that will call and instruct Ozow to cancel the payment
});
Thank you in adavnce for your support.
Additonal Notes:
It is a javascript runtime error and not a typescript compilation error
The error I am getting is that ozow.createPaymentFrame is not a function
I added the js script to the angular.json file. Below is the entire script section from the angular.json file
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"./src/assets/js/ipay-noredirect-1.0.min.js"
],
Please note I also tried :
"src/assets/js/ipay-noredirect-1.0.min.js"
I have a static class with only static method written in javascript. The pourpose of the calss and the method is to be a callback container for a certain kind of ajax call.
From the HTML page, sometimes an ajax call is raised and the static method of static class described above, is passed as callback argument.
All work just fine, i also remeber to have debugged the callback previously, but after the last chrome update, even if i can debug the callback, i can't see variable value.
I can't access variable value (when a breackpoint in the static callback is hit, so in the same scope of breakpoint) with the console nor with the watch.
This is the callback class with static method (it's a bit triky, but i prefer not simplify it because maybe the problem reside in the callback code)
/**
* List of defaults callback
* */
class CallbackDefaults {
/**
* Callback used to update price of priced articles
* #param {object} data Page of ArticleDto with actual prices
*/
static priceUpdateCallback = function (data) {
var callbackSource = "getPricesAndStock_callback";
try {
if (!data || data.Success == false || !data.ReturnData || !data.ReturnData.PageContent && data.ReturnData.PageContent.length > 0)
return;
for (var index = 0; index < data.ReturnData.PageContent.length; index++) {
var currentArticle = data.ReturnData.PageContent[index];
var item = document.querySelector(".cgi-priced[ref-code='" + currentArticle.Code + "']");
if (item && currentArticle && currentArticle.Attributes && currentArticle.Attributes.PriceData && currentArticle.Attributes.PriceData.TaxedPrice) {
var priceData = currentArticle.Attributes.PriceData;
var finalPrice = globals.isVatIncluded ? priceData.TaxedPrice : priceData.CalculatedPrice;
let precetageBadge = item.querySelector(".discount-percentage") || { textContent: "" };
let originalPrice = item.querySelector(".original-price") || { textContent: "" };
let discountedPrice = item.querySelector(".discounted-price") || { textContent: "" };
let buyButton = item.querySelector(".buy") || { disabled: false };
var percentage = globals.trustAS400Perc ?
finalPrice.DiscountPercentage :
finalPrice.CalculatedDiscountPercentage;
var percentageString = globals.trustAS400Perc ?
finalPrice.DiscountPercAsString :
finalPrice.CalculatedDiscountPercAsString;
if (!percentage || percentage <= 0)
precetageBadge?.classList?.add("d-none");
else
{
if (precetageBadge?.classList?.contains("d-none"))
precetageBadge?.classList?.remove('d-none');
precetageBadge.textContent = percentageString || "";
}
if (finalPrice.NetPriceAsStringWithCurrency == finalPrice.GrossPriceAsStringWithCurrency)
originalPrice?.classList?.add("d-none");
else
{
originalPrice.textContent = finalPrice.GrossPriceAsStringWithCurrency || "";
}
if (finalPrice.NetPriceAsStringWithCurrency)
discountedPrice.textContent = finalPrice.NetPriceAsStringWithCurrency || "";
else
buyButton.disabled = true;
//update quantity limit
var inSpinner = $(item).find("input[meta=original]");
if (inSpinner && inSpinner.length == 1) {
var updatedQuantity = currentArticle?.Attributes?.StockInformation?.AvailableQuantityFromCgi;
if (updatedQuantity && updatedQuantity > 0) {
inSpinner.inputSpinner("destroy");
inSpinner[0].max = updatedQuantity;
inSpinner.inputSpinner(globals.inputSpinnerConf);
}
}
}
}
}
catch (callbackErr) {
ClientLogManager.logError(callbackSource, callbackErr);
Toaster.getToast("tstTemplatePriceError");
}
};
}
In JQuery ajax success function i call the callback in the following way :
success: function (data) {
try
{
CallbackDefaults.priceUpdateCallback(data);
}
catch (callErr) {
ClientLogManager.logError(source, callErr)
}
}
When i place a breack point into priceUpdateCallback, for example on the following line :
var callbackSource = "getPricesAndStock_callback";
And the run code, the breakpoint will be hit, but i can't see the actual value of 'callbackSource' variable.
I can't get the value hovering, placing the variable in the watch or writing it into the console.
If i try to access the variable through console i get this error :
VM255:1 Uncaught ReferenceError: callbackSource is not defined
at eval (eval at priceUpdateCallback (CallbackDefaults.js:1:1), <anonymous>:1:1)
at priceUpdateCallback (CallbackDefaults.js:13:30)
at Object.success (ConnectionManager.js:169:25)
at c (jquery-3.6.0.min.js:2:28327)
at Object.fireWith [as resolveWith] (jquery-3.6.0.min.js:2:29072)
at l (jquery-3.6.0.min.js:2:79901)
at XMLHttpRequest.<anonymous> (jquery-3.6.0.min.js:2:82355)
I can't understand why, because i remember to have debugged that function before, and seems strange that the new chrome version just introduce a so blatant bug.
--Edit :
i am using Chrome 98.0.4758.102 (Official Build) (64-bit)
I've looked through various similar questions but honestly I don't understand any of the answers (such as they are) in order to apply any of them to what I've written. I'd really appreciate some help as I'm extremely new to this and I'm very lost!
I'm attempting to update an existing page used by moderators for clearing created data as it comes in from users. It uses server side events to check for new items, the old version uses regular forms but the page takes too long to refresh after submitting data. I'm trying to use to set the form data in the background without the need for a refresh but I'm struggling to get the event listeners to attach to the visual elements. They are created dynamically from the event source data. Visually the output looks how I want it to, but it's not behaving as it needs to. One response to a similar-ish question said don't trust the console log, it could be working, but it definitely isn't, the process on the receiving end is a copy of the existing form handler for the old page, so I know that works.
I'm unsure if it's a syntax error or if I need a different approach, the errors I'm getting look like this - it can't find the element I want it to attach the script to:
Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
at :1:37
at EventSource.source.onmessage (MOD.php:39)
This is what I've written on the receiving page:
window.onload = function() {
var last = "";
var lastqueue = "";
var source = new EventSource("MOD-data.php");
source.onmessage = function(event) {
var mydata = event.data;
var data = mydata.split('&&');
var upddate = (data[0]);
var queuedata = (data[1]);
if (mydata != last) {
last = mydata;
if (queuedata != lastqueue) {
var Qdata = queuedata.split('||');
for (let i = 0; i < Qdata.length; i++) {
var itmdata = Qdata[i].split('.');
var itmID = "Q" +(itmdata[0]);
var exists = document.getElementById(itmID);
if (exists === null) {
var itmclass = (itmdata[1]);
var itmbg = (itmdata[2]);
var itmwho = (itmdata[3]);
var itmimg = (itmdata[4]);
var rewbox = "<div id=\"" + itmID + "\" class=\"Qitm " + itmclass + "\" style=\"background:#" + itmbg + "\">" + itmwho + "<input type=\"image\" class=\"rew\" name=\"submit\" src=\"/web/rewards/" + itmimg + ".png\"></div>";
document.getElementById("Qcon").innerHTML += "" + rewbox + "";
var newScript = document.createElement("script");
var inlineScript = document.createTextNode("document.getElementById(" + itmID + ").addEventListener(\"click\", Qclear, true);function Qclear() {\$.ajax({type: \"POST\",url: \"MOD-queue-clear.php\", data: \"timestamp=" + itmID + "\"})}");
newScript.append(inlineScript);
document.getElementById(itmID).appendChild(newScript);
};
};
lastqueue = queuedata;
};
document.getElementById("debug").innerHTML = "<!--" + queuedata + "-->";
};
};
};
Okay, so I'm fairly new to javascript and I'm working on the front-end of a webapplication for my internship, and this just utterly baffles me.
I have a select and an input element, both of which feed into a message model for a database Procedure Call through .POST(). I've done this in other scripts in the project, but here it won't work no matter how I try to assign the values.
Here's the code:
var cctOldSelect = document.getElementById("ConceptToCopy");
var cctOld = cctOldSelect.options[cctOldSelect.selectedIndex].value;
var cctNew = document.getElementById('NewConceptName').value;
console.log("cctOld: " + cctOld + "; cctNew: " + cctNew);
if (cctOld !== "" && cctNew !== "") {
console.log("model creation started.");
var model = {
p_cct_code_old: cctOldSelect.options[cctOldSelect.selectedIndex].value,
p_cct_code_new: document.getElementById('NewConceptName').value,
p_specialty_layout: null
};
console.log("model creation ended.");
}
console.log("cctOld model: " + model.cctOld + "; cctNew model: " + model.cctNew);
output:
cctOld: 1020H; cctNew: 1021H
model creation started.
model creation ended.
cctOld model: undefined; cctNew model: undefined
I've tried multiple ways:
p_cct_code_Old: $scope.<ElementID> //both with and without .value
p_cct_code_Old: document.getElementById(<ElementID>)
var cctOld = document.getElementById(<ElementID>); p_cctOld: cctOld
None of which work. Why won't it assign a value?
The problem in this case is that you create a new object called "model" and with two attributes called "p_cct_code_old" and "p_cct_code_new", then you are trying to access two attributes called "cctOld" and "cctNew" out of scope.
The JS interpreter when you are trying to access a non existing attributes do not throw an error, instead he return an undefined value.
The thing that I suggest to make the things work is:
var model = {};
var cctOldSelect = document.getElementById("ConceptToCopy");
var cctOld = cctOldSelect.options[cctOldSelect.selectedIndex].value;
var cctNew = document.getElementById('NewConceptName').value;
console.log("cctOld: " + cctOld + "; cctNew: " + cctNew);
if (cctOld !== "" && cctNew !== "") {
console.log("model creation started.");
model.p_cct_code_old = cctOldSelect.options[cctOldSelect.selectedIndex].value;
model.p_cct_code_new = document.getElementById('NewConceptName').value;
model.p_specialty_layout: null;
console.log("model creation ended.");
}
console.log("cctOld model: " + model.p_cct_code_old + "; cctNew model: " + model.p_cct_code_new);
Tell me if this solution helped you !
At the moment I'm facing a javascript problem. This is the javascript code:
$(document).ready(function() {
/*
createNewTodo("_OPDRACHT_", "_PRIO_", "_DONE_");
_OPDRACHT_ = wat er gedaan met worden.
_PRIO_ = prioriteit 1-5 (1 is hoogste, 5 is laagste)
_DONE_ = uitgevoerd 1-2 (1 is nee, 2 is ja
*/
function todo(opdracht,prio,done) {
this.opdracht = opdracht;
this.prio = prio;
this.done = done;
}
function createNewTodo(opdracht,prio,done) {
var createdTodo = new todo(opdracht,prio,done);
if ( localStorage.todoCount == undefined ) {
localStorage.setItem('todoCount', 0)
}
var todoSize = parseInt(localStorage.todoCount) + 1;
commitToStorage(todoSize,createdTodo);
}
function addList(){
var val = $('#name').val();
var tjap = createNewTodo(val,"1","1");
}
function commitToStorage(objectCount,newObject) {
var item = + objectCount;
localStorage.setItem('todoCount', objectCount);
localStorage.setItem(item, JSON.stringify(newObject));
}
var todoCount = localStorage.getItem('todoCount');
for (i=1;i<=todoCount;i++)
{
var number = parseInt(i) + 1;
var todo = jQuery.parseJSON(localStorage.getItem(+ i));
createMarkup(todo);
}
function createMarkup(todo) {
$('ul#items').append(
"<li>" +
todo.opdracht + " " +
"</li>"
);
}
$('#add-btn').click(addList);
});
When I click on the add-btn it will insert a item in localstorage with a array of values. Everything is working fine until I refresh the page. At the first time I can add as many items in localstorage without a problem but when I try to add items after refreshing the page I get the following error: Uncaught TypeError: object is not a function. Been searching a lot on the internet but could't find a appropriate solution for this. Anyone that can help me out and push me in the right direction? Thanks in advance.
There is no separated local scope inside for loop so you are assigning an object to your variable called todo that was previously declared as a function instead of creating a new local variable with the same name to store your todo data.
You can read more about this particular topic and most of the features and 'pitfalls' of the language on http://bonsaiden.github.io/JavaScript-Garden/#function.scopes . I would strongly suggest you to read the whole page, it will save you a lot of time in the future.