For Paytm JS Checkoput - payment

<div id="paytm-checkoutjs"></div>
<script type="application/html" crossorigin="anonymous" src="https://securegw-stage.paytm.in/merchantpgpui/checkoutjs/merchants/demoKey.js" onload="onScriptLoad();"> </script>
<script>
function onScriptLoad(){
var config = {
"root": "",
"flow": "DEFAULT",
"data": {
"orderId": "", /* update order id */
"token": "", /* update token value */
"tokenType": "TXN_TOKEN",
"amount": "" /* update amount */
},
"handler": {
"notifyMerchant": function(eventName,data){
console.log("notifyMerchant handler function called");
console.log("eventName => ",eventName);
console.log("data => ",data);
}
}
};
if(window.Paytm && window.Paytm.CheckoutJS){
window.Paytm.CheckoutJS.onLoad(function excecuteAfterCompleteLoad() {
// initialze configuration using init method
window.Paytm.CheckoutJS.init(config).then(function onSuccess() {
// after successfully updating configuration, invoke JS Checkout
window.Paytm.CheckoutJS.invoke();
}).catch(function onError(error){
console.log("error => ",error);
});
});
}
}
</script>
The form after selecting the payment option will be shown below.
Please let me know how to take values from the below form to the function written in above and work the payment gateway.
<div class="container" style="padding-top:100px;">
<form action="" method="post">
<input type="hidden" id="CUST_ID" name="CUST_ID" value="<?php echo $txtMarketCode; ?>">
<input type="hidden" id="INDUSTRY_TYPE_ID" name="INDUSTRY_TYPE_ID" value="Retail">
<input type="hidden" id="CHANNEL_ID" name="CHANNEL_ID" value="WEB">
<div class="form-group">
<label>Order ID:</label>
<input type="text" class="form-control" id="ORDER_ID" name="ORDER_ID" size="20" maxlength="20" autocomplete="off" tabindex="1" value="<?php echo $txtTranID; ?>">
</div>
<div class="form-group">
<label>Amount to Pay:</label>
<input type="text" class="form-control" id="TXN_AMOUNT" name="TXN_AMOUNT" autocomplete="off" tabindex="5" value="<?php echo $txtTxnAmount; ?>">
</div>
<div class="form-group">
<input type="submit" name="submit" value="CheckOut" class="btn btn-success btn-lg" style="background-
color:#0000FF; margin-left: 37%;">
</div>
</form>
</div>
</body>
I have tried to add JS Checkout for Paytm payment gateway integration to my webite. How to pass value from my php form to above onScriptLoad() function. please help me incorporate this function.

First, you need to call initiate transaction API which will return you with a transaction token. Pass the transaction token obtained in the function as below -
function onScriptLoad(){
var config = {
"root": "",
"flow": "DEFAULT",
"data": {
"orderId": "<?php echo $orderid;?>", /* update order id */
"token": "<?php echo $txn_token;?>", /* update token value */
"tokenType": "TXN_TOKEN",
"amount": "<?php echo $amount;?>" /* update amount */
},
"handler": {
"notifyMerchant": function(eventName,data){
console.log("n`enter code here`otifyMerchant handler function called");
console.log("eventName => ",eventName);
console.log("data => ",data);
}
}
};
if(window.Paytm && window.Paytm.CheckoutJS){
window.Paytm.CheckoutJS.onLoad(function excecuteAfterCompleteLoad() {
// initialze configuration using init method
window.Paytm.CheckoutJS.init(config).then(function onSuccess() {
// after successfully updating configuration, invoke JS Checkout
window.Paytm.CheckoutJS.invoke();
}).catch(function onError(error){
console.log("error => ",error);
});
});
}
}
If it still doesn't resolve your problem please raise a query on "Paytm Developer Support"

Related

blog post edit from MongoDB does not save changes in NodeJS, ejs template

