Sending email to user upon registration in react - javascript

I am working on an app with React as the base. I have created a registration page and want to send a verification code via email to the user once he registers. I have done the UI part, but have no idea on how to proceed and make it work. I have seen how emails are sent to the user upon registration in PHP, and want to implement the same in React.

Since you are using node, you'll be able to make use of the node mailer package. This allows you to send emails easily straight from node.
https://nodemailer.com/
Have a look at there site for all the details on how to get it setup!
Here is some psuedo code:
User.register(userDetails).then( (createdUser) => {
// Your user is created
// Now lets send them an email
var mailOptions = {
from: '"Info ?" <yoursite#yoursite.com>', // sender address
to: userDetails.email, // This can also contain an array of emails
subject: 'Thanks for registering with <your site name>',
// text: 'Hello world ?', // plaintext body
html: '<b>Some HTML here....</b>' // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
})

Related

Telegram bot payments - show receipt after successful payment

I have a Telegram bot that processes payments. The payments work as they should, however, I have not been able to show receipt after a successful payment.
The current behavior is:
user clicks on PAY button, fills the card information and pays for the service
payment is processed and message about successful transaction is sent
at this point, I would like for the PAY button to change to RECEIPT button
The current behavior on screenshot:
Desired behavior:
The desired behavior was screenshoted from chat with #ShopBot, which is mentioned in Telegram docs as a test tool.
The only mention about how the "receipt" is handled I could find in the Telegram docs were these two sentences at https://core.telegram.org/bots/payments :
If the invoice message was sent in the chat with #merchantbot, it becomes a Receipt in the UI for the user — they can open this receipt at any time and see all the details of the transaction.
If the message was sent to any other chat, the Pay button remains and can be used again. It is up to the merchant bot whether to actually accept multiple payments.
However, I don't understand how to achieve this in the code. As far as I know, the invoice message WAS sent to the chat with my bot (as in the first sentence) so it SHOULD become a Receipt.
The bot is written in Node.js and uses webhook to handle messages. The code section of the webhook important for this question:
router.route('/')
.post(async (req, res) => {
try {
// if pre_checkout_query is defined, there was an attempt for payment
if (req.body.pre_checkout_query) {
// use answerPreCheckoutQuery Telegram method
...
}
const message = req.body.message || req.body.edited_message;
// this means user's payment was successful
if (message.successful_payment) {
// success, deliver goods or services
// send message about successful payment
...
}
} catch (err) {
...
}
})
The invoice is sent with sendInvoice method like this:
const url = `https://api.telegram.org/bot${process.env.TELEGRAM_BOT_TOKEN}/sendInvoice`;
const response = await axios.get(url, {
params: {
chat_id: chatID,
title: 'SOME TITLE',
description: 'some decription',
payload: 'SOME-PAYLOAD',
provider_token: process.env.STRIPE_API_TOKEN,
currency: 'EUR',
prices: JSON.stringify([
{
label: 'some label',
amount: 200,
},
]),
},
});
The two methods from the API that are used for processing the payments are sendInvoice and answerPreCheckoutQuery but neither of them contains any argument that would possibly change the output the way I want. Am I missing something?
Note at the end: despite all this, the payments works. This is just a cosmetic change I would like to achieve.
I also had this problem, specify a parameter: start_parameter='unique-string'

Emit event for particular user if login functionality in application in Socket.io with Node.js

I have used methods socket.on and io.emit, And i got response to all users. But, i want to get response for particular user.
But my application contains login functionality and i followed this post on stackoverflow, and they are saying we need unique userId and socketId in an object for a particular user to emit an event for a particular user.
But i am getting the userId after login, But we want it when user connect to app.
So can anyone please help me with the same?
In your node.js, create a global array 'aryUser', each element contains the socketid and loginid.
node.js onConnect (new connection), add a new element to the array with the socketid and set loginid = empty.
after the user login, emit an event from client to the server, e.g:
socket.emit('userloginok', loginid)
in node.js, define a function:
socket.on('userloginok', loginid)
and in this function, search the aryUser with the socketid and replace the empty loginid inside the array element with the parm loginid.
in node.js, define the function:
socket.on('disconnect')
and in this function, search the aryUser, use aryUser.splice(i,1) to remove the user just disconnected.
that means, aryUser contains all users connected, some of them logined, some of them not logined. And you can use the socketid of the array to send message to particular user, and/or all users.
Example Source Code:
server.js
http://www.zephan.top/server.js
server.html
http://www.zephan.top/server.html.txt
rename server.html.txt to server.html, put server.html and server.js in the same directory, and run:
node server.js
Yes, you definitely need socketId in order to send and receive messages between two specific users.
UserId is required just to keep track of socketId associated with the particular user or you can manage it with some other way as well that's up to you.
As per your question, you have userId of the user and you need socketId of that user! So, in this case, you can pass userId when that particular connects to a socket server from the client side as shown in below snippet,
const socket = io(this.SOCKET_SERVER_BASE_URL, { query: `userId=${userId}` });
And you can read this user on nodejs server like this,
const userId= socket.request._query['userId'],
const socketId= socket.id
Now store this socketId in somewhere, for example, Redis or some sort of caching mechanism again up to you, just make sure fetching and retrieval should be fast.
Now while sending a message just pull the socketId from your cache and emit the message on that socketId by using below code,
io.to(socket.id).emit(`message-response`, {
message: 'hello'
});
I have written a complete blog post on this topic on both Angular and AngularJs, you can refer those as well.
Edit 1:
Part 1 =>
When your user completes the login request, then make the connection to the socket server.
Assuming you are using React Or Angular After a successful login you will redirect your user to home component(page). On the Home component(page) make the socket server connect by passing the userId just like this,
const socket = io(SOCKET_SERVER_BASE_URL, { query: `userId=${userId}` });
P.S. you can get userID from URL or maybe using a cookie that is up to you.
Once you receive this socket connection request on the server, then you can read the userID query and you can get socketId associated with it and store it in cache like this,
io.use( async (socket, next) => {
try {
await addSocketIdInCache({
userId: socket.request._query['userId'],
socketId: socket.id
});
next();
} catch (error) {
// Error
console.error(error);
}
});
Part 2 =>
Now, let's say you have a list of the users on the client side, and you want to send a message to particular users.
socket.emit(`message`, {
message: 'hello',
userId: userId
});
On the server side, fetch the socketId from the cache using UserId. Once you get the socketId from cache send a specific message like this,
io.to(socketId).emit(`message-response`, {
message: 'hello'
});
Hope this helps.

Get user's Info from post request of Nodemailer

i am using for our project in company the nodemailer, its working perfectly
fine.
I am wondering if its possible to get user's info automatically from the post request. for example i need to get the html variable like this:
html: 'Hello i am ${request.username} i sent this email to you'
this is how i need my request looks like:
var transporter = nodemailer.createTransport({
host: 'servername.com',
port: 25,
debug: true,
logger:true,
secure: false,
});
// i need the mail options like the following
var mailOptions = {
from: 'MYEMAIL#COMPANYNAME.com', // sender address (who sends)
to: 'MYEMAIL#COMPANYNAME.com', // list of receivers (who receives)
subject: 'this email sent from ${request.username} ', // Subject line
text: 'Hello world ', // plaintext body
html: 'this email sent from ${request.username}'
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
What you are asking is not possible (atleast ethically) unless you have username and email mapping available. But still to add a personal touch to email you can use part before "#" i.e. take this email for instance "your_name#domain.com", you can send email as
${request.username} will be "your_name"

Clear cache related to POST requests in Node.js

I'm using nodemailer to allow users to contact me via email. After submitting the form data, I'm redirected to my homepage (which is what I want), but if I try to refresh the page I get an alert message that says:
Confirm Form Resubmission
The page that you're looking for used information that you entered.
Returning to that page might cause any action you took to be repeated.
Do you want to continue?
I think this has something to do with the user's data being cached, so is there a way around this? I don't want people sending me multiple emails by accident, and I don't want them annoyed with an alert box every time they refresh. Here's my controller function:
module.exports.contactMessage = function(req, res) {
// html message sent to my email
var output = `
<p>You have a new contact request</p>
<h3>Contact Details</h3>
<ul>
<li>Name: ${req.body.name + ' ' + req.body.surname}</li>
<li>Email: ${req.body.email}</li>
</ul>
<h3>Message:</h3>
<p>${req.body.message}</p>
`;
var from = req.body.email;
var to = 'example#example.com';
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: 'smtp.gmail.email',
service: "Gmail",
auth: {
user: 'example#example.com',
pass: 'password'
},
tls: {
rejectUnauthorized:false
}
});
// setup email data with unicode symbols
let mailOptions = {
from: from, // sender address
to: to, // list of receivers
html: output // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message sent: %s', info.messageId);
res.render('index', {msg: 'Your message has been sent'});
});
};
Usually appending a random integer to the end of the url will cause the browser to reload the page because it does not match exactly what is in cache.
For example, https://www.google.com?318973187678123 will load the same page as https://www.google.com but will force the browser to not load from cache.
Note however, this random integer needs change each reload to work, so generate a new random integer each reload.

Sending a welcome email parse cloudcode with mailgun

I have a working mailgun server in my parse cloudcode for an iOS app. I have set up a series of emails to be triggered by status changes in the database. I have now set up a welcome email that was formerly hard coded into the app. I have it set up as an afterSave however during the app the user is saved more than once, causing the welcome to be triggered. Is there a way I can only send this out once, or do I have to make it specific to a new user registering in the function if that is possible. Thanks.
Parse.Cloud.afterSave(Parse.User, function(request) {
console.log("aftersave fired");
if(!request.user.existed()){
var email = "Hello and welcome";
var subject = "Welcome to W!";
var recipient = request.user.get("email");
console.log(recipient);
Mailgun.sendEmail({
to: "#gmail.com",
from: "#gmail.com",
subject: subject,
text: email
}, {
success: function(httpResponse) {
response.success();
},
error: function(httpResponse) {
response.success();
}
});
}
});
You can do something as simple as set a flag in a new column on the User class which indicates that they have been welcomed. When the user is saved, check that flag and decide wether to send or not (and update the flag).

Categories

Resources