鸿蒙电商购物车全栈项目:订单管理、支付管理与 AI 原生
核心价值与学习目标
本文完成鸿蒙电商购物车全栈项目的核心业务功能实现。
学习目标:
- 掌握订单管理的设计与实现;
- 实现创建订单、查看订单、取消订单;
- 理解支付管理的设计与实现;
- 实现微信支付、支付宝支付;
- 掌握 AI 原生的设计与实现;
- 实现 AI 搜索、AI 推荐、AI 客服;
- 优化订单管理、支付管理、AI 原生的用户体验(响应速度、数据安全、用户反馈)。
学习重点:
- 鸿蒙 APP 订单管理的开发流程;
- 订单管理的分类与使用场景;
- 支付管理的设计与实现;
- AI 原生的设计与实现。
一、订单管理基础
1.1 订单管理定义
订单管理是指对应用的订单进行管理,主要包括以下方面:
- 创建订单:用户可以创建订单;
- 查看订单:用户可以查看订单;
- 取消订单:用户可以取消订单;
- 订单状态管理:管理订单的状态。
1.2 订单管理架构
订单管理采用分层架构,由以下部分组成:
- 订单服务层:负责订单的业务逻辑;
- 订单数据层:负责订单的数据存储与管理;
- 订单接口层:负责订单的接口设计与实现;
- 订单展示层:负责订单的界面渲染与交互。
二、订单管理实战
2.1 实战目标
基于项目架构,实现以下功能:
- 创建订单:用户可以创建订单;
- 查看订单:用户可以查看订单;
- 取消订单:用户可以取消订单。
2.2 订单管理工具类
entry/src/main/ets/utils/OrderManagementUtil.ets
import order from '@ohos.order';
// 订单管理工具类
export class OrderManagementUtil {
private static instance: OrderManagementUtil | null = null;
private orderHelper: order.OrderHelper | null = null;
// 单例模式
static getInstance(): OrderManagementUtil {
if (!OrderManagementUtil.instance) {
OrderManagementUtil.instance = new OrderManagementUtil();
}
return OrderManagementUtil.instance;
}
// 初始化订单管理
async init(): Promise<void> {
if (!this.orderHelper) {
this.orderHelper = order.createOrderHelper();
}
}
// 创建订单
async createOrder(cartItemIds: Array<number>): Promise<order.CreateOrderResult> {
if (!this.orderHelper) {
return null;
}
const result = await this.orderHelper.createOrder(cartItemIds);
return result;
}
// 查看订单
async getOrderList(): Promise<Array<order.Order>> {
if (!this.orderHelper) {
return [];
}
const result = await this.orderHelper.getOrderList();
return result;
}
// 取消订单
async cancelOrder(orderId: number): Promise<order.CancelOrderResult> {
if (!this.orderHelper) {
return null;
}
const result = await this.orderHelper.cancelOrder(orderId);
return result;
}
// 确认收货
async confirmOrder(orderId: number): Promise<order.ConfirmOrderResult> {
if (!this.orderHelper) {
return null;
}
const result = await this.orderHelper.confirmOrder(orderId);
return result;
}
}
2.3 订单创建应用
entry/src/main/ets/pages/CreateOrderPage.ets
import { OrderManagementUtil } from '../utils/OrderManagementUtil';
import { CartManagementUtil } from '../utils/CartManagementUtil';
@Entry
@Component
struct CreateOrderPage {
@State order: order.Order | null = null;
@State cartItems: Array<cart.CartItem> = [];
@State totalPrice: number = 0;
build() {
Column({ space: 16 }) {
if (this.cartItems.length > 0) {
Text('订单详情').fontSize(18).fontWeight(FontWeight.Bold).textColor('#000000');
ListComponent({ data: this.cartItems, renderItem: (item: cart.CartItem, index: number) => {
Row({ space: 16 }) {
Image(item.avatarUrl).width(80).height(80).objectFit(ImageFit.Cover).borderRadius(8);
Column({ space: 8 }) {
Text(item.name).fontSize(16).fontWeight(FontWeight.Bold).textColor('#000000');
Text(item.description).fontSize(14).textColor('#666666').maxLines(2).textOverflow({ overflow: TextOverflow.Ellipsis });
Text(`¥${item.price}`).fontSize(16).fontWeight(FontWeight.Bold).textColor('#FF0000');
}.layoutWeight(1);
Text(`×${item.quantity}`).fontSize(14).textColor('#666666');
}.width('100%').height('auto').padding(16).backgroundColor('#FFFFFF').borderRadius(8).margin({ bottom: 8 });
}, onItemClick: (item: cart.CartItem, index: number) => {
router.pushUrl({ url: '/pages/ProductDetailPage', params: { productId: item.productId }});
}});
Row({ space: 16 }) {
Text('总价格:').fontSize(16).fontWeight(FontWeight.Bold).textColor('#000000');
Text(`¥${this.totalPrice}`).fontSize(18).fontWeight(FontWeight.Bold).textColor('#FF0000');
}.width('100%').height('auto').justifyContent(FlexAlign.End).padding(16).backgroundColor('#FFFFFF').borderRadius(8);
ButtonComponent({ text: '提交订单', onClick: async () => {
await this.createOrder();
}, disabled: this.cartItems.length === 0 });
}
}.width('100%').height('100%').padding(16).backgroundColor('#F5F5F5');
}
aboutToAppear() {
OrderManagementUtil.getInstance().init();
CartManagementUtil.getInstance().init();
this.getCartData();
}
async getCartData(): Promise<void> {
this.cartItems = await CartManagementUtil.getInstance().getCartList();
this.totalPrice = this.cartItems.reduce((sum, item) => sum + item.price * item.quantity, 0);
}
async createOrder(): Promise<void> {
const cartItemIds = this.cartItems.map(item => item.cartItemId);
const result = await OrderManagementUtil.getInstance().createOrder(cartItemIds);
if (result.success) {
promptAction.showToast({ message: '订单创建成功' });
await CartManagementUtil.getInstance().clearCart();
router.pushUrl({ url: '/pages/OrderListPage' });
} else {
promptAction.showToast({ message: '订单创建失败' });
}
}
}
2.4 订单列表应用
entry/src/main/ets/pages/OrderListPage.ets
import { OrderManagementUtil } from '../utils/OrderManagementUtil';
@Entry
@Component
struct OrderListPage {
@State orderList: Array<order.Order> = [];
build() {
Column({ space: 16 }) {
ListComponent({ data: this.orderList, renderItem: (item: order.Order, index: number) => {
Row({ space: 16 }) {
Column({ space: 8 }) {
Text(`订单号:${item.orderId}`).fontSize(14).textColor('#666666');
Text(`创建时间:${item.createTime}`).fontSize(14).textColor('#666666');
Text(`订单状态:${this.getOrderStatusText(item.orderStatus)}`).fontSize(14).textColor(this.getOrderStatusColor(item.orderStatus));
Text(`总价格:¥${item.totalPrice}`).fontSize(16).fontWeight(FontWeight.Bold).textColor('#000000');
}.layoutWeight(1);
Row({ space: 8 }) {
if (item.orderStatus === '待支付') {
ButtonComponent({ text: '立即支付', onClick: async () => {
await this.payOrder(item.orderId);
}, disabled: false });
}
if (item.orderStatus === '待发货' || item.orderStatus === '待收货') {
ButtonComponent({ text: '取消订单', onClick: async () => {
await this.cancelOrder(item.orderId);
}, disabled: false });
}
if (item.orderStatus === '待收货') {
ButtonComponent({ text: '确认收货', onClick: async () => {
await this.confirmOrder(item.orderId);
}, disabled: false });
}
}.width('auto').height('auto');
}.width('100%').height('auto').padding(16).backgroundColor('#FFFFFF').borderRadius(8).margin({ bottom: 8 });
}, onItemClick: (item: order.Order, index: number) => {
router.pushUrl({ url: '/pages/OrderDetailPage', params: { orderId: item.orderId }});
}});
}.width('100%').height('100%').padding(16).backgroundColor('#F5F5F5');
}
aboutToAppear() {
OrderManagementUtil.getInstance().init();
this.getOrderList();
}
async getOrderList(): Promise<void> {
this.orderList = await OrderManagementUtil.getInstance().getOrderList();
}
async cancelOrder(orderId: number): Promise<void> {
const result = await OrderManagementUtil.getInstance().cancelOrder(orderId);
if (result.success) {
promptAction.showToast({ message: '订单取消成功' });
this.getOrderList();
} else {
promptAction.showToast({ message: '订单取消失败' });
}
}
async confirmOrder(orderId: number): Promise<void> {
const result = await OrderManagementUtil.getInstance().confirmOrder(orderId);
if (result.success) {
promptAction.showToast({ message: '确认收货成功' });
this.getOrderList();
} else {
promptAction.showToast({ message: '确认收货失败' });
}
}
async payOrder(orderId: number): Promise<void> {
router.pushUrl({ url: '/pages/PaymentPage', params: { orderId: orderId }});
}
getOrderStatusText(orderStatus: string): string {
switch (orderStatus) {
case '待支付': return '待支付';
case '待发货': return '待发货';
case '待收货': return '待收货';
case '已完成': return '已完成';
case '已取消': return '已取消';
default: return '未知状态';
}
}
getOrderStatusColor(orderStatus: string): string {
switch (orderStatus) {
case '待支付': return '#FF0000';
case '待发货': return '#FFA500';
case '待收货': return '#008000';
case '已完成': return '#0000FF';
case '已取消': return '#666666';
default: return '#000000';
}
}
}
三、支付管理实战
3.1 实战目标
基于项目架构,实现以下功能:
- 微信支付:实现微信支付功能;
- 支付宝支付:实现支付宝支付功能。
3.2 支付管理工具类
entry/src/main/ets/utils/PaymentManagementUtil.ets
import payment from '@ohos.payment';
// 支付管理工具类
export class PaymentManagementUtil {
private static instance: PaymentManagementUtil | null = null;
private paymentHelper: payment.PaymentHelper | null = null;
// 单例模式
static getInstance(): PaymentManagementUtil {
if (!PaymentManagementUtil.instance) {
PaymentManagementUtil.instance = new PaymentManagementUtil();
}
return PaymentManagementUtil.instance;
}
// 初始化支付管理
async init(): Promise<void> {
if (!this.paymentHelper) {
this.paymentHelper = payment.createPaymentHelper();
}
}
// 微信支付
async wechatPay(orderId: number): Promise<payment.WechatPayResult> {
if (!this.paymentHelper) {
return null;
}
const result = await this.paymentHelper.wechatPay(orderId);
return result;
}
// 支付宝支付
async alipay(orderId: number): Promise<payment.AlipayResult> {
if (!this.paymentHelper) {
return null;
}
const result = await this.paymentHelper.alipay(orderId);
return result;
}
}
3.3 支付应用
entry/src/main/ets/pages/PaymentPage.ets
import { PaymentManagementUtil } from '../utils/PaymentManagementUtil';
import { OrderManagementUtil } from '../utils/OrderManagementUtil';
@Entry
@Component
struct PaymentPage {
@State order: order.Order | null = null;
@State paymentMethod: string = 'wechat';
@State orderId: number = 0;
build() {
Column({ space: 16 }) {
if (this.order) {
Text(`订单号:${this.order.orderId}`).fontSize(14).textColor('#666666');
Text(`创建时间:${this.order.createTime}`).fontSize(14).textColor('#666666');
Text(`总价格:¥${this.order.totalPrice}`).fontSize(18).fontWeight(FontWeight.Bold).textColor('#FF0000');
Text('支付方式:').fontSize(14).textColor('#000000');
RadioContainer({ name: 'paymentMethod', value: this.paymentMethod }) {
Radio({ value: 'wechat', name: 'paymentMethod' }) {
Text('微信支付').fontSize(14).textColor('#000000');
}.onChange((value: string) => {
this.paymentMethod = value;
});
Radio({ value: 'alipay', name: 'paymentMethod' }) {
Text('支付宝支付').fontSize(14).textColor('#000000');
}.onChange((value: string) => {
this.paymentMethod = value;
});
}.width('100%').height('auto');
ButtonComponent({ text: '立即支付', onClick: async () => {
await this.pay();
}, disabled: !this.order });
}
}.width('100%').height('100%').padding(16).backgroundColor('#F5F5F5');
}
aboutToAppear() {
PaymentManagementUtil.getInstance().init();
OrderManagementUtil.getInstance().init();
this.getOrderDetail();
}
async getOrderDetail(): Promise<void> {
const params = router.getParams() as { orderId: number };
this.orderId = params.orderId;
this.order = await OrderManagementUtil.getInstance().getOrderDetail(this.orderId);
}
async pay(): Promise<void> {
let result: payment.WechatPayResult | payment.AlipayResult | null;
if (this.paymentMethod === 'wechat') {
result = await PaymentManagementUtil.getInstance().wechatPay(this.orderId);
} else {
result = await PaymentManagementUtil.getInstance().alipay(this.orderId);
}
if (result?.success) {
promptAction.showToast({ message: '支付成功' });
router.pushUrl({ url: '/pages/OrderListPage' });
} else {
promptAction.showToast({ message: '支付失败' });
}
}
}
四、AI 原生实战
4.1 实战目标
基于项目架构,实现以下功能:
- AI 搜索:实现 AI 搜索功能;
- AI 推荐:实现 AI 推荐功能;
- AI 客服:实现 AI 客服功能。
4.2 AI 搜索实现
1. AI 搜索工具类
entry/src/main/ets/utils/AISearchUtil.ets
import ai from '@ohos.ai';
// AI 搜索工具类
export class AISearchUtil {
private static instance: AISearchUtil | null = null;
private aiHelper: ai.AIHelper | null = null;
// 单例模式
static getInstance(): AISearchUtil {
if (!AISearchUtil.instance) {
AISearchUtil.instance = new AISearchUtil();
}
return AISearchUtil.instance;
}
// 初始化 AI 搜索
async init(): Promise<void> {
if (!this.aiHelper) {
this.aiHelper = ai.createAIHelper();
}
}
// AI 搜索
async aiSearch(keyword: string): Promise<Array<product.Product>> {
if (!this.aiHelper) {
return [];
}
const result = await this.aiHelper.aiSearch(keyword);
return result;
}
}
2. AI 搜索应用
entry/src/main/ets/pages/AISearchPage.ets
import { AISearchUtil } from '../utils/AISearchUtil';
@Entry
@Component
struct AISearchPage {
@State searchKeyword: string = '';
@State productList: Array<product.Product> = [];
build() {
Column({ space: 16 }) {
InputComponent({ placeholder: '请输入搜索关键词', value: this.searchKeyword, onChange: (value: string) => {
this.searchKeyword = value;
}, type: InputType.Normal });
ButtonComponent({ text: 'AI 搜索', onClick: async () => {
await this.aiSearch();
}, disabled: !this.searchKeyword });
ListComponent({ data: this.productList, renderItem: (item: product.Product, index: number) => {
Row({ space: 16 }) {
Image(item.avatarUrl).width(80).height(80).objectFit(ImageFit.Cover).borderRadius(8);
Column({ space: 8 }) {
Text(item.name).fontSize(16).fontWeight(FontWeight.Bold).textColor('#000000');
Text(item.description).fontSize(14).textColor('#666666').maxLines(2).textOverflow({ overflow: TextOverflow.Ellipsis });
Text(`¥${item.price}`).fontSize(16).fontWeight(FontWeight.Bold).textColor('#FF0000');
}.layoutWeight(1);
ButtonComponent({ text: '查看详情', onClick: () => {
router.pushUrl({ url: '/pages/ProductDetailPage', params: { productId: item.productId }});
}, disabled: false });
}.width('100%').height('auto').padding(16).backgroundColor('#FFFFFF').borderRadius(8).margin({ bottom: 8 });
}, onItemClick: (item: product.Product, index: number) => {
router.pushUrl({ url: '/pages/ProductDetailPage', params: { productId: item.productId }});
}});
}.width('100%').height('100%').padding(16).backgroundColor('#F5F5F5');
}
aboutToAppear() {
AISearchUtil.getInstance().init();
}
async aiSearch(): Promise<void> {
this.productList = await AISearchUtil.getInstance().aiSearch(this.searchKeyword);
}
}
4.3 AI 推荐实现
1. AI 推荐工具类
entry/src/main/ets/utils/AIRecommendationUtil.ets
import ai from '@ohos.ai';
// AI 推荐工具类
export class AIRecommendationUtil {
private static instance: AIRecommendationUtil | null = null;
private aiHelper: ai.AIHelper | null = null;
// 单例模式
static getInstance(): AIRecommendationUtil {
if (!AIRecommendationUtil.instance) {
AIRecommendationUtil.instance = new AIRecommendationUtil();
}
return AIRecommendationUtil.instance;
}
// 初始化 AI 推荐
async init(): Promise<void> {
if (!this.aiHelper) {
this.aiHelper = ai.createAIHelper();
}
}
// AI 推荐
async aiRecommendation(): Promise<Array<product.Product>> {
if (!this.aiHelper) {
return [];
}
const result = await this.aiHelper.aiRecommendation();
return result;
}
}
2. AI 推荐应用
entry/src/main/ets/pages/AIRecommendationPage.ets
import { AIRecommendationUtil } from '../utils/AIRecommendationUtil';
@Entry
@Component
struct AIRecommendationPage {
@State productList: Array<product.Product> = [];
build() {
Column({ space: 16 }) {
Text('AI 推荐商品').fontSize(18).fontWeight(FontWeight.Bold).textColor('#000000');
ListComponent({ data: this.productList, renderItem: (item: product.Product, index: number) => {
Row({ space: 16 }) {
Image(item.avatarUrl).width(80).height(80).objectFit(ImageFit.Cover).borderRadius(8);
Column({ space: 8 }) {
Text(item.name).fontSize(16).fontWeight(FontWeight.Bold).textColor('#000000');
Text(item.description).fontSize(14).textColor('#666666').maxLines(2).textOverflow({ overflow: TextOverflow.Ellipsis });
Text(`¥${item.price}`).fontSize(16).fontWeight(FontWeight.Bold).textColor('#FF0000');
}.layoutWeight(1);
ButtonComponent({ text: '查看详情', onClick: () => {
router.pushUrl({ url: '/pages/ProductDetailPage', params: { productId: item.productId }});
}, disabled: false });
}.width('100%').height('auto').padding(16).backgroundColor('#FFFFFF').borderRadius(8).margin({ bottom: 8 });
}, onItemClick: (item: product.Product, index: number) => {
router.pushUrl({ url: '/pages/ProductDetailPage', params: { productId: item.productId }});
}});
}.width('100%').height('100%').padding(16).backgroundColor('#F5F5F5');
}
aboutToAppear() {
AIRecommendationUtil.getInstance().init();
this.getAIRecommendation();
}
async getAIRecommendation(): Promise<void> {
this.productList = await AIRecommendationUtil.getInstance().aiRecommendation();
}
}
4.4 AI 客服实现
1. AI 客服工具类
entry/src/main/ets/utils/AICustomerServiceUtil.ets
import ai from '@ohos.ai';
// AI 客服工具类
export class AICustomerServiceUtil {
private static instance: AICustomerServiceUtil | null = null;
private aiHelper: ai.AIHelper | null = null;
// 单例模式
static getInstance(): AICustomerServiceUtil {
if (!AICustomerServiceUtil.instance) {
AICustomerServiceUtil.instance = new AICustomerServiceUtil();
}
return AICustomerServiceUtil.instance;
}
// 初始化 AI 客服
async init(): Promise<void> {
if (!this.aiHelper) {
this.aiHelper = ai.createAIHelper();
}
}
// AI 客服
async aiCustomerService(question: string): Promise<ai.AICustomerServiceResult> {
if (!this.aiHelper) {
return null;
}
const result = await this.aiHelper.aiCustomerService(question);
return result;
}
}
2. AI 客服应用
entry/src/main/ets/pages/AICustomerServicePage.ets
import { AICustomerServiceUtil } from '../utils/AICustomerServiceUtil';
@Entry
@Component
struct AICustomerServicePage {
@State question: string = '';
@State answer: string = '';
build() {
Column({ space: 16 }) {
Text('AI 客服').fontSize(18).fontWeight(FontWeight.Bold).textColor('#000000');
InputComponent({ placeholder: '请输入您的问题', value: this.question, onChange: (value: string) => {
this.question = value;
}, type: InputType.Normal });
ButtonComponent({ text: '发送', onClick: async () => {
await this.sendQuestion();
}, disabled: !this.question });
if (this.answer) {
Text('AI 回答:').fontSize(14).textColor('#000000');
Text(this.answer).fontSize(14).textColor('#666666').maxLines(10).textOverflow({ overflow: TextOverflow.Ellipsis });
}
}.width('100%').height('100%').padding(16).backgroundColor('#F5F5F5');
}
aboutToAppear() {
AICustomerServiceUtil.getInstance().init();
}
async sendQuestion(): Promise<void> {
const result = await AICustomerServiceUtil.getInstance().aiCustomerService(this.question);
if (result?.success) {
this.answer = result.answer;
} else {
this.answer = '抱歉,未能找到相关答案';
}
}
}
五、项目配置与部署
5.1 配置文件修改
在 entry/src/main/module.json5 中添加订单管理、支付管理、AI 原生配置:
{
"module": {
"requestPermissions": [/* ... */],
"abilities": [/* ... */],
"widgets": [/* ... */],
"pages": [/* ... */]
}
}
5.2 项目部署
- 编译项目:在 DevEco Studio 中点击「Build」→「Build HAP」,编译项目。
- 部署到设备:将编译后的 HAP 文件部署到鸿蒙设备上。
- 测试功能:
- 在应用中查看创建订单的效果;
- 在应用中查看查看订单的效果;
- 在应用中查看取消订单的效果;
- 在应用中查看微信支付的效果;
- 在应用中查看支付宝支付的效果;
- 在应用中查看 AI 搜索的效果;
- 在应用中查看 AI 推荐的效果;
- 在应用中查看 AI 客服的效果。
六、项目运行与效果验证
6.1 效果验证
- 订单管理:创建订单、查看订单、取消订单;
- 支付管理:微信支付、支付宝支付;
- AI 原生:AI 搜索、AI 推荐、AI 客服。
七、总结
本文完成了鸿蒙电商购物车全栈项目的核心业务功能实现:
- 鸿蒙 APP 订单管理的定义与架构;
- 创建订单、查看订单、取消订单的实现;
- 支付管理的设计与实现;
- 微信支付、支付宝支付的实现;
- AI 原生的设计与实现;
- AI 搜索、AI 推荐、AI 客服的实现。


