0% found this document useful (0 votes)
24 views16 pages

e-commerce code

This document outlines the steps to create a fully functional e-commerce website using HTML, CSS, JavaScript, Node.js, Express, and MongoDB. It includes project structure, backend setup with CRUD operations, authentication, product management, and payment gateway integration. Additionally, it provides guidance on enhancing user experience, implementing user roles, and order management functionalities.

Uploaded by

Desolated guy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views16 pages

e-commerce code

This document outlines the steps to create a fully functional e-commerce website using HTML, CSS, JavaScript, Node.js, Express, and MongoDB. It includes project structure, backend setup with CRUD operations, authentication, product management, and payment gateway integration. Additionally, it provides guidance on enhancing user experience, implementing user roles, and order management functionalities.

Uploaded by

Desolated guy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Creating a fully functional e-commerce website with all the features you mentioned (CRUD

operations, authentication, and payment gateway) is a complex task that requires a


significant amount of code and setup. Below, I'll provide a simplified version of how you can
structure your project and implement these features using HTML, CSS, JavaScript, Node.js,
Express, and MongoDB.

### Project Structure

```
ecommerce-website/

├── client/ # Frontend files
│ ├── index.html
│ ├── styles.css
│ └── script.js

├── server/ # Backend files
│ ├── models/
│ │ └── User.js
│ │ └── Product.js
│ ├── routes/
│ │ └── auth.js
│ │ └── products.js
│ ├── config.js
│ ├── server.js
│ └── package.json

└── README.md
```

### Step 1: Setting Up the Backend

1. **Initialize the Node.js Project**

```bash
mkdir ecommerce-website
cd ecommerce-website
mkdir server
cd server
npm init -y
npm install express mongoose bcryptjs jsonwebtoken cors dotenv
```

2. **Create the Server File**

`server/server.js`

```javascript
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const authRoutes = require('./routes/auth');
const productRoutes = require('./routes/products');
require('dotenv').config();

const app = express();


app.use(cors());
app.use(express.json());

mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true,


useUnifiedTopology: true })
.then(() => console.log('MongoDB connected'))
.catch(err => console.log(err));

app.use('/api/auth', authRoutes);
app.use('/api/products', productRoutes);

const PORT = process.env.PORT || 5000;


app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
```

3. **Create User and Product Models**

`server/models/User.js`

```javascript
const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({


username: { type: String, required: true },
password: { type: String, required: true }
});

module.exports = mongoose.model('User ', UserSchema);


```

`server/models/Product.js`

```javascript
const mongoose = require('mongoose');

const ProductSchema = new mongoose.Schema({


name: { type: String, required: true },
price: { type: Number, required: true },
description: { type: String, required: true },
imageUrl: { type: String, required: true }
});

module.exports = mongoose.model('Product', ProductSchema);


```

4. **Create Authentication Routes**

`server/routes/auth.js`

```javascript
const express = require('express');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const router = express.Router();

// Sign Up
router.post('/signup', async (req, res) => {
const { username, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
const newUser = new User({ username, password: hashedPassword });
await newUser .save();
res.status(201).send('User created');
});

// Sign In
router.post('/signin', async (req, res) => {
const { username, password } = req.body;
const user = await User.findOne({ username });
if (!user) return res.status(400).send('User not found');

const isMatch = await bcrypt.compare(password, user.password);


if (!isMatch) return res.status(400).send('Invalid credentials');

const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET);


res.json({ token });
});

module.exports = router;
```

5. **Create Product Routes**

`server/routes/products.js`

```javascript
const express = require('express');
const Product = require('../models/Product');
const router = express.Router();

// Create Product
router.post('/', async (req, res) => {
const newProduct = new Product(req.body);
await newProduct.save();
res.status(201).send('Product created');
});

// Get All Products


router.get('/', async (req, res) => {
const products = await Product.find();
res.json(products);
});

// Update Product
router.put('/:id', async (req, res) => {
await Product.findByIdAndUpdate(req.params.id, req.body);
res.send('Product updated');
});

// Delete Product
router.delete('/:id', async (req, res) => {
await Product.findByIdAndDelete(req.params.id);
res.send('Product deleted ');
});

// Get Single Product


router.get('/:id', async (req, res) => {
const product = await Product.findById(req.params.id);
res.json(product);
});

module.exports = router;
```

