Alternative to then() function - javascript

I'm working on a project that requires a PayPal payment gateway. I found a simple tutorial online that works fine, with the exception that the PayPal Response is sent to the console log. Looking online for any instance were the then() function is used for other than logging to console came up empty. The present code:
return actions.order.capture().then(function (details) {
console.log(details);
needs to be changed, to a function other than then() in order to send the JSON object to the PHP processing page. Being a backend developer, I'm not sure what function that will be. Can anyone make a suggestion please? The entire code is as follows:
The HTML & JS Script
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Paypal Payment</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<main id="cart-main">
<div class="site-title text-center">
<h3 class="font-title">Shopping Cart</h3>
</div>
<div class="container">
<div class="grid">
<div class="col-1">
<div class="flex item justify-content-between">
<div class="flex">
<div class="img text-center">
<img src="./assets/pro1.png" alt="">
</div>
<div class="title">
<h3>Canon EOS 1500D</h3>
<span>Electronics</span>
<div class="buttons">
<button type="submit"><i class="fas fa-chevron-up"></i> </button>
<input type="text" class="font-title" value="1">
<button type="submit"><i class="fas fa-chevron-down"></i> </button>
</div>
Save for later |
Delete From Cart
</div>
</div>
<div class="price">
<h4 class="text-red">$349</h4>
</div>
</div>
</div>
<div class="col-2">
<div class="subtotal text-center">
<h3>Price Details</h3>
<ul>
<li class="flex justify-content-between">
<label for="price">Products ( 1 item ) : </label>
<span>$399</span>
</li>
<li class="flex justify-content-between">
<label for="price">Delivery Charges : </label>
<span>Free</span>
</li>
<hr>
<li class="flex justify-content-between">
<label for="price">Amout Payble : </label>
<span class="text-red font-title">$399</span>
</li>
</ul>
<div id="paypal-payment-button">
</div>
</div>
</div>
</div>
</div>
</main>
<script src="https://www.paypal.com/sdk/js?client-id=ASbdZ8CH5kN5y98rzOuKMLPYsHl4QHLYcDGJ6lgaRjxiRp97t53sPWr1yG5vyd9mlHbyqw3vGUZaJsok&disable-funding=credit,card"></script>
<script>
// Create a Global var - the HTML charge is dummy stuff
window.charge = 0.27;
paypal.Buttons({
style : {
color: 'blue',
shape: 'pill'
},
createOrder: function (data, actions) {
return actions.order.create({
purchase_units : [{
amount: {
value: window.charge
}
}]
});
},
onApprove: function (data, actions) {
return actions.order.capture().then(function (details) {
console.log(details);
window.location.replace("https://localhost/PayPal_Simple/payPalResponse.php?q=good");
window.alert('This was successful.');
})
},
onCancel: function (data) {
window.location.replace("https://localhost/PayPal_Simple/payPalResponse.php?q=bad");
window.alert('Something went wrong!');
}
}).render('#paypal-payment-button');</script>
</body>
</html>
The PHP
<?php
// Get the Response from PayPal
$status = $_GET['q'];
// Once there is an object that can be tested, that will be used instead of ?q=
if($status = "good") {
echo "The payment was a success.<br />";
} elseif($status = "bad") {
echo "The charge was cancelled.";
} else {
echo "Something else went wrong.";
}
// Of course, this doesn't display anything
echo '<pre>';
print_r($_POST);
echo '<pre>';
// Insert data into the database
// Redirect the client to another page
?>
Thanks so much in advance for your help!
Cheers,
Rick

Do not capture on the client side and then send data to a backend. Instead, change to a proper server-side integration--the backend should be communicating with PayPal itself and sending data to the client on request.
Make two routes on your server, one for 'Create Order' and one for 'Capture Order', documented here. These routes should return only JSON data (no HTML or text). The latter one should (on success) store the payment details in your database before it does the return (particularly purchase_units[0].payments.captures[0].id, the PayPal transaction ID)
Pair those two routes with the following approval flow: https://developer.paypal.com/demo/checkout/#/pattern/server

As This link reads , try using
onApprove
''''
const onApprove= new Promise((resolve, reject) => {
{resolve((data,actions) => {actions.order.capture(data,actions)}});
});
''''
buttonPushFunction
''''
async function doYourButtonPush() {
try {
await onApprove;
console.log("The Promise is resolved!", value);
} catch (e) {
console.error("The Promise is rejected!", error);
} finally {
function (details) {
console.log(details);
window.location.replace("https://localhost/PayPal_Simple/payPalResponse.php?q=good");
window.alert('This was successful.');
}
}
}
''''

Related

JavaScript function not getting called on HTML button click

I have a JavaScript file with a function called "AddCenter(e)" that is called on the click of a button but nothing happens. Can anyone help me?
For some more details, I am using a node.js project, an express server and on online IDE called: Replit. Here is the website url: replit.com
EDIT : So I have modified everything like you guys suggested but still nothing happens.
Here is the link to the part of the website : Website Link
So the url is supposed to change from : https://worldsportcenters.xxgamecodingxx.repl.co/api/v1/im to : https://worldsportcenters.xxgamecodingxx.repl.co/
But instead it goes to the same url but adds a ? at the end of it : https://worldsportcenters.xxgamecodingxx.repl.co/api/v1/im?
Does anyone know why ???
Here is my JavaScript file :
const centers = require('../../models/Center');
const centerName = document.getElementById('center-name');
const centerAddress = document.getElementById('center-address');
const centerDescription = document.getElementById('center-description');
const key = document.getElementById('dev-key');
const submitButton = document.getElementById('submit-button');
function CheckForURL(str)
{
let reg = new RegExp('([a-zA-Z\d]+://)?((\w+:\w+#)?([a-zA-Z\d.-]+\.[A-Za-z]{2,4})(:\d+)?(/.*)?)', 'i')
return reg.test(str)
}
async function AddCenter(e)
{
e.preventDefault();
if (centerName.value === '') return alert('Please fill in the "Sport Center Name" field');
else if (centerAddress.value === '') return alert('Please fill in the "Sport Center Address" field');
else if (centerDescription.value === '') return alert('Please fill in the "Sport Center Description" field');
else if (key.value === '') return alert('Please fill in the "Developper Key" field');
else if (CheckForURL(centerDescription.value)) return alert('You can not put a url in the free marker "Sport Center Description" field');
else if (key.value !== process.env['DEVELOPER_KEY'])
{
alert('You filled in the wrong KEY in the "Sport Center Description" field, and this window will self destruct in 10 seconds');
var timer = setInterval(function() {
window.close();
}, 10000);
return;
}
centers.create({
type: 'informative',
name: centerName.value,
address: centerAddress.value,
description: centerDescription.value
});
if (res.status === 400)
{
throw Error('That sport center already exists !');
}
alert('Center added !');
window.location.href = '/';
}
submitButton.addEventListener("click", function ()
{
AddCenter();
});
The HTML file :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link
rel="stylesheet",
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css",
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T",
crossorigin="anonymous"
/>
<title>World Sport Center - Add Center</title>
<link rel="stylesheet" href="/css/main.css" />
</head>
<body>
<div class="text-center">
<div class="container my-3">
<h1 class="display-4 text-center disable-select">Add Informative Marker</h1>
<form id="center-form" class="mb-4">
<div class="form-group">
<blockquote class="blockquote">
<p class="mb-0 disable-select">Sport Center Name</p>
</blockquote>
<input type="text" id="center-name" class="form-control" />
</div>
<div class="form-group">
<blockquote class="blockquote">
<p class="mb-0 disable-select">Sport Center Address</p>
</blockquote>
<input type="text" id="center-address" class="form-control" />
</div>
<div class="form-group">
<blockquote class="blockquote">
<p class="mb-0 disable-select">Sport Center Description</p>
</blockquote>
<textarea type="text" rows="2" id="center-description" class="form-control" maxlength="150"></textarea>
</div>
<div class="form-group">
<blockquote class="blockquote">
<p class="mb-0 disable-select">Developper Key</p>
</blockquote>
<input type="text" id="dev-key" class="form-control" />
</div>
<-- Back
<button id="submit-button" class="btn btn-lg btn-primary">Submit --></button>
</form>
</div>
</div>
<script src="/js/informative.js"></script>
</body>
</html>
onclick="AddCenter"
The value of an onclick attribute is the function body for the event handler.
That makes this, roughly, equivalent to:
theElement.addEventListener("click", function () {
AddCenter;
});
If you want to call the function then you need to do so with ( then any arguments you want to pass, then ).
That said, use addEventListener, intrinsic event attributes have some gotchas and don't separate concerns very well.

Property or method "navlink" is not defined on the instance but referenced during render - Vue.js

I'm having some problem with vue.js
I'm learning how to create components and I'm making some components that I want to use for a wordpress theme. I'm using the REST API to get the contents and pass the response data from axios to the UI managed by vue and vue coponents. I'm getting always this error:
Property or method "navlink" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property
This happen after I've created a new component for the nav menu, I think the code is correct but any help will be appreciated. I have the home.php file that will be used for the homepage as a template using Template Name: on top of the file and inside the header.php file I've removed the old menu and I've placed a vue template. I will do the same for the footer, but how I can fix errors that are caused by widgets or wordpress generated inline scripts? How I can fix my error ?
// this is the code of header.php
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="profile" href="http://gmpg.org/xfn/11">
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<div class="container-fluid p-0" id="theme-vue">
<theme-nav v-for="nav in navData" :navlink="nav.post_title"></theme-nav>
<script type="text/x-template" id="theme-nav">
<nav class="navbar navbar-expand-md fixed-top main-nav">
<button class="navbar-toggler hamburger hamburger--spin" type="button" data-toggle="collapse" data-target="#navbar-content" aria-controls="navbar-content" aria-expand="false" aria-label="<?php _e('Toggle Navigation'); ?>">
<span class="hamburger-box">
<span class="hamburger-inner"></span>
</span>
</button>
<a class="navbar-brand ml-auto" href="#">
<img src="" width="auto" height="75">
</a>
<div class="collapse navbar-collapse navbar-content" id="navbar-content">
<ul class="navbar-nav mx-auto">
<li class="nav-item">
<a class="nav-link top" href="#">{{ navlink }}</a>
</li>
</ul>
</div>
</nav>
</script>
// this is the code of home.php
<?php /* Template Name: Homepage */ ?>
<?php get_header(); ?>
<uptheme-cover v-for="post in postData" :title="post.title.rendered" :src="post._embedded['wp:featuredmedia'][0].source_url"></uptheme-cover>
<script type="text/x-template" id="uptheme-cover">
<div class="row container-cover p-0" style="height:100vh;">
<div class="parallax" :data-parallax-image="src"></div>
<div class="row">
<div class="col-sm-12 col-md-12 col-lg-12 p-4">
<h1>{{ title }}</h1>
</div>
</div>
<div class="overlay"></div>
</div>
</script>
<?php //get_footer(); ?>
// this is the footer, it will cause error in vue because of the google map iframe footer widget and wordpress footer scripts
<?php wp_footer(); ?>
<div class="row p-0 footer">
<?php if( is_active_sidebar('footer-map') ): ?>
<?php dynamic_sidebar('footer-map'); ?>
<?php endif; ?>
<div class="col-sm-12 col-md-12 col-lg-12 p-0 text-center credits-col">
<small><?php _e('Powered by '); ?><a class="" href=""><?php _e('UpAdv')?></a></small>
</div>
</div>
</div>
// this code is placed inside the main.js file of my theme
Vue.component('theme-nav',{
template: '#theme-nav',
props: {
//navId: Number
navlink: String,
}
});
Vue.component('theme-cover',{
template: '#theme-cover',
props: {
title: String,
src: String
}
});
const app = new Vue({
el: '#theme-vue',
data: {
postData: [],
navData: []
},
mounted: function(){
this.getMenu();
this.getIndex();
},
created: function(){
this.initParallax();
},
methods: {
initParallax: function(){
const parallax = new universalParallax();
},
getMenu: function(){
// this line didn't work, I need to get the custom logo but I don't know how with REST API?
axios.get('wp-json/theme/v1/logo').then( (response) => {
console.log(response);
});
axios.get('wp-json/theme/v1/menu').then( (response) => {
console.log(response);
response.data.forEach( (item, i) => {
this.navData.push(item);
});
});
},
getIndex: function(){
axios.get('wp-json/wp/v2/pages/?slug=home&_embed').then( (res) => {
console.log(res.data);
res.data.forEach( (item, i) => {
this.postData.push(item);
console.log(item._embedded['wp:featuredmedia'][0].source_url);
});
});
}
}
});
Try adding the navlink under data like
data: {
postData: [],
navData: [],
navlink:''
}

Cant access get results from fetch api request

I've been trying to access the array results from my fetch api request. I can get the results to return and parse it from json into a javascript object. However I cant access the results. The array is that is return called results. I wondering what I'm missing. The ultimate aim of the project is to get 12 random profiles from the api and get it to display to the card div. The error message I'm getting is 'Uncaught (in promise) TypeError: Cannot read property 'results' of undefined at app.js:40'
HTML
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Public API Requests</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href="css/normalize.css" rel="stylesheet">
<link href="css/styles.css" rel="stylesheet">
</head>
<body>
<header>
<div class="header-inner-container">
<div class="header-text-container">
<h1>AWESOME STARTUP EMPLOYEE DIRECTORY</h1>
</div>
<div class="search-container">
</div>
</div>
</header>
<div id="gallery" class="gallery">
</div>
</body>
<script type="text/javascript" src="app.js"></script>
</html>
Javascript
const gallery = document.getElementById('gallery');
const card = document.createElement('div');
card.classList.add('card');
gallery.appendChild(card);
function fetchData(url) {
return fetch(url)
.then(response => { return response.json()})
.then(data => {console.log(data)})
.catch(error => {console.log('Error with fetching API', error)})
}
function generateInfo(data) {
const info = data.map( item => `
<div class="card-img-container">
<img class="card-img" src="${data}" alt="profile picture">
</div>
<div class="card-info-container">
<h3 id="name" class="card-name cap">${name.first} ${name.last}</h3>
<p class="card-text">${data.email}</p>
<p class="card-text cap">${location.city}</p>
</div>
`)
card.innerHTML = info;
}
fetchData('https://randomuser.me/api/')
.then(data => generateInfo(data.results));
The error is clear, the object you are getting in data is not defined, that's why it does not have a result key.
Check that data is coming from the URL. When I fetch the URL there is JSON coming in.
Also note that in the second then you have for debugging is not returning the data variable, and that's why you get nothing afterwards.
Add a return statement like: return data;
Extra info related to the catch part from docs: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API if you want to check for errors look at the status code from response.
The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.
Change the fetchData function, remove .then block where you are getting final data, attach it when calling fetchData
function fetchData(url) {
return fetch(url)
.then(response => { return response.json()})
.catch(error => {console.log('Error with fetching API',
error)})}
fetchData('https://randomuser.me/api/')
.then(data =>generateInfo(data.results)); //success to the final promise
Now inside generate info use foreach() instead of map().Since for each user object you need to create card.
function generateInfo(results) {
results.forEach( userObj =>{
const card = document.createElement('div');
card.classList.add('card');
card.innerHTML = `
<div class="card-img-container">
<img class="card-img" src="${userObj.picture.thumbnail}" alt="profile picture">
</div>
<div class="card-info-container">
<h3 id="name" class="card-name cap">${userObj.name.first} ${name.last}</h3>
<p class="card-text">${userObj.email}</p>
<p class="card-text cap">${userObj.location.city}</p>
</div>
`;
gallery.appendChild(card);
})
}
Run the following snippet to check if it works.
const gallery = document.getElementById('gallery');
function fetchData(url) {
return fetch(url)
.then(response => { return response.json()})
.catch(error => {console.log('Error with fetching API', error)})}
function generateInfo(results) {
results.forEach( userObj =>{
const card = document.createElement('div');
card.classList.add('card');
card.innerHTML = `
<div class="card-img-container">
<img class="card-img" src="${userObj.picture.thumbnail}" alt="profile picture">
</div>
<div class="card-info-container">
<h3 id="name" class="card-name cap">${userObj.name.first} ${name.last}</h3>
<p class="card-text">${userObj.email}</p>
<p class="card-text cap">${userObj.location.city}</p>
</div>
`;
gallery.appendChild(card);
})
}
fetchData('https://randomuser.me/api/')
.then(data =>generateInfo(data.results));
<header>
<div class="header-inner-container">
<div class="header-text-container">
<h1>AWESOME STARTUP EMPLOYEE DIRECTORY</h1>
</div>
<div class="search-container">
</div>
</div>
</header>
<div id="gallery" class="gallery">
</div>

Javascript variables braces html tag not interpreted

I have a problem with the outlook API. I display mails but the body doesn't interpret html tags. I only see the source code of the page.I tried a lot of things but I can't get the tags interpreted. Anybody got a solution? Thank you
// Get the 10 newest messages
client
.api('/me/mailfolders/inbox/messages')
.header('X-AnchorMailbox', emailAddress)
.top(1)
.select('subject,from,receivedDateTime,bodyPreview,uniqueBody')
.orderby('receivedDateTime DESC')
.get((err, res) => {
if (err) {
callback(null, err);
} else {
callback(res.value);
}
});
} else {
var error = { responseText: 'Could not retrieve access token' };
callback(null, error);
}
});
<div class="test">
<!-- Handlebars template for message list -->
<script id="msg-list-template">
<div class="row">
<div class="col-lg-6">
{{#each messages}}
<div class="list-group-item">
<h3 id="msg-from" class="">{{this.from.emailAddress.name}}</h3>
<h4 id="msg-subject" class="list-group-item-heading">{{this.subject}}</h4>
<p id="msg-received" class="list-group-item-heading text-muted"><em>Received: {{formatDate this.receivedDateTime}}</em></p>
<p id="msg-bodyPreview" class="list-group-item-text text-muted azerty"><em>{{this.bodyPreview}}</em></p>
<p id="msg" class=""><em>{{this.uniqueBody.content}}</em></p>;
</div>
{{/each}}

OpenID-Connect-Java-Spring-Server CORS Disabled ERROR

I just started using oidc-client-js, so i am really confused trying to understand it . I have the below question :) .
I have been connected to a remote webserver running OpenIDConnect and specifically using https://github.com/mitreid-connect/OpenID-Connect-Java-Spring-Server i have builded the openid-connect-server-webapp and created a client correctly. It is hosted on a vm .
I followed this tutorial -> link
Link of 3 html files i modified for the tutorial i followed ->
here
The error that is shown on the console:
All good as you can see on the image below , i authorized the simple javascript app and i am getting back the access_token along with id_token , though when i am trying to call the API , boom i get error and i don't know why ?
The html index code i have is ( in case it helps you ) :
<!DOCTYPE html>
<html>
<head>
<title>JS Application</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.css" />
<style>
.main-container {
padding-top: 70px;
}
pre:empty {
display: none;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#">JS Application</a>
</div>
</div>
</nav>
<div class="container main-container">
<div class="row">
<div class="col-xs-12">
<ul class="list-inline list-unstyled requests">
<li>Home</li>
<li><button type="button" class="btn btn-default js-login">Login</button></li>
<li><button type="button" class="btn btn-default js-call-api">Call API</button></li>
<li><button type="button" class="btn btn-danger js-logout">Logout</button></li>
</ul>
</div>
</div>
<div class="row">
<div class="col-xs-6">
<div class="panel panel-default">
<div class="panel-heading">User data</div>
<div class="panel-body">
<pre class="js-user"></pre>
</div>
</div>
</div>
<div class="col-xs-6">
<div class="panel panel-default">
<div class="panel-heading">API call result</div>
<div class="panel-body">
<pre class="js-api-result"></pre>
</div>
</div>
</div>
</div>
</div>
<script src="node_modules/jquery/dist/jquery.js"></script>
<script src="node_modules/bootstrap/dist/js/bootstrap.js"></script>
<script src="node_modules/oidc-client/dist/oidc-client.js"></script>
<script>
// helper function to show data to the user
function display(selector, data) {
if (data && typeof data === 'string') {
data = JSON.parse(data);
}
if (data) {
data = JSON.stringify(data, null, 2);
}
$(selector).text(data);
}
var settings = {
authority: 'http://snf-761523.vm.okeanos.grnet.gr:8080/openid-connect-server-webapp',
client_id: 'client',
client_secret: "secret",
user_id: "user",
popup_redirect_uri: 'http://localhost/jsApp/popup.html',
silent_redirect_uri: 'http://localhost/jsApp/silent-renew.html',
post_logout_redirect_uri: 'http://localhost/jsApp/index.html',
response_type: 'token id_token',
scope: 'openid profile email offline_access',
filterProtocolClaims: false
};
var manager = new Oidc.UserManager(settings);
var user;
Oidc.Log.logger = console;
manager.events.addUserLoaded(function (loadedUser) {
user = loadedUser;
display('.js-user', user);
});
manager.events.addSilentRenewError(function (error) {
console.error('error while renewing the access token', error);
});
manager.events.addUserSignedOut(function () {
alert('The user has signed out');
});
$('.js-login').on('click', function () {
manager
.signinPopup()
.catch(function (error) {
console.error('error while logging in through the popup', error);
});
});
$('.js-call-api').on('click', function () {
var headers = {};
if (user && user.access_token) {
headers['Authorization'] = 'Bearer ' + user.access_token;
}
$.ajax({
url: 'http://snf-761523.vm.okeanos.grnet.gr:8080/openid-connect-server-webapp/api/tokens/access',
method: 'GET',
dataType: 'json',
headers: headers
}).then(function (data) {
display('.js-api-result', data);
}).catch(function (error) {
display('.js-api-result', {
status: error.status,
statusText: error.statusText,
response: error.responseJSON
});
});
});
$('.js-logout').on('click', function () {
manager
.signoutRedirect()
.catch(function (error) {
console.error('error while signing out user', error);
});
});
</script>
</body>
</html>
There is a temporary solution tough only for testing your application and not for production , disabling Web-Security on Google Chrome
FIRST YOU NEED TO KILL ALL THE INSTANCES OF CHROME , then install a Plugin Called CORS Toggle
and finally run the bellow commants from Terminal or Commant Prompt
For Windows
.\chrome --args --disable-web-security --user-data-dir
For Ubuntu Linux (tested only there)
/opt/google/chrome/google-chrome --args --disable-web-security --user-data-dir

Categories