<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Chirag Bhardwaj</title>
    <description>The latest articles on DEV Community by Chirag Bhardwaj (@chiragbhardwaj).</description>
    <link>https://dev.to/chiragbhardwaj</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1167525%2F390c6106-d7d1-4fa9-8ce8-7f2c099be006.jpg</url>
      <title>DEV Community: Chirag Bhardwaj</title>
      <link>https://dev.to/chiragbhardwaj</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/chiragbhardwaj"/>
    <language>en</language>
    <item>
      <title>Reset Password</title>
      <dc:creator>Chirag Bhardwaj</dc:creator>
      <pubDate>Tue, 05 Dec 2023 11:41:26 +0000</pubDate>
      <link>https://dev.to/chiragbhardwaj/reset-password-37jn</link>
      <guid>https://dev.to/chiragbhardwaj/reset-password-37jn</guid>
      <description>&lt;p&gt;Resetting a password in any login page has become so common in the applications nowadays.&lt;/p&gt;

&lt;p&gt;this article gives you an insight of what are logics which are needed to add this feature to your react App.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;This is the simple logic that we need to implement:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--lQRxBzi_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w6qqxyww8wb8i0tqx064.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--lQRxBzi_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w6qqxyww8wb8i0tqx064.png" alt="Image description" width="800" height="695"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;then, next question that probably will come to your mind:&lt;/p&gt;

&lt;p&gt;1.how can we send OTP and how to verify OTP ?&lt;br&gt;
2.how to send mail to the user with OTP ?&lt;br&gt;
3.how to reset password against the DB ?&lt;br&gt;
4.how many endpoints are needed to perform the whole operation?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PREQUISITE&lt;/strong&gt; : you should have some knowledge about how to creating APIs and how to integrate in the frontend.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ENDPOINTS&lt;/strong&gt;:&lt;br&gt;
1- to generate the OTP, storing the OTP with email in the database and to send the OTP with email.(/reset)&lt;/p&gt;

&lt;p&gt;MODEL FOR OTP:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import mongoose, { Schema } from "mongoose";



const OTPSchema = new Schema({
    email:{
        type:String,
        required:true
    },
    otp:{
        type:String,
        required:true
    }
},{timestamps:true});



const OTPmodal = mongoose.model("OTP",OTPSchema);

export default OTPmodal;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;LOGICS FOR APIs : &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How to send OTPs and how to verify the OTP?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;step 1 : when user click on the forgot password then user is navigate to the otp-filling page.&lt;br&gt;
&lt;strong&gt;install through npm&lt;/strong&gt; : nodemailer,otp-generator,bcrypt&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
&amp;lt;your Router&amp;gt;.post("/sendOTPMail", async (req, res) =&amp;gt; {
  const { email } = req.body;
  const otp = "" + otpGenerator.generate(4, { digits: true, lowerCaseAlphabets: false, upperCaseAlphabets: false, specialChars: false });
  if (!email) {
    return res.status(400).json({
      message: "pls the mail properly"
    })
  }
  const emailRegex = /^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})$/;
  const isValid = () =&amp;gt; {
    return emailRegex.test(email);
  }
  if (!isValid) {
    return res.status(400).json({
      message: "your mail is not valid,but enter correct email"
    })
  }
  else {
    const data = await OTPmodal.findOne({ email })
    if (data) {
      const updatedata = await OTPmodal.findOneAndUpdate({ email: email }, { otp: otp });
      if (updatedata) {
        const transport = nodemailer.createTransport({
          service: "gmail",
          auth: {
            user: "",
            pass: ""
          }
        })

        let message = {
          from: "&amp;lt;YOUR Gmail&amp;gt;",
          to: email,
          subject: "recovery password reset OTP",
          html: `&amp;lt;p&amp;gt;your OTP : ${otp}&amp;lt;/p&amp;gt;`
        }
        transport.sendMail(message);
        return res.status(200).json({
          message: "recovery email sent"
        })
      }
      else{
        return res.status(500).json({
          message:"server side error"
        })
      }
    }
    else {
      const datacreate = await OTPmodal.create({
        email:email,
        otp:otp
      });
      if (datacreate) {
        const transport = nodemailer.createTransport({
          service: "gmail",
          auth: {
            user: "",
            pass: ""
          }
        })

        let message = {
          from: "&amp;lt;YOUR BUISNESS EMAIL&amp;gt;",
          to: email,
          subject: "recovery password reset OTP",
          html: `&amp;lt;p&amp;gt;your OTP : ${otp}&amp;lt;/p&amp;gt;`
        }
        transport.sendMail(message);
        return res.status(200).json({
          message: "recovery email sent"
        })
      }
    }
  }
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;so, what are we doing here?&lt;/p&gt;