### Step 2: Setting Up the Frontend

1. **Create HTML Structure**

`client/index.html`

```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>E-commerce Website</title>
</head>
<body>
<div id="app">
<h1>E-commerce Website</h1>
<div id="auth">
<h2>Sign In</h2>
<input type="text" id="username" placeholder="Username">
<input type="password" id="password" placeholder="Password">
<button onclick="signIn()">Sign In</button>
<h2>Sign Up</h2>
<button onclick="signUp()">Sign Up</button>
</div>
<div id="products"></div>
</div>
<script src="script.js"></script>
</body>
</html>
```

2. **Add CSS Styles**

`client/styles.css`

```css
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
}

#app {
max-width: 600px;
margin: auto;
}

h1, h2 {
text-align: center;
}

input {
display: block;
margin: 10px auto;
padding: 10px;
width: 80%;
}
button {
padding: 10px;
width: 80%;
margin: 10px auto;
cursor: pointer;
}
```

3. **Implement JavaScript Functionality**

`client/script.js`

```javascript
const apiUrl = 'http://localhost:5000/api';

async function signUp() {


const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
const response = await fetch(`${apiUrl}/auth/signup`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
const data = await response.text();
alert(data);
}

async function signIn() {


const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
const response = await fetch(`${apiUrl}/auth/signin`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
const data = await response.json();
if (data.token) {
localStorage.setItem('token', data.token);
alert('Sign in successful');
loadProducts();
} else {
alert(data);
}
}

async function loadProducts() {


const response = await fetch(`${apiUrl}/products`);
const products = await response.json();
const productsDiv = document.getElementById('products');
productsDiv.innerHTML = '';
products.forEach(product => {
productsDiv.innerHTML +=
`<div><h3>${product.name}</h3><p>${product.description}</p><p>Price:
$${product.price}</p></div>`;
});
}
```

### Step 3: Payment Gateway Integration

For payment gateway integration, you can use services like Stripe or PayPal. You would
typically set up a payment route in your backend and handle the payment processing in your
frontend.

### Step 4: Running the Application

1. **Start the Backend Server**

```bash
cd server
node server.js
```

2. **Open the Frontend**

Open `client/index.html` in your browser to access the e-commerce website.

This is a basic structure to get you started. You can expand upon this by adding more
features, improving the UI, and implementing error handling and validation. ### Step 5:
Enhancing the Application

1. **Add Product Upload Functionality**

To allow users to upload products, you can create a form in your HTML and handle file
uploads in your backend.

`client/index.html`

```html
<h2>Add Product</h2>
<input type="text" id="productName" placeholder="Product Name">
<input type="number" id="productPrice" placeholder="Product Price">
<input type="text" id="productDescription" placeholder="Product Description">
<input type="file" id="productImage">
<button onclick="addProduct()">Add Product</button>
```
`client/script.js`

```javascript
async function addProduct() {
const name = document.getElementById('productName').value;
const price = document.getElementById('productPrice').value;
const description = document.getElementById('productDescription').value;
const image = document.getElementById('productImage').files[0];

const formData = new FormData();


formData.append('name', name);
formData.append('price', price);
formData.append('description', description);
formData.append('image', image);

const response = await fetch(`${apiUrl}/products`, {


method: 'POST',
body: formData
});
const data = await response.text();
alert(data);
loadProducts();
}
```

2. **Update Product Route to Handle File Uploads**

You will need to install `multer` for handling file uploads.

```bash
npm install multer
```

`server/routes/products.js`

```javascript
const multer = require('multer');
const path = require('path');

const storage = multer.diskStorage({


destination: (req, file, cb) => {
cb(null, 'uploads/');
},
filename: (req, file, cb) => {
cb(null, Date.now() + path.extname(file.originalname));
}
});
const upload = multer({ storage });

router.post('/', upload.single('image'), async (req, res) => {


const newProduct = new Product({
name: req.body.name,
price: req.body.price,
description: req.body.description,
imageUrl: req.file.path
});
await newProduct.save();
res.status(201).send('Product created');
});
```

