How to implement Gpay payment gateway in NodeJS? - node.js

I tried it in html and javascript it's working perfect in web (mobile's browser).I am using angular for frontend and node for backend but not getting any solution for redirect Playstore or Gpay for mobile browser. Basically I want to implement for mobile browser.
this is my node for backend code & for frontend I already paste static--
const canMakePaymentCache = 'canMakePaymentCache';
onBuyClicked();
function readSupportedInstruments() {
let formValue = {};
formValue['pa'] = keys.GPAY_MERCHANT_ID;//merchantId
formValue['pn'] = `Test_Gpay_Name`;//transactionId
formValue['tn'] = 'Testing Messages ';//message
formValue['mc'] = 'merchant Code';//
formValue['tr'] = 'Transaction Reference';
formValue['tid'] = 'Transaction id';
formValue['url'] = 'http://localhost.co/';
return formValue;
}
function readAmount() {
//const pay_amount = parseInt(req.body.amount) * 100;
return parseInt(req.body.amount) * 100;
}
function onBuyClicked() {
// if (!window.PaymentRequest) {
// console.log('Web payments are not supported in this browser.');
// return;
// }
let formValue = readSupportedInstruments();
const supportedInstruments = [
{
supportedMethods: ['https://pwp-server.appspot.com/pay-dev'],
data: formValue,
},
{
supportedMethods: ['https://tez.google.com/pay'],
data: formValue,
},
];
const details = {
total: {
label: 'Total',
amount: {
currency: 'INR',
value: readAmount(),
},
},
displayItems: [
{
label: 'Original amount',
amount: {
currency: 'INR',
value: readAmount(),
},
},
],
};
const options = {
requestShipping: false,
requestPayerName: false,
requestPayerPhone: false,
requestPayerEmail: false,
shippingType: 'shipping',
};
let request = null;
try {
//const PaymentRequest = {};
//request = PaymentRequest(supportedInstruments, details, options);
request ={supportedInstruments, details, options};
} catch (e) {
return;
}
if (!request) {
console.log('Web payments are not supported in this browser.');
return;
}
var canMakePaymentPromise = checkCanMakePayment(request);
canMakePaymentPromise
.then((result) => {
showPaymentUI(request, result);
})
.catch((err) => {
console.log('Error calling checkCanMakePayment: ' + err);
});
}
function checkCanMakePayment(request) {
//if (sessionStorage.hasOwnProperty(canMakePaymentCache)) {
//return Promise.resolve(JSON.parse(sessionStorage[canMakePaymentCache]));
//}
var canMakePaymentPromise = Promise.resolve(true);
if (request.canMakePayment) {
canMakePaymentPromise = request.canMakePayment();
}
return canMakePaymentPromise
.then((result) => {
canMakePaymentCache = result;
return result;
})
.catch((err) => {
console.log('Error calling canMakePayment: ' + err);
});
}
function showPaymentUI(request, canMakePayment) {
if (!canMakePayment) {
redirectToPlayStore();
return;
}
let paymentTimeout = window.setTimeout(function () {
window.clearTimeout(paymentTimeout);
request.abort()
.then(function () {
console.log('Payment timed out after 20 minutes.');
})
.catch(function () {
console.log('Unable to abort, user is in the process of paying.');
});
}, 20 * 60 * 1000); /* 20 minutes */
request.show()
.then(function (instrument) {
window.clearTimeout(paymentTimeout);
processResponse(instrument); // Handle response from browser.
})
.catch(function (err) {
console.log(err);
});
}
function processResponse(instrument) {
var instrumentString = instrumentToJsonString(instrument);
console.log(instrumentString);
fetch('/buy', {
method: 'POST',
headers: new Headers({ 'Content-Type': 'application/json' }),
body: instrumentString,
credentials: 'include',
})
.then(function (buyResult) {
if (buyResult.ok) {
return buyResult.json();
}
console.log('Error sending instrument to server.');
})
.then(function (buyResultJson) {
completePayment(
instrument, buyResultJson.status, buyResultJson.message);
})
.catch(function (err) {
console.log('Unable to process payment. ' + err);
});
}
function completePayment(instrument, result, msg) {
instrument.complete(result)
.then(function () {
console.log('Payment completes.');
console.log(msg);
document.getElementById('inputSection').style.display = 'none'
document.getElementById('outputSection').style.display = 'block'
document.getElementById('response').innerHTML =
JSON.stringify(instrument, undefined, 2);
})
.catch(function (err) {
console.log(err);
});
}
console.log(`in line 448....`);
function redirectToPlayStore() {
//if (confirm('Tez not installed, go to play store and install?')) {
//window.location.href = 'https://play.google.com/store/apps/details?id=com.google.android.apps.nbu.paisa.user.alpha'
//res.writeHead( "https://play.google.com/store/apps/details?id=com.google.android.apps.nbu.paisa.user.alpha" );
const response_data = axios
.post(
'https://play.google.com/store/apps/details?id=com.google.android.apps.nbu.paisa.user.alpha',
)
console.log(`in line no. 459... ${response_data}`);
return response_data;
//};
}
function instrumentToJsonString(instrument) {
var instrumentDictionary = {
methodName: instrument.methodName,
details: instrument.details,
shippingAddress: addressToJsonString(instrument.shippingAddress),
shippingOption: instrument.shippingOption,
payerName: instrument.payerName,
payerPhone: instrument.payerPhone,
payerEmail: instrument.payerEmail,
};
return JSON.stringify(instrumentDictionary, undefined, 2);
}

