Skip to content

Commit da839b9

Browse files
committed
add pay chat
1 parent ec77c0f commit da839b9

File tree

10 files changed

+169
-10
lines changed

10 files changed

+169
-10
lines changed

Diff for: package-lock.json

+24-6
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Diff for: package.json

+1
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747
"sequelize-typescript": "^2.1.6",
4848
"sinon": "^18.0.0",
4949
"socket.io": "^4.7.5",
50+
"stripe": "^16.2.0",
5051
"supertest": "^7.0.0",
5152
"swagger-jsdoc": "^6.2.8",
5253
"swagger-ui-express": "^5.0.0",

Diff for: src/controllers/Payment.ts

+99
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
import express, { Request, Response } from "express";
2+
import Stripe from "stripe";
3+
import dotenv from "dotenv";
4+
import { findOrderById, findProductById } from "../services/paymentService";
5+
6+
dotenv.config();
7+
8+
const stripe = new Stripe(`${process.env.STRIPE_SECRET_KEY}`);
9+
export const checkout = async (req: Request, res: Response) => {
10+
try {
11+
const orderId = req.params.id;
12+
const order = await findOrderById(orderId);
13+
if (!order) {
14+
return res.status(404).json({ message: "Order not found" });
15+
}
16+
const line_items: any[] = await Promise.all(
17+
order.products.map(async (item: any) => {
18+
const productDetails:any = await findProductById(item.productId);
19+
const unit_amount = Math.round(productDetails!.price * 100);
20+
return {
21+
price_data: {
22+
currency: "usd",
23+
product_data: {
24+
name: productDetails?.name,
25+
images: [productDetails?.image[0]],
26+
},
27+
unit_amount: unit_amount,
28+
},
29+
quantity: item.quantity,
30+
};
31+
})
32+
);
33+
console.log(line_items)
34+
35+
36+
const session = await stripe.checkout.sessions.create({
37+
line_items,
38+
mode: "payment",
39+
success_url: process.env.SUCCESS_PAYMENT_URL,
40+
cancel_url: process.env.CANCEL_PAYMENT_URL,
41+
metadata: {
42+
orderId: orderId,
43+
},
44+
});
45+
46+
47+
res.status(200).json({ url: session.url });
48+
} catch (error: any) {
49+
res.status(500).json({ message: error.message });
50+
}
51+
};
52+
53+
export const webhook = async (req: Request, res: Response) => {
54+
const sig: any = req.headers["stripe-signature"];
55+
const webhookSecret: any = process.env.WEBHOOK_SECRET_KEY;
56+
let event: any;
57+
try {
58+
event = stripe.webhooks.constructEvent(req.body, sig, webhookSecret);
59+
} catch (err: any) {
60+
console.log(`⚠️ Webhook signature verification failed.`, err.message);
61+
return res.status(400).send(`Webhook Error: ${err.message}`);
62+
}
63+
64+
switch (event.type) {
65+
case "checkout.session.completed":
66+
const session = event.data.object;
67+
68+
try {
69+
const lineItems = await stripe.checkout.sessions.listLineItems(
70+
session.id
71+
);
72+
73+
const orderId = session.metadata.orderId;
74+
const order = await findOrderById(orderId);
75+
if (order) {
76+
order.status = "paid";
77+
await order.save();
78+
} else {
79+
console.error("Order not found:", orderId);
80+
}
81+
} catch (err) {
82+
console.error("Error processing session completed event:", err);
83+
}
84+
break;
85+
86+
case "payment_intent.succeeded":
87+
const paymentIntent = event.data.object;
88+
console.log("Payment Intent succeeded: ", paymentIntent);
89+
break;
90+
case "payment_method.attached":
91+
const paymentMethod = event.data.object;
92+
console.log("Payment Method attached: ", paymentMethod);
93+
break;
94+
95+
default:
96+
console.log(`Unhandled event type ${event.type}`);
97+
}
98+
res.json({ received: true });
99+
};

Diff for: src/controllers/cart.controller.ts