&lt;p&gt;The API endpoint, "/sendOTPMail," handles password recovery by:&lt;/p&gt;

&lt;p&gt;1.Defining a POST route.&lt;br&gt;
2.Extracting email and generating a 4-digit OTP.&lt;br&gt;
3.Validating input, checking email presence and format.&lt;br&gt;
4.Updating or creating records in the OTP database.&lt;br&gt;
5.Using Nodemailer to email the OTP for password recovery.&lt;br&gt;
6.Responding with 200 for success, 500 for server errors.&lt;/p&gt;

&lt;p&gt;step 2: when user will enter the otp , how to verify that otp with the otp we have already stored in the DB?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;Route&amp;gt;.post("/verify",async(req,res)=&amp;gt;{
  const {userEmail,userOTP} =req.body;
 const data = await OTPmodal.findOne({email:userEmail});
 if(data.otp == userOTP){
  return res.status(200).json({
    message:"user is verified",
  })
 }
  return res.status(401).json({
    message:"incorrect password"
  })
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;so what are we doing here?&lt;br&gt;
1- we are fetching the data by finding against the email the user has written, that you can transfer through routes for payload.&lt;br&gt;
2- if the otp matches with user input , it will return a successful message.&lt;/p&gt;

&lt;p&gt;now, comes the question if user want to resend the email, then the above reset Api will again update the OTP generated recently against the email user has entered.&lt;br&gt;
The user will now be forwarded to the reset Page.&lt;/p&gt;

&lt;p&gt;step 3 :  To reset the password.(we are assuming that each user have the unique email)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;Route&amp;gt;.patch("/reset",async (req,res)=&amp;gt;{
 const email = req.body.email;

 const password = bcrypt.hashSync(req.body.password, 10);

  userModal.findOneAndUpdate({email:email},{password:password}).then((data,err)=&amp;gt;{
    if(data){
      return res.status(201).json({
        message:"data updated"
      })
    }
    if(err){
      return res.status(201).json({
        message:"user not found"
      })
    }
  })
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;How is it working?&lt;/p&gt;

&lt;p&gt;The code defines a route handler for a PATCH request to "/reset". It retrieves an email and password from the request body, hashes the password, and updates the user's password in the database using Mongoose. The response includes a success message if the update is successful and an appropriate message if the user is not found, both with a status of 201 (Created). The code could benefit from improvements, such as using asynchronous hashing and more robust error handling.&lt;br&gt;
After the data is update , user will redirected to the login page.&lt;/p&gt;

&lt;p&gt;Thank you for reading the post.&lt;br&gt;
You can comment your doubts as well.&lt;/p&gt;

</description>
      <category>react</category>
      <category>webdev</category>
      <category>beginners</category>
      <category>opensource</category>
    </item>
    <item>
      <title>How to integrate RazorPay Gateway into your ReactJS + express.js(frontend+backend)</title>
      <dc:creator>Chirag Bhardwaj</dc:creator>
      <pubDate>Sun, 19 Nov 2023 11:02:13 +0000</pubDate>
      <link>https://dev.to/chiragbhardwaj/how-to-integrate-razorpay-gateway-into-your-reactjs-expressjsfrontendbackend-11jm</link>
      <guid>https://dev.to/chiragbhardwaj/how-to-integrate-razorpay-gateway-into-your-reactjs-expressjsfrontendbackend-11jm</guid>
      <description>&lt;p&gt;&lt;strong&gt;Step 1&lt;/strong&gt;: you need to upload the script programmatically in reactJS.&lt;/p&gt;

&lt;p&gt;Add this in App.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useEffect } from "react";
import displayRazor from "./utils/paymentGateway";
function App() {

  //programatically adding the script in html

  const loadscript = (src)=&amp;gt;{
    return new Promise((resolve)=&amp;gt;{
      const script = document.createElement("script");
      script.src = src;
      script.onload = ()=&amp;gt;{
        resolve(true);
      }
      script.onerror = ()=&amp;gt;{
        resolve(false);
      }

      document.body.appendChild(script);
    })

  }
  // on page Load , we are adding script.
  useEffect(()=&amp;gt;{
  loadscript("http://checkout.razorpay.com/v1/checkout.js")
  },[])

  return(
   &amp;lt;&amp;gt;

   &amp;lt;button onClick={displayRazor}&amp;gt;Buy Now&amp;lt;/button&amp;gt;

   &amp;lt;/&amp;gt;
  )
  }

export default App
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;loadscript is taking src as the parameter which is returning a promise .&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;resolve is used by passing argument as true or false , indicating that script has been successfully loaded or not.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;DOM manipulation is used for creation and appending the element.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;"&lt;a href="http://checkout.razorpay.com/v1/checkout.js"&gt;http://checkout.razorpay.com/v1/checkout.js&lt;/a&gt;" is the endpoint provided by Razorpay for orders.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 2&lt;/strong&gt;:&lt;br&gt;
 Now we will create a function which will trigger a pop-up of razorPay on the screen.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;create utils &amp;gt; paymentGateway.js&lt;/strong&gt;&lt;br&gt;
(you can create folder of your choice , this is what i personally prefer)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;paymentGateway.js&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default async function displayRazor(){
const data = await fetch("http://localhost:3000/razorpay", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  } 
}).then((t) =&amp;gt; t.json());
const option = {
  key:"&amp;lt;your_key&amp;gt;",
  currency:data.currency,
  amount:data.amount,
  description:"",
  image:"http://localhost:3000/logo.jpg",
  handler:(res)=&amp;gt;{
   alert("order_id" + res.razorpay_order_id);
   alert("payment_id" + res.razorpay_payment_id);
  },
// name that will shown on the popUp
  prefill:{
    name:"",
    email:"",
    contact:""
  }
 }
 const paymentObject = new window.Razorpay(option);

 paymentObject.open();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;displayRazor function will be triggered on click.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;This will make a post request to the backend server.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;instance of razorpay which accepts option as a parameter object.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Backend:
&lt;/h2&gt;

&lt;p&gt;Note : in your package.json --&amp;gt; add type : "module"&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;step 1&lt;/strong&gt; : In cmd &lt;/p&gt;

&lt;p&gt;npm i express path cors shortid razorpay url&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;step 2&lt;/strong&gt;: add this in your index.js : &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;import all the required libraries
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import express from "express";
import path from "path";
import cors from "cors";
import shortid from "shortid";
import razorpay from "razorpay";
import { fileURLToPath } from "url";
import { dirname } from "path";
const PORT = 3000;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;step 3&lt;/strong&gt;: add a middleware for preventing cors error&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.use(cors())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;step 4&lt;/strong&gt;: create an instance of express:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const app = express();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;step 5&lt;/strong&gt; : create an instance of razorpay:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const razorpayInstance = new razorpay({
  key_id: "&amp;lt;key_id&amp;gt;",
  key_secret: "&amp;lt;key_secret&amp;gt;"
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;how to generate this key_id and key_secret will be explained in the end.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;step 6&lt;/strong&gt; : (optional) --&amp;gt; add logo.png in your root directory&lt;/p&gt;

&lt;p&gt;create a route handler for fetching the png:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.get("/logo.png", async (req, res) =&amp;gt; {
  try {
    // Use import.meta.url to get the current file's URL,
    // then convert it to the file path using fileURLToPath.
    const currentFilePath = fileURLToPath(import.meta.url);

    // Get the directory name using the dirname function.
    const currentDir = dirname(currentFilePath);

    // Create the path to the logo.png file.
    const imagePath = path.join(currentDir, "logo.png");

    // Send the file as a response
    res.sendFile(imagePath);
  } catch (error) {
    console.error("Error serving logo.png:", error);
    res.status(500).send("Internal Server Error");
  }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;fileURLToPath(import.meta.url): This is used to convert the file URL of the current module (where this code is located) to a file path.&lt;/li&gt;
&lt;li&gt;dirname(currentFilePath): This extracts the directory name from the file path.&lt;/li&gt;
&lt;li&gt;path.join(currentDir, "logo.png"): This creates the full file path by joining the directory path with the filename "logo.png".&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;step 7 :(important) create a route handler for the creating payment order&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.post("/razorpay",async (req,res)=&amp;gt;{
  const payment_capture = 1;  
// 1 means payment should be captured immediately
  const amount = 2;
  const currency = 'INR';
const option = {
  amount: amount *100,
  currency:currency,
  receipt: shortid.generate(),
  payment_capture
};
  try{
   const response = await razorpayInstance.orders.create(option);
   console.log(response);
     res.json({
      id:response.id,
      currency:response.currency,
      amount:response.amount
     })
  }
  catch(error){
   console.log (error);
  }

})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our whole backend and frontend part is completed.&lt;/p&gt;

&lt;p&gt;How to generate API keys in razorpay:&lt;/p&gt;

&lt;p&gt;step1 : visit &lt;a href="https://dashboard.razorpay.com/app/dashboard"&gt;razorpay&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;step 2 : search api&lt;/p&gt;

&lt;p&gt;step 3 : click on API keys&lt;/p&gt;

&lt;p&gt;step 4 : generate your own API keys and replace it in the above code.&lt;/p&gt;

&lt;p&gt;Github code : &lt;a href="https://github.com/chirag14252/RazorPaymentGateway"&gt;PaymentGatewayDemo&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