Related

One signal push notification node js API

Push notification node js API using One signal
Hello guys, I've watched a tutorial to implement push notifications on flutter app project.
the code I'll show is how to set up a push notification on node js API using one signal.
I need help to know how to view the notification using One Signal API.
here is the notification service folder
notification.services.js
const { ONE_SIGNAL_API_KEY } = require('../utils/config')
const { info } = require('../utils/logger')
const sendNotification = async (data, callback) => {
const headers = {
'Content-Type': 'application/json; charset=utf-8',
Authorization: 'Basic ' + ONE_SIGNAL_API_KEY,
}
const options = {
host: 'onesignal.com',
port: 443,
path: '/api/v1/notifications',
method: 'POST',
headers: headers,
}
const https = require('https')
const req = https.request(options, res => {
res.on('data', data => {
info(JSON.parse(data))
return callback(null, JSON.parse(data))
})
})
req.on('error', e => {
return callback({
message: e,
})
})
req.write(JSON.stringify(data))
req.end()
}
here is the notification controller folder
notification.controller.js
const { ONE_SIGNAL_APP_ID } = require('../utils/config')
const notificationsService = require('../services/notifications.services')
const sendNotification = (req, res, next) => {
const message = {
app_id: ONE_SIGNAL_APP_ID,
headings: { en: 'All Devices' },
contents: { en: 'Send push notifications to all devices' },
included_segments: ['All'],
content_available: true,
small_icon: 'ic_notification_icon',
data: {
// eslint-disable-next-line quotes
PushTitle: "Porc'Ivoire",
},
}
notificationsService.sendNotification(message, (error, results) => {
if (error) {
next(error)
}
return res.status(200).send({
message: 'Success',
data: results,
})
})
}
const sendNotificationToDevice = (req, res, next) => {
var message = {
app_id: ONE_SIGNAL_APP_ID,
headings: { en: '🤑 Paiement accepté' },
contents: {
en: 'Votre paiment a été effrctué avec succès',
},
included_segments: ['included_player_ids'],
include_player_ids: req.body.devices,
content_available: true,
small_icon: 'ic_notification_icon',
data: {
// eslint-disable-next-line quotes
PushTitle: "Porc'Ivoire",
},
}
notificationsService.sendNotification(message, (error, results) => {
if (error) {
next(error)
}
return res.status(200).send({
message: 'Success',
data: results,
})
})
}
module.exports = {
sendNotification,
sendNotificationToDevice,
}

Stop node mailer scheduler after 3 days of subscribing to newsletter

I have a node.js application and I am using node mailer. When user subscribes to newsletter I send him newsletter every day at specific hour. How can I achieve that it will stop sending to that specific user after 3 days.
Code in MailServiceCron.ts:
export const CRON = () => {
scheduleJob("0 5 * * *", async () => {
try {
let UserList = await User.getUsersByDate();
UserList.forEach(async (user: IUserGet) => {
var content = fs.readFileSync("src/data/email.html");
var htmlbody = content.toString();
await fetch(
"api_url" +
process.env.USER_KEY,
{
method: "POST",
headers: { "Content-Type": "application/json" },
}
)
.then(async (res) => {
return [await res.json(), res.status];
})
.then(([data, status]) => {
console.log(data);
if (data.steviloDelovnihMest > 0) {
let transporter = nodemailer.createTransport({
host: "host",
port: 25,
secure: false, // true for 465, false for other ports
});
let info = transporter.sendMail({
from: "<no-reply#text.com>", // sender address
to: user.email, // list of receivers
subject: `test`, // Subject line// plain text body
html: htmlbody, // html body
});
}
})
.catch((error) => {
return console.log(error);
});
});
console.log("Sending mails");
} catch (e) {
console.log(e);
}
});
};
function deleteEmptyProps(obj: any): any {
Object.keys(obj).forEach((k) => {
if (
!obj[k] ||
obj[k] === undefined ||
(Array.isArray(obj[k]) && obj[k].length === 0)
) {
delete obj[k];
}
});
return obj;
}
export const deletingNonActiveCRON = () => {
scheduleJob("0 * * * *", async () => {
try {
let response = await User.deleteNonActive();
console.log(response);
} catch (e) {
console.log(e);
}
});
};
And in my separate file mail.ts i have this:
module.exports.deleteNonActive = async function () {
let date = new Date();
return await User.deleteMany({
$and: [
{ dateStart: { $lt: new Date(date.setHours(date.getHours() - 48)) } },
{ aktivnost: { $eq: false } },
],
});
};
My idea is that I need also some deleteExpired function, something like that?
module.exports.deleteExpired = async function () {
await User.updateMany(
{
$and: [
{ dateEnd: { $lt: new Date() } },
{ aktivnost: { $eq: true } },
],
},
{ $set: { aktivnost: false } }
);
};
Which I also call in MailServiceCron.ts file like deleteNonActive function?

