【实战】鸿蒙5电商应用:AGC支付+分析+远程配置综合案例
引言
本文将带您开发一个基于鸿蒙5的电商应用,整合AppGallery Connect(AGC)的核心服务:支付系统、分析服务和远程配置。通过这个实战案例,您将学习如何将这些服务无缝集成到鸿蒙应用中,提升电商应用的商业能力和用户体验。
项目准备
- 创建AGC项目
首先在AppGallery Connect控制台:
创建新项目
启用"应用内支付"、"分析服务"和"远程配置"服务
下载agconnect-services.json配置文件
2. 初始化鸿蒙项目
ohos create hwmall --template @ohos/ets-template
支付系统集成
- 配置支付模块
在entry/build.gradle中添加依赖:
dependencies {
implementation 'com.huawei.agconnect:agconnect-apms-harmony:1.6.5.300'
implementation 'com.huawei.hms:iap-harmony:6.4.0.300'
}
2. 支付服务封装
创建PayService.ets:
import iap from '@hw-hms/iap';
import agconnect from '@hw-agconnect/core-harmony';
export class PayService {
private static instance: PayService = new PayService();
private constructor() {
agconnect.instance().init(getContext());
}
public static get(): PayService {
return this.instance;
}
// 查询商品信息
async queryProducts(productIds: string[]): Promise<ProductInfo[]> {
try {
const result = await iap.createProductDataHelper().obtainProductInfo({
priceType: iap.PriceType.IN_APP_CONSUMABLE,
productIds: productIds
});
return result.productInfoList;
} catch (err) {
console.error('查询商品失败:', err);
throw err;
}
}
// 创建支付订单
async createOrder(productId: string): Promise<OrderResult> {
try {
const result = await iap.createOrder({
productId: productId,
priceType: iap.PriceType.IN_APP_CONSUMABLE,
developerPayload: 'hwmall_' + new Date().getTime()
});
// 记录支付事件
this.logPaymentEvent('create_order', productId);
return result;
} catch (err) {
console.error('创建订单失败:', err);
throw err;
}
}
// 确认订单
async confirmOrder(purchaseToken: string): Promise<void> {
try {
await iap.consumeOwnedPurchase({
purchaseToken: purchaseToken
});
// 记录支付成功事件
this.logPaymentEvent('payment_success', purchaseToken);
} catch (err) {
console.error('确认订单失败:', err);
throw err;
}
}
// 记录支付事件
private logPaymentEvent(event: string, params: string) {
const analytics = agconnect.instance().getAnalytics();
analytics.onEvent(event, {
'product_id': params,
'timestamp': new Date().toISOString()
});
}
}
3. 支付页面实现
创建PaymentPage.ets:
import { PayService } from '../services/PayService';
@Entry
@Component
struct PaymentPage {
@State productList: ProductInfo[] = [];
@State selectedProduct: ProductInfo | null = null;
aboutToAppear() {
// 加载商品列表
this.loadProducts();
}
async loadProducts() {
try {
this.productList = await PayService.get().queryProducts([
'product_vip_monthly',
'product_coins_100',
'product_premium'
]);
} catch (err) {
console.error('加载商品失败:', err);
}
}
build() {
Column() {
// 商品列表
List({ space: 10 }) {
ForEach(this.productList, (product: ProductInfo) => {
ListItem() {
ProductItem({
product: product,
onSelected: (p: ProductInfo) => {
this.selectedProduct = p;
}
})
}
})
}
.width('100%')
.layoutWeight(1)
// 支付按钮
Button('立即购买', { type: ButtonType.Capsule })
.width('80%')
.height(50)
.margin(20)
.onClick(async () => {
if (this.selectedProduct) {
await this.purchaseProduct(this.selectedProduct.productId);
}
})
.enabled(!!this.selectedProduct)
}
}
async purchaseProduct(productId: string) {
try {
const orderResult = await PayService.get().createOrder(productId);
const confirmResult = await PayService.get().confirmOrder(orderResult.purchaseToken);
// 支付成功处理
promptAction.showToast({
message: '支付成功!',
duration: 2000
});
// 返回上一页
router.back();
} catch (err) {
promptAction.showToast({
message: '支付失败: ' + err.message,
duration: 3000
});
}
}
}
分析服务集成
- 用户行为分析
创建AnalyticsService.ets:
import agconnect from '@hw-agconnect/core-harmony';
export class AnalyticsService {
private static instance: AnalyticsService = new AnalyticsService();
private analytics = agconnect.instance().getAnalytics();
public static get(): AnalyticsService {
return this.instance;
}
// 记录页面访问
trackPageView(pageName: string) {
this.analytics.onEvent('page_view', {
'page_name': pageName,
'timestamp': new Date().toISOString()
});
}
// 记录用户行为
trackUserAction(action: string, params: object = {}) {
this.analytics.onEvent(action, {
...params,
'user_id': this.getUserId(),
'timestamp': new Date().toISOString()
});
}
// 设置用户属性
setUserProfile(profile: object) {
this.analytics.setUserProfile({
...profile,
'last_active': new Date().toISOString()
});
}
private getUserId(): string {
// 实际项目中应从用户系统获取
return 'user_' + Math.random().toString(36).substr(2, 9);
}
}
2. 在页面中使用分析服务
修改HomePage.ets:
import { AnalyticsService } from '../services/AnalyticsService';
@Entry
@Component
struct HomePage {
aboutToAppear() {
// 记录页面访问
AnalyticsService.get().trackPageView('home_page');
// 设置用户属性
AnalyticsService.get().setUserProfile({
'user_level': 'standard',
'first_visit': false
});
}
build() {
Column() {
// 页面内容...
Button('浏览商品', { type: ButtonType.Capsule })
.onClick(() => {
// 记录用户行为
AnalyticsService.get().trackUserAction('click_browse_products');
router.push({ url: 'pages/ProductListPage' });
})
}
}
}
远程配置集成
- 远程配置服务
创建RemoteConfigService.ets:
import agconnect from '@hw-agconnect/core-harmony';
export class RemoteConfigService {
private static instance: RemoteConfigService = new RemoteConfigService();
private config = agconnect.instance().getRemoteConfig();
public static get(): RemoteConfigService {
return this.instance;
}
// 初始化配置
async initialize() {
// 设置默认值
const defaults = {
'feature_payment_enabled': true,
'promo_banner_text': '夏季大促销,全场5折起!',
'homepage_layout_version': 'v1',
'max_checkout_items': 10
};
await this.config.applyDefault(defaults);
// 获取最新配置
try {
await this.config.fetch(0);
await this.config.apply();
} catch (err) {
console.error('获取远程配置失败:', err);
}
}
// 获取配置值
getValue(key: string, defaultValue: any = null): any {
return this.config.getValue(key) ?? defaultValue;
}
// 监听配置变化
onConfigChanged(callback: (changedKeys: string[]) => void) {
this.config.onRemoteConfigUpdate((changedKeys) => {
callback(changedKeys);
});
}
}
2. 在应用启动时初始化
修改EntryAbility.ets:
import { RemoteConfigService } from '../services/RemoteConfigService';
export default class EntryAbility extends Ability {
onCreate(want, launchParam) {
// 初始化AGC
agconnect.instance().init(this.context);
// 初始化远程配置
RemoteConfigService.get().initialize().then(() => {
console.log('远程配置初始化完成');
});
// 监听配置变化
RemoteConfigService.get().onConfigChanged((changedKeys) => {
console.log('配置已更新:', changedKeys);
// 可以在这里通知UI更新
});
}
}
3. 在页面中使用远程配置
修改HomePage.ets:
import { RemoteConfigService } from '../services/RemoteConfigService';
@Entry
@Component
struct HomePage {
@State promoText: string = '加载中...';
@State paymentEnabled: boolean = true;
aboutToAppear() {
// 从远程配置获取促销文本
this.promoText = RemoteConfigService.get().getValue('promo_banner_text');
// 检查支付功能是否开启
this.paymentEnabled = RemoteConfigService.get().getValue('feature_payment_enabled', true);
}
build() {
Column() {
// 促销横幅
Text(this.promoText)
.fontSize(16)
.fontColor(Color.Red)
.margin(10)
// 支付按钮(根据配置显示/隐藏)
if (this.paymentEnabled) {
Button('立即购买', { type: ButtonType.Capsule })
// 按钮样式...
}
}
}
}
电商核心功能整合
- 购物车服务
创建CartService.ets:
import { AnalyticsService } from './AnalyticsService';
import { RemoteConfigService } from './RemoteConfigService';
export class CartService {
private static instance: CartService = new CartService();
private items: CartItem[] = [];
private maxItems: number = 10;
public static get(): CartService {
return this.instance;
}
constructor() {
// 从远程配置获取最大商品数量
this.maxItems = RemoteConfigService.get().getValue('max_checkout_items', 10);
}
// 添加商品到购物车
addItem(product: Product, quantity: number = 1) {
// 检查是否超过最大数量
if (this.items.length >= this.maxItems) {
throw new Error(`购物车商品数量不能超过${this.maxItems}件`);
}
const existingItem = this.items.find(item => item.product.id === product.id);
if (existingItem) {
existingItem.quantity += quantity;
} else {
this.items.push({ product, quantity });
}
// 记录分析事件
AnalyticsService.get().trackUserAction('add_to_cart', {
product_id: product.id,
quantity: quantity
});
}
// 获取购物车商品
getItems(): CartItem[] {
return [...this.items];
}
// 清空购物车
clear() {
this.items = [];
}
}
2. 订单服务
创建OrderService.ets:
import { PayService } from './PayService';
import { AnalyticsService } from './AnalyticsService';
import { RemoteConfigService } from './RemoteConfigService';
export class OrderService {
private static instance: OrderService = new OrderService();
public static get(): OrderService {
return this.instance;
}
// 创建订单
async createOrder(cartItems: CartItem[]): Promise<Order> {
// 检查支付功能是否开启
const paymentEnabled = RemoteConfigService.get().getValue('feature_payment_enabled', true);
if (!paymentEnabled) {
throw new Error('支付功能暂时不可用');
}
// 计算总价
const total = cartItems.reduce((sum, item) => {
return sum + (item.product.price * item.quantity);
}, 0);
// 创建订单记录
const order: Order = {
id: 'order_' + new Date().getTime(),
items: cartItems,
total: total,
status: 'pending',
createdAt: new Date()
};
// 记录分析事件
AnalyticsService.get().trackUserAction('create_order', {
order_id: order.id,
total_amount: total,
item_count: cartItems.length
});
return order;
}
// 支付订单
async payOrder(order: Order): Promise<PaymentResult> {
try {
// 在实际应用中,这里应该调用支付接口
const paymentResult = await PayService.get().createOrder('checkout_' + order.id);
// 更新订单状态
order.status = 'paid';
order.paymentId = paymentResult.purchaseToken;
// 记录分析事件
AnalyticsService.get().trackUserAction('payment_success', {
order_id: order.id,
payment_id: order.paymentId,
amount: order.total
});
return { success: true, order };
} catch (err) {
// 记录失败事件
AnalyticsService.get().trackUserAction('payment_failed', {
order_id: order.id,
error: err.message
});
throw err;
}
}
}
项目结构与最佳实践
- 推荐项目结构
hwmall/
├── entry/
│ ├── src/
│ │ ├── main/
│ │ │ ├── ets/
│ │ │ │ ├── pages/ # 页面组件
│ │ │ │ ├── services/ # 服务层
│ │ │ │ │ ├── AnalyticsService.ets
│ │ │ │ │ ├── PayService.ets
│ │ │ │ │ ├── RemoteConfigService.ets
│ │ │ │ │ ├── CartService.ets
│ │ │ │ │ └── OrderService.ets
│ │ │ │ ├── models/ # 数据模型
│ │ │ │ ├── utils/ # 工具类
│ │ │ │ └── EntryAbility.ets # 应用入口
│ │ │ └── resources/ # 资源文件
│ │ └── module.json5 # 模块配置
│ └── build.gradle # 模块构建配置
└── build.gradle # 项目构建配置 - 最佳实践建议
安全支付:
所有支付操作应在服务端验证
使用AGC的应用内支付SDK提供的安全机制
定期检查订单状态,防止未支付成功的订单被标记为已支付
分析优化:
定义清晰的事件命名规范
避免收集敏感用户信息
使用用户分群功能分析不同用户群的行为差异
远程配置:
为所有配置项设置合理的默认值
使用分层策略管理不同用户群体的配置
重大变更前先进行A/B测试
性能监控:
使用AGC的性能监控服务跟踪关键操作耗时
设置性能阈值报警
总结
本文通过一个鸿蒙5电商应用实战案例,展示了如何整合AGC的三大核心服务:
支付系统:实现安全可靠的应用内购买流程
分析服务:跟踪用户行为,优化业务决策
远程配置:动态调整应用功能和界面,无需发布新版本
这些服务的组合使用可以显著提升电商应用的商业能力和运营效率。通过本文提供的代码示例,您可以快速在自己的鸿蒙5应用中实现这些功能,并根据实际需求进行扩展。

浙公网安备 33010602011771号