I have created a blog site in NodeJS, EJS using mongodb. My problem is my posts show up from my database but I I want to make a change to it, it won't save.
app.js
app.post('/do-edit-post/:postId',(req, res) => {
const requestedPostId = req.params.postId;
Post.updateOne({ _id:requestedPostId }, {$set: {
title: req.body.title,
author:req.body.author,
content:req.body.content
}
}, function (err, result) {
if (err) {
console.log(err);
} else {
console.log("Post Updated successfully");
res.redirect("/admin");
}
});
});
In my editpostID.ejs:
<form class="" action="/do-edit-post" method="post">
<div class="form-group">
<label>Title</label>
<input class="form-control" hidden="<%= post._id %>">
<input class="form-control" text="text" name="postTitle" value="<%= title %>">
<label>Author</label>
<input class="form-control" text="text" name="postAuthor" value="<%= author %>">
<label>Post</label>
<!-- Text area matching the selector specified in the TinyMCE configuration -->
<textarea id="mytextarea" class="form-control" name="postBody" rows="5" cols="30" value=<%- content %>> </textarea>
</div>
<button class="btn btn-warning" type="submit" name="button">Save</button>
</form>
I even tried adding a hidden input field of ._id but it's not saving. What am I missing?
First of all you should add a input name on your hidden input
<form class="" action="/do-edit-post" method="post">
<div class="form-group">
<label>Title</label>
<input class="form-control" type="hidden" value="<%= _id %>" name="postId"> //<-- name added here also you should send the id on input value
<input class="form-control" text="text" name="postTitle" value="<%= title %>">
<label>Author</label>
<input class="form-control" text="text" name="postAuthor" value="<%= author %>">
<label>Post</label>
<!-- Text area matching the selector specified in the TinyMCE configuration -->
<textarea id="mytextarea" class="form-control" name="postBody" rows="5" cols="30" value=<%- content %>> </textarea>
</div>
<button class="btn btn-warning" type="submit" name="button">Save</button>
</form>
Then on node side you can get the id like this
app.post('/do-edit-post/:id',async (req, res) => {
const requestedPostId = req.body.postId; // <-- get the id from the form
await Post.findByIdAndUpdate(requestedPostId , {
title: req.body.title,
author:req.body.author,
content:req.body.content
}).catch(err => {
if (err){
console.log(err)
}else{
console.log("Post Updated successfully");
res.redirect("/admin");
}
})
});

Node js Dropzone js - Upload file without submitting form

I am new in node js and trying to integrate single file upload using dropzone js. I want to upload image before submitting form. I have managed to call the upload action before submitting.
Here is my html code:
<form id="add_user" name="add_user" class="form-horizontal" action="/add-new-user" method="POST">
<div class="directory-bg text-center">
<div class="directory-overlay">
<span id="imageuploader">
<input name="profileimg" id="profileimg" type="hidden" value="">
<img id="ws_user_avatar" class="rounded-circle thumb-lg img-thumbnail dropzone" data-thumb="public/assets/images/users/user.png" src="public/assets/images/users/user.png" alt="Generic placeholder image">
<!--<div class="fallback">
<input name="image" id="image" type="file">
</div>-->
x
</span>
</div>
</div>
<div class="directory-content p-4">
<div class="mt-4">
<% if(success != "") {%>
<div class="alert alert-success" role="alert">
<strong>Done!</strong> <%= success %>
</div>
<% } %>
<div class="row">
<div class="col-md-12">
<div class="mb-3">
<label class="form-label" for="email">Email Address</label>
<input type="email" class="form-control" name="email" id="email" placeholder="Email Address" data-key="Email Address" autocomplete="off" autofill="false">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label class="form-label" for="fname">First Name</label>
<input type="text" class="form-control" name="fname" id="fname" placeholder="First Name" data-key="First Name" autocomplete="off" autofill="false">
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label class="form-label" for="lname">Last Name</label>
<input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" data-key="Last Name" autocomplete="off" autofill="false">
</div>
</div>
</div>
</div>
</div>
</form>
Here is the js code to handle dropzone event
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone(".dropzone", {
url: '/upload-image',
autoProcessQueue: false,
uploadMultiple: false,
maxFiles:2,
maxFilesize: 2,
createImageThumbnails:false,
hiddenInputContainer: "img.rounded-circle",
init: function(file) {
var prevFile = null;
this.on("addedfile", function(file) {
var $this = this;
setTimeout(function () {
if(file.status == "error"){
alert(file.previewTemplate.innerText);
} else {
if(prevFile){
$this.removeFile($this.files[0])
}
prevFile = file;
$("#user_avatar").attr('data-imgname', file.name);
previewImage($this);
}
}, 10);
});
}
});
function previewImage(input){
let fileReference = input.files && input.files[0];
if(fileReference){
var reader = new FileReader();
reader.onload = (event) => {
document.getElementById('user_avatar').src = event.target.result;
}
reader.readAsDataURL(fileReference);
}
}
$(document).on('click','#btn_submit', function(e){
e.preventDefault();
if(myDropzone.getQueuedFiles().length > 0){
myDropzone.processQueue();
} else {
$("#add_user").submit();
}
});
Here is the post handler code in router.js file:
const express = require('express');
const router = express.Router();
router.post('/upload-image', function(req, res){
console.log('requested inage',req.files.file.path);
// fs.readFile(request.files.file.path, function(err, data) {
// var newPath = __dirname + "/public/img/xspectra/customlogo.png";
// fs.writeFile(newPath, data, function (err) {
// console.log("Finished writing file..." + err);
// response.redirect("back");
// });
// });
});
When the dropzone myDropzone.processQueue() function called, I get an error message in the post handler function TypeError: Cannot read property 'file' of undefined.
Can anyone suggest me where I am doing wrong?
Many Thanks!
That means that the file uploaded didn't properly make it to your web server. Are you using express-fileupload on the nodejs side to handle the uploads?
If so, I recommend checking out this link on a really great tutorial

