鸿蒙5应用内支付:AGC IAP集成与测试指南
前言
随着鸿蒙操作系统(HarmonyOS)的不断发展,鸿蒙5带来了更强大的应用内支付(IAP)能力。AppGallery Connect(AGC)提供的IAP服务为开发者提供了便捷的应用内支付解决方案。本文将详细介绍如何在鸿蒙5应用中集成AGC IAP,并提供完整的代码示例和测试方法。
一、环境准备
在开始之前,请确保您已完成以下准备工作:
安装最新版DevEco Studio
注册华为开发者账号
在AppGallery Connect中创建项目和应用
开通应用内支付服务
二、项目配置
- 添加依赖
在模块级build.gradle文件中添加AGC和IAP相关依赖: 
dependencies {
implementation 'com.huawei.agconnect:agconnect-core:1.7.0.300'
implementation 'com.huawei.hms:iap:6.10.0.300'
}
2. 配置签名
在agconnect-services.json文件中配置应用签名信息:
{
"client": {
"app_id": "您的应用ID",
"cp_id": "您的CP ID",
"product_id": "您的产品ID"
},
"service": {
"iap": {
"store_id": "您的商店ID"
}
}
}
三、IAP核心功能实现
- 初始化IAP客户端
import iap from '@ohos.iap';
import agconnect from '@hw-agconnect/api'; 
export class IAPService {
private iapClient: iap.IAPClient;
constructor() {
// 初始化AGC
agconnect.instance().init();
// 创建IAP客户端
this.iapClient = iap.getIAPClient(agconnect.instance().getContext());
}
}
2. 查询商品信息
public async queryProducts(productIds: string[]): Promise<iap.ProductInfoResult> {
try {
const request: iap.ProductInfoReq = {
priceType: iap.PriceType.IN_APP_CONSUMABLE, // 可消费商品
productIds: productIds
};
const result = await this.iapClient.obtainProductInfo(request);
console.log('查询商品成功:', JSON.stringify(result));
return result;
} catch (err) {
console.error('查询商品失败:', JSON.stringify(err));
throw err;
}
}
3. 创建支付订单
public async createPurchase(productId: string, developerPayload?: string): Promise<iap.PurchaseResultInfo> {
try {
const request: iap.PurchaseIntentReq = {
productId: productId,
priceType: iap.PriceType.IN_APP_CONSUMABLE,
developerPayload: developerPayload || ''
};
const result = await this.iapClient.createPurchaseIntent(request);
console.log('创建订单成功:', JSON.stringify(result));
return result;
} catch (err) {
console.error('创建订单失败:', JSON.stringify(err));
throw err;
}
}
4. 确认订单
public async confirmPurchase(purchaseToken: string): Promise
try {
const request: iap.ConsumeOwnedPurchaseReq = {
purchaseToken: purchaseToken
};
await this.iapClient.consumeOwnedPurchase(request);
console.log('确认订单成功');
} catch (err) {
console.error('确认订单失败:', JSON.stringify(err));
throw err;
}
}
5. 查询历史订单
public async queryHistoryPurchases(): Promise<iap.OwnedPurchasesResult> {
try {
const request: iap.OwnedPurchasesReq = {
priceType: iap.PriceType.IN_APP_CONSUMABLE
};
const result = await this.iapClient.obtainOwnedPurchases(request);
console.log('查询历史订单成功:', JSON.stringify(result));
return result;
} catch (err) {
console.error('查询历史订单失败:', JSON.stringify(err));
throw err;
}
}
四、UI实现示例
以下是一个简单的商品购买页面实现:
import { IAPService } from '../services/IAPService';
@Entry
@Component
struct ProductPage {
private iapService: IAPService = new IAPService();
@State productList: Array
@State isLoading: boolean = true;
aboutToAppear() {
this.loadProducts();
}
async loadProducts() {
try {
const productIds = ['product1', 'product2', 'product3']; // 替换为您的商品ID
const result = await this.iapService.queryProducts(productIds);
this.productList = result.productInfoList;
this.isLoading = false;
} catch (err) {
console.error('加载商品失败:', err);
this.isLoading = false;
}
}
async buyProduct(productId: string) {
try {
const result = await this.iapService.createPurchase(productId);
// 处理支付结果
if (result.returnCode === 0) {
// 支付成功,确认订单
await this.iapService.confirmPurchase(result.purchaseToken);
promptAction.showToast({ message: '购买成功!' });
}
} catch (err) {
promptAction.showToast({ message: '购买失败: ' + err.message });
}
}
build() {
Column() {
if (this.isLoading) {
LoadingProgress()
.width(50)
.height(50)
Text('加载中...')
.margin({ top: 10 })
} else {
List({ space: 10 }) {
ForEach(this.productList, (product) => {
ListItem() {
Column() {
Text(product.productName)
.fontSize(18)
.fontWeight(FontWeight.Bold)
Text(product.productDesc)
.fontSize(14)
.margin({ top: 5 })
Text('价格: ' + product.price + product.currency)
.fontSize(16)
.margin({ top: 10 })
Button('购买')
.width('80%')
.margin({ top: 15 })
.onClick(() => {
this.buyProduct(product.productId);
})
}
.padding(15)
.width('100%')
}
.borderRadius(10)
.backgroundColor('#f5f5f5')
})
}
.width('100%')
.padding(10)
}
}
.width('100%')
.height('100%')
.padding(10)
}
}
五、测试与验证
- 沙盒测试环境配置
在AGC控制台配置沙盒测试账号: 
登录AppGallery Connect
进入"用户与权限" > "测试用户"
添加测试账号
为测试账号分配沙盒测试权限
2. 测试用例
import { describe, it, expect } from '@ohos/hypium';
import { IAPService } from '../../main/ets/services/IAPService';
const iapService = new IAPService();
describe('IAPServiceTest', () => {
it('testQueryProducts', 0, async () => {
try {
const result = await iapService.queryProducts(['product1']);
expect(result.returnCode).assertEqual(0);
expect(result.productInfoList.length).assertGreaterThan(0);
} catch (err) {
expect().assertFail('查询商品失败: ' + JSON.stringify(err));
}
});
it('testCreatePurchase', 0, async () => {
try {
const result = await iapService.createPurchase('product1', 'test_payload');
expect(result.returnCode).assertEqual(0);
expect(result.purchaseToken.length).assertGreaterThan(0);
  // 确认订单
  await iapService.confirmPurchase(result.purchaseToken);
} catch (err) {
  expect().assertFail('创建订单失败: ' + JSON.stringify(err));
}
});
it('testQueryHistoryPurchases', 0, async () => {
try {
const result = await iapService.queryHistoryPurchases();
expect(result.returnCode).assertEqual(0);
} catch (err) {
expect().assertFail('查询历史订单失败: ' + JSON.stringify(err));
}
});
});
3. 常见问题排查
支付失败错误码处理
function handleError(error) {
switch (error.code) {
case 60051: // 商品不存在
promptAction.showToast({ message: '商品不存在,请检查商品ID' });
break;
case 60052: // 商品已拥有
promptAction.showToast({ message: '您已购买过此商品' });
break;
case 60053: // 用户取消
promptAction.showToast({ message: '您已取消支付' });
break;
case 60054: // 支付失败
promptAction.showToast({ message: '支付失败,请重试' });
break;
default:
promptAction.showToast({ message: '发生错误: ' + error.message });
}
}
日志收集 在开发阶段,建议开启详细日志:
iap.setIAPLogLevel(iap.LogLevel.DEBUG);
六、最佳实践
支付流程优化
在支付前检查网络状态
提供支付中状态提示
处理支付超时情况
安全性考虑
不要在客户端存储敏感信息
验证支付结果签名
使用developerPayload防止重复支付
性能优化
缓存商品信息
异步加载支付SDK
减少不必要的支付状态查询
结语
通过本文的介绍,您应该已经掌握了在鸿蒙5应用中集成AGC IAP服务的关键步骤。从环境配置到核心功能实现,再到测试验证,完整的支付流程已经可以运行。在实际开发中,还需要根据具体业务需求进行适当调整,并严格遵守华为应用市场的支付规范。
                    
                
                
            
        
浙公网安备 33010602011771号