鸿蒙生活缴费小程序开发指南
开发环境准备
- 安装DevEco Studio:下载并安装最新版DevEco Studio(支持HarmonyOS 5.0)
- 配置HarmonyOS SDK:确保已安装HarmonyOS 5.0 SDK
- 创建项目:选择"Application" -> "Empty Ability"模板
项目结构
LifePaymentApp/
├── entry/
│ ├── src/
│ │ ├── main/
│ │ │ ├── ets/
│ │ │ │ ├── pages/
│ │ │ │ ├── utils/
│ │ │ │ ├── model/
│ │ │ │ └── app.ets
│ │ │ ├── resources/
│ │ │ └── config.json
核心功能实现
1. 用户认证模块
import userAuth from '@ohos.userIAM.userAuth';
@Entry
@Component
struct LoginPage {
@State phoneNumber: string = ''
@State smsCode: string = ''
async sendSmsCode() {
try {
const result = await userAuth.sendSmsCode(this.phoneNumber);
promptAction.showToast({ message: '验证码已发送' });
} catch (error) {
promptAction.showToast({ message: '发送失败: ' + error.message });
}
}
async verifyLogin() {
try {
const result = await userAuth.verifySmsCode(this.phoneNumber, this.smsCode);
if (result) {
router.replaceUrl({ url: 'pages/Home' });
}
} catch (error) {
promptAction.showToast({ message: '登录失败: ' + error.message });
}
}
build() {
Column() {
TextInput({ placeholder: '请输入手机号' })
.onChange((value: string) => { this.phoneNumber = value })
TextInput({ placeholder: '请输入验证码' })
.onChange((value: string) => { this.smsCode = value })
Button('获取验证码', { type: ButtonType.Capsule })
.onClick(() => this.sendSmsCode())
Button('登录', { type: ButtonType.Capsule })
.onClick(() => this.verifyLogin())
}
}
}
2. 缴费功能实现
import http from '@ohos.net.http';
import router from '@ohos.router';
@Entry
@Component
struct PaymentPage {
@State billInfo: BillInfo = {
billNumber: '',
amount: 0,
dueDate: '',
paymentStatus: false
}
@State paymentAmount: number = 0
async getBillInfo(billNumber: string) {
let httpRequest = http.createHttp();
try {
let response = await httpRequest.request(
'https://api.example.com/bills/' + billNumber,
{ method: 'GET' }
);
this.billInfo = JSON.parse(response.result);
this.paymentAmount = this.billInfo.amount;
} catch (error) {
promptAction.showToast({ message: '获取账单失败' });
}
}
async makePayment() {
try {
const paymentResult = await pay.requestPayment({
amount: this.paymentAmount,
billNumber: this.billInfo.billNumber
});
if (paymentResult.code === 0) {
router.replaceUrl({ url: 'pages/PaymentSuccess' });
} else {
promptAction.showToast({ message: '支付失败: ' + paymentResult.message });
}
} catch (error) {
promptAction.showToast({ message: '支付异常' });
}
}
build() {
Column() {
Text('账单号: ' + this.billInfo.billNumber)
Text('应缴金额: ¥' + this.billInfo.amount.toFixed(2))
Text('到期日: ' + this.billInfo.dueDate)
TextInput({ placeholder: '输入支付金额' })
.onChange((value: string) => {
this.paymentAmount = Number(value) || 0
})
Button('立即支付', { type: ButtonType.Capsule })
.onClick(() => this.makePayment())
}
}
}
3. 缴费记录查询
import { HistoryItem } from '../model/HistoryModel';
@Entry
@Component
struct HistoryPage {
@State historyList: Array<HistoryItem> = []
// 加载缴费记录
async loadHistory() {
try {
this.historyList = await storage.get('paymentHistory') || [];
} catch (error) {
promptAction.showToast({ message: '加载记录失败' });
}
}
build() {
List({ space: 10 }) {
ForEach(this.historyList, (item: HistoryItem) => {
ListItem() {
Column() {
Text(item.billType + '缴费')
Text('金额: ¥' + item.amount.toFixed(2))
Text('时间: ' + item.paymentTime)
}
}
})
}
.onAppear(() => this.loadHistory())
}
}
特色功能实现
1. 账单提醒功能
import reminderAgent from '@ohos.reminderAgent';
export function setBillReminder(billInfo: BillInfo) {
let reminderRequest: reminderAgent.ReminderRequest = {
reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER,
timer: {
triggerTimeInSeconds: new Date(billInfo.dueDate).getTime() / 1000 - 3 * 24 * 60 * 60
},
title: billInfo.billType + '账单即将到期',
content: '请及时缴纳¥' + billInfo.amount.toFixed(2),
expiredContent: billInfo.billType + '账单已到期',
snoozeTimes: 2,
notificationId: billInfo.billNumber
};
reminderAgent.publishReminder(reminderRequest)
.then(reminderId => {
console.info('提醒设置成功, ID: ' + reminderId);
})
.catch(err => {
console.error('提醒设置失败: ' + JSON.stringify(err));
});
}
2. 多设备协同支付
import distributedDeviceInfo from '@ohos.distributedDeviceInfo';
import distributedData from '@ohos.data.distributedData';
export class PaymentCollaboration {
static async startCrossDevicePayment(paymentInfo: PaymentInfo) {
const deviceList = await distributedDeviceInfo.getAvailableDeviceList();
if (deviceList.length > 0) {
const kvManager = distributedData.createKVManager({
context: getContext(),
bundleName: 'com.example.lifepayment'
});
const kvStore = await kvManager.getKVStore('paymentStore', {
createIfMissing: true
});
await kvStore.put('currentPayment', JSON.stringify(paymentInfo));
router.pushUrl({ url: 'pages/DeviceSelector' });
} else {
promptAction.showToast({ message: '未发现可用协同设备' });
}
}
}
应用配置
// entry/src/main/config.json
{
"app": {
"bundleName": "com.example.lifepayment",
"vendor": "example",
"version": {
"code": 1,
"name": "1.0.0"
}
},
"deviceConfig": {
"default": {
"network": {
"cleartextTraffic": true
}
}
},
"module": {
"name": "entry",
"type": "entry",
"abilities": [
{
"name": "MainAbility",
"icon": "$media:icon",
"label": "生活缴费",
"launchType": "standard",
"backgroundModes": ["dataTransfer", "notification"]
}
],
"reqPermissions": [
{
"name": "ohos.permission.INTERNET"
},
{
"name": "ohos.permission.NOTIFICATION_CONTROLLER"
},
{
"name": "ohos.permission.DISTRIBUTED_DATASYNC"
}
]
}
}