3. **Display Product Images**

Update the product display section in your HTML to show images.

`client/script.js`

```javascript
products.forEach(product => {
productsDiv.innerHTML += `<div><h3>${product.name}</h3><img
src="${product.imageUrl}" alt="${product.name}"
style="width:100px;height:100px;"><p>${product.description}</p><p>Price:
$${product.price}</p></div>`;
});
```

### Step 6: Implementing Payment Gateway

1. **Integrate Stripe for Payments**

Install the Stripe package in your backend.

```bash
npm install stripe
```

2. **Create Payment Route**

`server/routes/payment.js`

```javascript
const express = require('express');
const Stripe = require('stripe');
const router = express.Router();
const stripe = Stripe(process.env.STRIPE_SECRET_KEY);

router.post('/create-payment-intent', async (req, res) => {


const { amount } = req.body;
try {
const paymentIntent = await stripe.paymentIntents.create({
amount,
currency: 'usd',
});
res.send({ clientSecret: paymentIntent.client_secret });
} catch (error) {
res.status(500).send({ error: error.message });
}
});

module.exports = router;
```

3. **Frontend Payment Handling**

Add a payment button and handle the payment process in your frontend.

`client/index.html`

```html
<button onclick="pay()">Pay</button>
```

`client/script.js`

```javascript
async function pay() {
const response = await fetch(`${apiUrl}/payment/create-payment-intent`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ amount: 1000 }) // Example amount in cents
});
const { clientSecret } = await response.json();
// Use Stripe.js to handle the payment with the clientSecret
}
```

### Step 7: Final Touches

1. **Error Handling and Validation**

Ensure to add error handling and input validation in both frontend and backend to improve
user experience and security.
2. **Deployment**

Consider deploying your application using platforms like Heroku for the backend and Netlify
or Vercel for the frontend.

3. **Testing**

Thoroughly test all functionalities, including user authentication, product management, and
payment processing to ensure everything works as expected.

This setup provides a solid foundation for your e-commerce website, and you can continue
to build upon it with additional features like user roles, order management, product reviews,
and more. You can also enhance the user interface with frameworks like React or Vue.js for
a more dynamic experience. Consider implementing responsive design techniques to ensure
the website is mobile-friendly. Additionally, integrating analytics tools can help you track user
behavior and improve your site's performance over time. ### Step 8: Enhancing User
Experience

1. **Implementing User Roles**

You can add user roles (e.g., admin, customer) to manage permissions for different
functionalities. Update the User model to include a role field.

`server/models/User.js`

```javascript
const UserSchema = new mongoose.Schema({
username: { type: String, required: true },
password: { type: String, required: true },
role: { type: String, default: 'customer' } // Default role
});
```

2. **Admin Dashboard**

Create an admin dashboard to manage products and view orders. This can be a separate
HTML page accessible only to users with the admin role.

`client/admin.html`

```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Admin Dashboard</title>
</head>
<body>
<div id="admin">
<h1>Admin Dashboard</h1>
<div id="productManagement">
<h2>Manage Products</h2>
<button onclick="loadProducts()">Load Products</button>
<div id="adminProducts"></div>
</div>
</div>
<script src="admin.js"></script>
</body>
</html>
```

3. **Admin JavaScript Functionality**

Create a separate JavaScript file for admin functionalities.

`client/admin.js`

```javascript
async function loadProducts() {
const response = await fetch(`${apiUrl}/products`);
const products = await response.json();
const adminProductsDiv = document.getElementById('adminProducts');
adminProductsDiv.innerHTML = '';
products.forEach(product => {
adminProductsDiv.innerHTML += `<div><h3>${product.name}</h3><button
onclick="deleteProduct('${product._id}')">Delete</button></div>`;
});
}

async function deleteProduct(id) {


await fetch(`${apiUrl}/products/${id}`, {
method: 'DELETE'
});
loadProducts();
}
```

### Step 9: Order Management

1. **Create Order Model**

Add an Order model to manage user orders.


`server/models/Order.js`