Update Operation in MongoDB with NodeJs

I am working on a Blog WebSite with CRUD operation I am able to achieve CRD operations but have issues with update One.
Issue:-
When I click on the edit button it opens the compose tab with the textfile loaded successfully but when I click on update it redirects to the home page but nothing Update, Please help me get out from this.
//This is the code for edit & Update Route
app.get("/posts/:postId/edit", (req, res) => {
Post.findById(req.params.postId, (err, post) => {
if (err) {
console.log(err);
} else {
res.render("edit", { post: post });
}
});
});
app.post("/posts/:postId/edit", (req, res) => {
Post.findByIdAndUpdate(
req.params.postId,
{
$set: {
title: req.body.title,
content: req.body.content,
},
},
(err, update) => {
if (err) {
console.log(err);
} else {
console.log("Post Updated");
res.redirect("/");
}
}
);
});
Form for the Edit/Update
//This is the Edit ejs file containing the update form
<form action="/posts/<%=post._id%>/edit/?_method=PUT" method="post">
<div class="mb-3">
<label for="post-title">Title</label>
<input class="form-control" id="post-title" name="postTitle" type="text" placeholder="Input title"
required autocomplete="off" value="<%=post.title%>">
</div>
<div class="mb-3">
<label for="postcontent">Post</label>
<textarea class="form-control text-area" id="postcontent" name="blog" rows="4" cols="50" required
placeholder="Start writing your blog ..............."><%=post.content%></textarea>
</div>
<button class="btn btn-primary publish-btn" type="submit" name="button">Update</button>
</form>
Your error is from the Ejs
You didn’t rename your req.body well to match your incoming data
You were meant to be used title instead of postTitle
And content instead of blog
Just edit your ejs to this and test gee
<form action="/posts/<%=post._id%>/edit/?_method=PUT" method="post">
<div class="mb-3">
<label for="post-title">Title</label>
<input class="form-control" id="post-title" name=“title" type="text" placeholder="Input title"
required autocomplete="off" value="<%=post.title%>">
</div>
<div class="mb-3">
<label for="postcontent">Post</label>
<textarea class="form-control text-area" id="postcontent" name="content" rows="4" cols="50" required
placeholder="Start writing your blog ..............."><%=post.content%></textarea>
</div>
<button class="btn btn-primary publish-btn" type="submit" name="button">Update</button>
</form>
If this answers your question mark it as done

Post request with a JWT

