鸿蒙中用HarmonyOS SDK应用服务 HarmonyOS5开发一个生活缴费小程序

88 阅读2分钟

鸿蒙生活缴费小程序开发指南

开发环境准备

  1. ​安装DevEco Studio​​:下载并安装最新版DevEco Studio(支持HarmonyOS 5.0)
  2. ​配置HarmonyOS SDK​​:确保已安装HarmonyOS 5.0 SDK
  3. ​创建项目​​:选择"Application" -> "Empty Ability"模板

项目结构

LifePaymentApp/
├── entry/
│   ├── src/
│   │   ├── main/
│   │   │   ├── ets/
│   │   │   │   ├── pages/          # 页面目录
│   │   │   │   ├── utils/          # 工具类
│   │   │   │   ├── model/          # 数据模型
│   │   │   │   └── app.ets         # 应用入口
│   │   │   ├── resources/         # 资源文件
│   │   │   └── config.json        # 应用配置

核心功能实现

1. 用户认证模块

// ets/pages/Login.ets
import userAuth from '@ohos.userIAM.userAuth';

@Entry
@Component
struct LoginPage {
  @State phoneNumber: string = ''
  @State smsCode: string = ''

  // 发送短信验证码
  async sendSmsCode() {
    try {
      // 调用短信服务API
      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. 缴费功能实现

// ets/pages/Payment.ets
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 {
      // 调用支付SDK
      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. 缴费记录查询

// ets/pages/History.ets
import { HistoryItem } from '../model/HistoryModel';

@Entry
@Component
struct HistoryPage {
  @State historyList: Array<HistoryItem> = []

  // 加载缴费记录
  async loadHistory() {
    try {
      // 从本地数据库或网络API获取数据
      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. 账单提醒功能

// ets/utils/ReminderUtil.ets
import reminderAgent from '@ohos.reminderAgent';

export function setBillReminder(billInfo: BillInfo) {
  let reminderRequest: reminderAgent.ReminderRequest = {
    reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER,
    timer: {
      // 提前3天提醒
      triggerTimeInSeconds: new Date(billInfo.dueDate).getTime() / 1000 - 3 * 24 * 60 * 60
    },
    title: billInfo.billType + '账单即将到期',
    content: '请及时缴纳¥' + billInfo.amount.toFixed(2),
    expiredContent: billInfo.billType + '账单已到期',
    snoozeTimes: 2, // 可延迟提醒2次
    notificationId: billInfo.billNumber // 使用账单号作为通知ID
  };
  
  reminderAgent.publishReminder(reminderRequest)
    .then(reminderId => {
      console.info('提醒设置成功, ID: ' + reminderId);
    })
    .catch(err => {
      console.error('提醒设置失败: ' + JSON.stringify(err));
    });
}

2. 多设备协同支付

// ets/utils/DeviceCollaboration.ets
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"
      }
    ]
  }
}