Send multiple files from express server to rest api

I am trying to send multiple files from react to express server and then to microservice. The problem is that my express server is getting crashed whenever I try to upload multiple files.
Here is my express.js side code:
router.post("/upload-files", upload.array("file[]"), async function (req, res) {
let check = new FormData();
// check = req.files;
const file = req.files;
// console.log("DATA------------------------>", file);
// check.append("file", file.buffer, file.originalname);
await axios.post(
constants.URL2 +":9095/upload-files", check,
{
headers: {
...check.getHeaders(),
},
})
.then((res) => {
return res;
})
.then((result) => {
res.send(result.data);
});
});
Here is my React.js side code:
update = () => {
if (this.isValidForm()) {
$(".loader").css({ display: "block" });
$(".overlay").css({ display: "block" });
// const obj = {
// fullName: this.state.fullName,
// };
var formData = new FormData();
const size = this.state.fileData;
for (let i = 0; i < size.length; i++) {
console.log(this.state.fileData[i]);
formData.append("file[]", this.state.fileData[i]);
}
// formData.append("files", this.state.fileData);
const updateRequest = {
method: "POST",
headers: {
// "Content-Type": "application/json",
Authorization:
},
// body: JSON.stringify(obj),
body: formData
};
fetch(URL.BASE_URL + "upload-file", updateRequest)
.then((res) => {
if (res.status == 401) {
this.props.GETLOGGEDINUSER(null);
this.props.history.push("/");
} else {
return res.json();
}
})
.then((res) => {
if (res.statusCode == 0) {
this.props.history.push({
pathname: "/newScreen",
state: { notification: "File uploaded Successfully" },
});
toast.success("File uploaded Successfully");
$(".loader").css({ display: "none" });
$(".overlay").css({ display: "none" });
} else {
toast.error(res.message);
$(".loader").css({ display: "none" });
$(".overlay").css({ display: "none" });
}
});
} else {
}
};
I tried many ways to solve this but none of them works.

How to receive re-requested data when data requested by mounted() is re-requested by aixos interceptor