```javascript
const mongoose = require('mongoose');

const OrderSchema = new mongoose.Schema({


userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User ' },
products: [{ productId: { type: mongoose.Schema.Types.ObjectId, ref: 'Product' }, quantity:
Number }],
totalAmount: { type: Number, required: true },
status: { type: String, default: 'pending' }
});

module.exports = mongoose.model('Order', OrderSchema);


```

2. **Create Order Routes**

Add routes to create and manage orders.

`server/routes/orders.js`

```javascript
const express = require('express');
const Order = require('../models/Order');
const router = express.Router();

// Create Order
router.post('/', async (req, res) => {
const newOrder = new Order(req.body);
await newOrder.save();
res.status(201).send('Order created');
});

// Get User Orders


router.get('/:userId', async (req, res) => {
const orders = await Order.find({ userId: req.params.userId });
res.json(orders);
});

module.exports = router;
```

3. **Frontend Order Handling**

Add functionality to place orders from the frontend.

`client/script.js`
```javascript
async function placeOrder() {
const token = localStorage.getItem('token');
const response = await fetch(`${apiUrl}/orders`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({ userId: /* get user ID */, products: /* selected products */,
totalAmount: /* total price */ })
});
const data = await response.text();
alert(data);
}
```

### Step 10: Finalizing the Application

1. **Testing and Debugging**

Conduct thorough testing of all features, including user authentication, product management,
order processing, and payment handling. Fix any bugs or issues that arise during testing.

2. **Security Enhancements**

Implement security measures such as input validation, sanitization, and rate limiting to
protect against common vulnerabilities like SQL injection and XSS attacks.

3. **Performance Optimization**

Optimize the application for performance by implementing caching strategies, optimizing


database queries, and minimizing the size of assets.

4. **Documentation**

Create comprehensive documentation for your application, including setup instructions, API
endpoints, and usage guidelines. This will help other developers understand and contribute
to your project.

5. **Deployment**

Deploy your application to a cloud service provider. Ensure that your environment variables
are configured correctly for production, and set up a CI/CD pipeline if possible for easier
updates.

6. **Monitoring and Analytics**


Integrate monitoring tools to track application performance and user interactions. Use
analytics to gather insights on user behavior, which can inform future improvements and
features.

7. **User Feedback**

Consider implementing a feedback mechanism to gather user opinions and suggestions.


This can help you identify areas for improvement and prioritize new features based on user
needs.

8. **Continuous Improvement**

Plan for regular updates and enhancements to the application. Stay informed about new
technologies and best practices in web development to keep your e-commerce site
competitive and user-friendly.

By following these steps, you can create a robust e-commerce platform that meets user
needs and provides a seamless shopping experience. ### Step 11: Advanced Features

1. **Search Functionality**

Implement a search feature to allow users to find products easily. You can add a search bar
in your HTML and filter products based on user input.

`client/index.html`

```html
<input type="text" id="search" placeholder="Search products" oninput="searchProducts()">
```

`client/script.js`

```javascript
async function searchProducts() {
const query = document.getElementById('search').value.toLowerCase();
const response = await fetch(`${apiUrl}/products`);
const products = await response.json();
const filteredProducts = products.filter(product =>
product.name.toLowerCase().includes(query));
displayProducts(filteredProducts);
}

function displayProducts(products) {
const productsDiv = document.getElementById('products');
productsDiv.innerHTML = '';
products.forEach(product => {
productsDiv.innerHTML +=
`<div><h3>${product.name}</h3><p>${product.description}</p><p>Price:
$${product.price}</p></div>`;
});
}
```

2. **User Reviews and Ratings**

Allow users to leave reviews and ratings for products. Create a Review model and
corresponding routes.

`server/models/Review.js`

```javascript
const mongoose = require('mongoose');

const ReviewSchema = new mongoose.Schema({


productId: { type: mongoose.Schema.Types.ObjectId, ref: 'Product' },
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User ' },
rating: { type: Number, required: true },
comment: { type: String }
});

module.exports = mongoose.model('Review', ReviewSchema);


```

`server/routes/reviews.js`

```javascript
const express = require('express');
const Review = require('../models/Review');
const router = expre

You might also like