+4-1
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,10 @@ export const getCart = async (req: Request, res: Response) => {
6666
if (!cart) {
6767
return res.status(404).json({ message: "Cart not found" });
6868
}
69-
const cartitem = await CartItem.findAll({ where: { cartId: cart.cartId } });
69+
const cartitem = await CartItem.findAll({ where: { cartId: cart.cartId }, include: {
70+
model: Product,
71+
as: "Product"
72+
} });
7073

7174
return res.status(200).json({ cartitem });
7275
} catch (error: any) {

Diff for: src/controllers/checkout.controller.ts

+3-2
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { v4 as uuidv4 } from 'uuid';
66

77

88
export const createOrder = async (req: Request, res: Response) => {
9-
const { userId, deliveryAddress, paymentMethod } = req.body;
9+
const { userId, deliveryAddress, paymentMethod,client } = req.body;
1010
if(!userId || !deliveryAddress || !paymentMethod) {
1111
return res.status(400).json({ message: 'All fields are required' })
1212
}
@@ -37,7 +37,8 @@ export const createOrder = async (req: Request, res: Response) => {
3737
paymentMethod,
3838
status: 'pending',
3939
products: orderItems,
40-
totalAmount: totalAmount
40+
totalAmount: totalAmount,
41+
client
4142
});
4243
await CartItem.destroy({ where: { cartId: cart.cartId } });
4344
res.status(201).json({ message: 'Order placed successfully', order });

Diff for: src/database/models/cartitem.ts

+4
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,10 @@ class CartItem extends Model {
1414
foreignKey: "cartId",
1515
as: "cart",
1616
});
17+
CartItem.belongsTo(models.Product,{
18+
foreignKey: "productId",
19+
as: "Product"
20+
})
1721
}
1822
static initModel(sequelize: Sequelize) {
1923
CartItem.init(

Diff for: src/database/models/order.ts

+1
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ class Order extends Model {
2525
userId: { type: DataTypes.STRING, allowNull: false },
2626
paymentMethod: { type: DataTypes.INTEGER, allowNull: false },
2727
status: { type: DataTypes.STRING, allowNull: false },
28+
client: { type: DataTypes.STRING, allowNull: false },
2829
products: { type: DataTypes.JSONB, allowNull: false },
2930
totalAmount: {type:DataTypes.INTEGER,allowNull: false},
3031
expectedDeliveryDate: {type: DataTypes.DATE, allowNull: true}

Diff for: src/index.ts

+7
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,13 @@ app.use(cors({
5858
}
5959
));
6060
app.use(cookieParser());
61+
app.use((req, res, next) => {
62+
if (req.originalUrl === '/webhook') {
63+
next();
64+
} else {
65+
express.json()(req, res, next);
66+
}
67+
});
6168
app.use(express.urlencoded({ extended: true }));
6269
app.use(
6370
session({

Diff for: src/routes/checkout.router.ts

+14-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,20 @@
1-
import express from 'express'
1+
import express, { Request, Response } from 'express'
22
import { createOrder } from '../controllers/checkout.controller'
3+
import { checkout, webhook } from '../controllers/Payment';
4+
import { VerifyAccessToken } from '../middleware/verfiyToken';
35
const router = express.Router()
46

57
router.post('/checkout', createOrder)
68

9+
router.post("/payment/:id", VerifyAccessToken, checkout);
10+
11+
router.post('/webhook', express.raw({ type: 'application/json' }), webhook);
12+
13+
router.get("/success", async(req:Request,res:Response)=>{
14+
res.send("Succesfully")
15+
});
16+
router.get("/cancel", async(req:Request,res:Response)=>{
17+
res.send("Cancel")
18+
});
19+
720
export default router

Diff for: src/services/paymentService.ts

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import Order from "../database/models/order"
2+
import Product from "../database/models/product"
3+
4+
5+
export const findOrderById = async (orderId: any)=>{
6+
const order = await Order.findByPk(orderId)
7+
return order
8+
}
9+
export const findProductById = async (productId:any)=>{
10+
const product = await Product.findByPk(productId)
11+
return product
12+
}

0 commit comments

Comments
 (0)