the code below is the first request for get list data
mounted() {
this.getList()
},
methods: {
handleClick(row) {
console.log(row.id)
console.log(row.url)
this.$router.push({ name: 'Main', query: { id: row.id } })
},
getList() {
axios
.get('/api/v1/requests/all', {
params: {
userId: this.$store.state.userInfo.id,
},
})
.then(response => {
let moment = require('moment')
for (var item of response.data.data) {
item.createdAt = moment(item.createdAt).format(
'YYYY-MM-DD HH:mm:ss',
)
}
this.items = response.data.data
})
.catch(error => {
console.log(error)
})
}
my interceptor
axios.interceptors.response.use(
function (response) {
return response
},
async function (error) {
const originalRequest = error.config
if (error.response.status === 401 && !originalRequest._retry) {
error.response.config._retry = true
sessionStorage.removeItem('access-token')
let headers = {
grant_type: 'refresh_token',
Authorization: sessionStorage.getItem('refresh-token'),
}
axios
.post('/api/v1/users/refresh_token', {}, { headers: headers })
.then(response => {
let token = response.data.data
sessionStorage.setItem('access-token', token)
originalRequest.headers['Authorization'] = token
originalRequest.headers['grant_type'] = 'grant_type'
return axios.request(originalRequest)
})
.catch(error => {
console.log(error)
alert('blablabla.')
})
}
return Promise.reject(error)
},
)
the flow is i understand
1.token expired
2.move to list page
3.mounted hook is request data
4.getList -> axios get('~~request/all')
5.interceptor->axios post('~~~refresh_token')
6.re request with new token(request/all)
7.re request is 200, but not update list page
i'd really appreciate your help :)
Seems like you need to return the second request (await for result and return). Right now the result of second request seems to be ignored
axios.interceptors.response.use(
function (response) {
return response;
},
async function (error) {
const originalRequest = error.config;
if (error.response.status === 401 && !originalRequest._retry) {
error.response.config._retry = true;
sessionStorage.removeItem("access-token");
let headers = {
grant_type: "refresh_token",
Authorization: sessionStorage.getItem("refresh-token"),
};
const [secondError, res] = await axios // await here
.post("/api/v1/users/refresh_token", {}, { headers: headers })
.then(async (response) => {
let token = response.data.data;
sessionStorage.setItem("access-token", token);
originalRequest.headers["Authorization"] = token;
originalRequest.headers["grant_type"] = "grant_type";
return [null, await axios.request(originalRequest)];
})
.catch((err) => {
console.log(err);
alert("blablabla.");
return [err, null];
});
// Handle here
if(secondError) {
return Promise.reject(secondError);
}
return Promise.resolve(res)
}
return Promise.reject(error);
}
);
The above solution worked for me perfectly. here's the modified code that I used for my requirement.
export default function axiosInterceptor() {
//Add a response interceptor
axios.interceptors.response.use(
(res) => {
// Add configurations here
return res;
},
async function (error) {
const originalRequest = error.config;
let secondError, res
if (error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
[secondError, res] = await axios({
method: "POST",
url: `${baseURL}/account/token/refreshtoken`,
withCredentials: true,
headers: { "Content-Type": "application/json" },
})
.then(async (response) => {
//handle success
return [null, await axios.request(originalRequest)];
}).catch(function (error) {
console.error(error)
});
}
if (secondError) {
return Promise.reject(secondError);
}
return Promise.resolve(res)
}
);
}

Angular 4 Getting 404 not found in production mode

I'm building an angular node app and am doing a http post request to signup a user. Its a chain of observables that gets the users social login information, signs ups the user, then on success emails the user. In dev mode everything works perfect, in prod mode, im getting a 404 not found. I also want to note that in development mode, some of my function calls in the observables on success are not being called. Its acting very strange and cannot figure out what I am doing wrong.
Here is my route controller
module.exports = {
signup: function signup(req, res) {
return User.create({
email: (req.body.email).toLowerCase(),
image: req.body.image,
name: req.body.name,
provider: req.body.provider || 'rent',
uid: req.body.uid || null
}).then(function (user) {
return res.status(200).json({
title: "User signed up successfully",
obj: user
});
}).catch(function (error) {
console.log(error);
return res.status(400).json({
title: 'There was an error signing up!',
error: error
});
});
}
};
and route
router.post('/signup', function(req,res,next) {
return usersController.signup(req,res);
});
My service
#Injectable()
export class UserService {
private devUrl = 'http://localhost:3000/user';
private url = '/user';
sub: any;
public user: User;
constructor(
private authS: AuthService,
private http: HttpClient) {
}
signup(user: User) {
return this.http.post(this.url + '/signup', user);
}
auth(provider: string) {
return this.sub = this.authS.login(provider);
}
logout() {
this.authS.logout()
.subscribe(value => {
console.log(value);
}, error => console.log(error))
}
getUser() {
return this.user;
}
}
and my component logic for signing up using social buttons
onAuth(provider: string){
this.checkmark = true;
this.uis.onSignupComplete();
setTimeout(() => {
this.checkmark = false;
this.thankyou = true;
}, 2500);
this.userService.auth(provider)
.subscribe(user => {
this.user = {
email: user['email'],
image: user['image'],
name: user['name'],
provider: user['provider'],
uid: user['uid']
};
this.userService.signup(this.user)
.subscribe(user => {
this.randomNum = Math.floor(Math.random() * 2);
let userEmail = this.user.email;
let subject = 'Welcome to the rent community';
let html = '';
if (this.randomNum === 1) {
html = this.contactS.getAutoEmail1();
} else if (this.randomNum === 0) {
html = this.contactS.getAutoEmail0();
}
let email = new Email(subject, html, userEmail);
this.contactS.setEmail(email)
.subscribe(data => {
}, response => {
// if (response.error['error'].errors[0].message === 'email must be unique') {
// this.uis.onSetError('Email is already used');
// this.uis.onError();
// setTimeout(() => {
// this.uis.onErrorOff();
// }, 2500);
// } else {
// this.uis.onSetError('There was an error');
// this.uis.onError();
// setTimeout(() => {
// this.uis.onErrorOff();
// }, 2500);
// }
console.log(response);
});
}, resp => console.log(resp));
}, response => {
console.log(response);
});
}
Here is the whole component
import {Component, DoCheck, HostListener, OnInit} from '#angular/core';
import {User} from "../user/user.model";
import {UserService} from "../user/user.service";
import {UiService} from "../ui.service";
import {ContactService} from "../contact/contact.service";
import {Email} from "../contact/email.model";
#Component({
selector: 'app-landing-page',
templateUrl: './landing-page.component.html',
styleUrls: ['./landing-page.component.css']
})
export class LandingPageComponent implements OnInit, DoCheck {
user: User = {
email: '',
image: '',
name: '',
provider: '',
uid: ''
};
signupComplete = false;
signup = false;
contact = false;
error = false;
errorStr = 'There was an error';
checkmark = false;
thankyou = false;
randomNum = Math.floor(Math.random() * 2);
#HostListener('window:keyup', ['$event'])
keyEvent(event: KeyboardEvent) {
const enter = 13;
if (event.keyCode === enter) {
// this.onSignup();
}
}
constructor(
private uis: UiService,
private contactS: ContactService,
private userService: UserService) { }
ngOnInit() {}
ngDoCheck() {
this.signup = this.uis.onGetSignup();
this.contact = this.uis.onGetContact();
this.signupComplete = this.uis.onReturnSignupComplete();
this.error = this.uis.getError();
this.errorStr = this.uis.getErrorStr();
}
onClickAction(s: string) {
this.uis.onClickAction(s);
}
onSignup() {
this.user.provider = 'rent';
this.user.uid = null;
this.userService.signup(this.user)
.subscribe(user => {
this.randomNum = Math.floor(Math.random() * 2);
let userEmail = this.user.email;
let subject = 'Welcome to the rent community';
let html = '';
if (this.randomNum === 1) {
html = this.contactS.getAutoEmail1();
} else if (this.randomNum === 0) {
html = this.contactS.getAutoEmail0();
}
let email = new Email(subject, html, userEmail);
this.checkmark = true;
this.uis.onSignupComplete();
setTimeout(() => {
this.checkmark = false;
this.thankyou = true;
}, 2500);
this.contactS.setEmail(email)
.subscribe(email => {
this.onReset();
}
, error => console.log(error));
}, response => {
if (response.error['error'].errors[0].message === 'email must be unique') {
this.uis.onSetError('Email is already used');
this.uis.onError();
setTimeout(() => {
this.uis.onErrorOff();
}, 2500);
console.log(response);
} else {
this.uis.onSetError('There was an error');
this.uis.onError();
setTimeout(() => {
this.uis.onErrorOff();
}, 2500);
console.log(response);
}
});
}
onAuth(provider: string){
this.checkmark = true;
this.uis.onSignupComplete();
setTimeout(() => {
this.checkmark = false;
this.thankyou = true;
}, 2500);
this.userService.auth(provider)
.subscribe(user => {
this.user = {
email: user['email'],
image: user['image'],
name: user['name'],
provider: user['provider'],
uid: user['uid']
};
this.userService.signup(this.user)
.subscribe(user => {
this.randomNum = Math.floor(Math.random() * 2);
let userEmail = this.user.email;
let subject = 'Welcome to the rent community';
let html = '';
if (this.randomNum === 1) {
html = this.contactS.getAutoEmail1();
} else if (this.randomNum === 0) {
html = this.contactS.getAutoEmail0();
}
let email = new Email(subject, html, userEmail);
this.contactS.setEmail(email)
.subscribe(data => {
}, response => {
// if (response.error['error'].errors[0].message === 'email must be unique') {
// this.uis.onSetError('Email is already used');
// this.uis.onError();
// setTimeout(() => {
// this.uis.onErrorOff();
// }, 2500);
// } else {
// this.uis.onSetError('There was an error');
// this.uis.onError();
// setTimeout(() => {
// this.uis.onErrorOff();
// }, 2500);
// }
console.log(response);
});
}, resp => console.log(resp));
}, response => {
console.log(response);
});
}
onReset() {
this.user.email = '';
this.user.image = '';
this.user.name = '';
this.user.provider = '';
this.user.uid = '';
}
errorStyle(): Object {
if (this.error) {
return {height: '50px', opacity: '1'};
} else if (!this.error) {
return {height: '0', opacity: '0'};
}
return {};
}
}
I want to mention I am using angular-2-social-login for the social logins. Unsure why it would be calling 404 if I am using the /user/signup route appropriately.

Resources