I have a route which posts in /verify/:token, where :token is a jwt, but in my view the form sends a post request to /verify/:token and then in my route logic I get a invalid jwt because :token is being send, how can I fix this?
<form action="/verify/:token" method="POST">
<div class="input-group form-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input id="passcode" type="text" class="form-control" name="passcode" placeholder="Pass Code" required>
</div>
<button type="submit" class="btn btn-primary" style="display: inline-block;">Verify</button>
</form>
Pass token to your form page router
router.get("/", function (req, res, next) {
jwt.sign({_id: user._id}, jwtSecret, { expiresIn: '5m' }).then((token) => {
res.render("postForm", {
token: token
});
});
});
now you can use token in hidden input field assuming you are using ejs in client
<form action="/verify" method="POST">
<div class="input-group form-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input id="token" type="hidden" class="form-control" name="token" value="<%= token %> ">
<input id="passcode" type="text" class="form-control" name="passcode" placeholder="Pass Code" required>
</div>
<button type="submit" class="btn btn-primary" style="display: inline-block;">Verify</button>
</form>
Assuming you have jQuery in the client side, you have to prevent the default action of form when it is submitted. Then you have to send the ajax request by taking the value of the input field
$('form').submit(function(e){
//prevent default
e.preventDefault();
let token = $('#passcode').val();
let url = "/verify/" + token;
$.post( url, function( data ) {
// Do something once the ajax call succeeds
}).fail(function() {
alert( "error" );
});
});

Calling a PUT to express from EJS

I am trying to call a restful api created in expressjs from EJS form.
I tried looking on google and stackoverflow, and trying lots of different methods.
orders.ejs:
<ul class="orders">
<% for(var i=0; i<orders.length; i++) {%>
<ul class="order">
<p> coffee_id <span><%= orders[i].name %></span>
amount: <span><%= orders[i].amount %></span>
quantity <span><%= orders[i].quantity %></span> </p>
</ul>
<% } %>
</ul>
<div>
<form action="/orders" method="POST" action="orders/?_method=PUT">
<input type="text" placeholder="username" name="username">
<input type="text" placeholder="coffee name" name="name">
<input type="number" placeholder="amount" name="amount">
<input type="number" placeholder="quantity" name="quantity">
<button type="submit" id="order" >Submit</button>
</form>
</div>
nodejs.app.js:
app.post('/orders', (req, res) => { // falta o EJS
db.collection('orders').save(req.body, (err, result) => {
if (err) return console.log(err)
console.log(req.body);
res.render('orders.ejs', {
put: true
});
})
})
app.put('/orders/:coffeeid/:quantity', function(req, res) { ...
}
This code works fine individually calling them from Postman with the right parameters, but I need to call them both when I submit the EJS form.
app.get('/orders/:coffeeid',function(req, res) {
db.collection('orders').find({_id:req.params.coffeeid}).toArray, function(error,result){
if(!error && result && quantity){
return res.render('orders.ejs',{orders: result, coffeeid:result.coffeeid, quantity:'7'}); // <-- pass coffeeid to view
}
}
});
I need to read quantity also from the form and check for stock in the PUT, so for now I fixed it at '7'units, but now Cannot GET /orders
route for get orders :
app.get('/orders',function(req, res) {
// fetch all orders and display it to view
});
route for display edit page of order by coffeeid :
app.get('/orders/:coffeeid',function(req, res) {
var coffeeid= req.params.coffeeid;
db.collection('orders').find({_id:coffeeid}).toArray,function(error,result){
if(!error && result){
return res.render('orders.ejs',{orders:result,coffeeid:result.coffeeid, quantity:'7'});
}
});
});
form :
<form action="/orders/<%=coffeeid%>" method="POST">
<input name="_method" type="hidden" value="PUT">
<input type="text" placeholder="username" name="username">
<input type="text" placeholder="coffee name" name="name">
<input type="number" placeholder="amount" name="amount" value="">
<input type="number" placeholder="quantity" name="quantity" value="<%=quantity%>">
<button type="submit" id="order" >Submit</button>
</form>
to update information route will be :
app.put('/orders/:coffeeid', function(req, res) {
var coffeeid= req.params.coffeeid;
var quantity= req.body.quantity;
// save to database
}

Resources