以下是一个外卖App开发的核心模块说明及部分示例代码框架,由于篇幅限制,将重点呈现关键功能实现逻辑:
一、技术选型
– 前端:React Native(跨平台)+ Redux状态管理
– 后端:Node.js + Express框架
– 数据库:MongoDB + Redis缓存
– 支付:支付宝/微信支付SDK
– 地图:高德地图API
– 推送:Firebase Cloud Messaging
二、核心模块代码示例
1. 用户认证模块(JWT实现)
“`javascript
// 后端路由
app.post(‘/api/login’, async (req, res) => {
const { phone, password } = req.body;
const user = await User.findOne({ phone });
if (!user || !bcrypt.compareSync(password, user.password)) {
return res.status(401).json({ error: ‘认证失败’ });
}
const token = jwt.sign(
{ userId: user._id },
process.env.JWT_SECRET,
{ expiresIn: ‘7d’ }
);
res.json({ token, userInfo: { name: user.name, avatar: user.avatar } });
});
“`
2. 餐厅列表接口
“`javascript
// 餐厅搜索接口
router.get(‘/restaurants’, async (req, res) => {
const { latitude, longitude, keyword } = req.query;
const query = {
location: {
$near: {
$geometry: {
type: “Point”,
coordinates: [longitude, latitude]
},
$maxDistance: 5000 // 5公里范围
}
}
};
if (keyword) {
query.$text = { $search: keyword };
}
const restaurants = await Restaurant.find(query)
.limit(20)
.select(‘name rating deliveryFee minOrder logo’);
res.json(restaurants);
});
“`
3. 购物车功能实现(Redux)
“`javascript
// 前端购物车Reducer
const cartReducer = (state = [], action) => {
switch (action.type) {
case ‘ADD_ITEM’:
const existing = state.find(item => item.id === action.payload.id);
if (existing) {
return state.map(item =>
item.id === action.payload.id
? {…item, quantity: item.quantity + 1}
: item
);
}
return […state, {…action.payload, quantity: 1}];
case ‘UPDATE_QUANTITY’:
return state.map(item =>
item.id === action.payload.id
? {…item, quantity: action.payload.quantity}
: item
);
default:
return state;
}
};
“`
4. 订单创建逻辑
“`javascript
// 创建订单服务
const createOrder = async (userId, items, address) => {
const session = await mongoose.startSession();
session.startTransaction();
try {
// 库存检查
for (const item of items) {
const product = await Product.findById(item.productId).session(session);
if (product.stock < item.quantity) { throw new Error(`${product.name}库存不足`); } product.stock -= item.quantity; await product.save(); } // 创建订单 const order = new Order({ user: userId, items, total: calculateTotal(items), address, status: 'pending_payment' }); await order.save({ session }); await session.commitTransaction(); return order; } catch (error) { await session.abortTransaction(); throw error; } finally { session.endSession(); } }; ``` 三、关键功能实现要点 1. 实时定位: - 使用高德地图JS API实现LBS服务 - 通过Geolocation API获取用户坐标 - MongoDB地理空间索引加速附近商家查询 2. 支付集成: ```javascript // 微信支付示例 const unifiedOrder = async (orderId, totalFee) => {
const params = {
appid: WX_APPID,
mch_id: WX_MCHID,
nonce_str: generateNonce(),
body: ‘外卖订单支付’,
out_trade_no: orderId,
total_fee: totalFee 100,
spbill_create_ip: ‘用户IP’,
notify_url: ‘https://api.example.com/pay/notify’,
trade_type: ‘APP’
};
const sign = generateWXSign(params);
const response = await axios.post(‘https://api.mch.weixin.qq.com/pay/unifiedorder’,
buildXML({…params, sign}));
return parseXML(response.data);
};
“`
3. 订单状态推送:
– 使用WebSocket实现实时状态更新
– 订单状态变更时触发Firebase推送
– 后台任务监控超时未支付订单
四、安全防护措施
1. JWT Token设置合理有效期
2. 敏感数据(密码)使用bcrypt加密存储
3. SQL注入防护(使用ORM框架)
4. 支付接口HTTPS加密传输
5. 限流机制(express-rate-limit)
这个实现方案包含了外卖系统的核心模块,实际开发中需要根据具体需求补充第三方服务集成、性能优化和详细测试环节。建议使用TypeScript增强类型安全,并配合Jest进行单元测试。