鸿蒙中用HarmonyOS SDK应用服务 HarmonyOS5开发一个生活电费的缴纳和查询小程序

发布于:2025-06-10 ⋅ 阅读:(17) ⋅ 点赞:(0)

一、项目初始化与配置

1. 创建项目

ohpm init @harmony/utility-payment-app

2. 配置权限

// module.json5
{
  "requestPermissions": [
    {
      "name": "ohos.permission.INTERNET"
    },
    {
      "name": "ohos.permission.GET_NETWORK_INFO"
    },
    {
      "name": "ohos.permission.ACCESS_BILLING_SERVICE"
    }
  ]
}

二、核心功能实现

1. 电费账户绑定模块

// AccountBinding.ets
@Component
struct AccountBinding {
  @State accountInfo: ElectricAccount = {
    accountNumber: '',
    region: '',
    address: ''
  }

  @State regions: Array<string> = ['北京', '上海', '广州', '深圳']
  @State isLoading: boolean = false

  build() {
    Column() {
      Form({ labelPosition: 'fixed' }) {
        FormItem({ label: '地区选择' }) {
          Select(this.accountInfo.region)
            .options(this.regions.map(region => ({ value: region })))
            .onSelect((index) => {
              this.accountInfo.region = this.regions[index]
            })
        }

        FormItem({ label: '电费账号' }) {
          TextInput({ placeholder: '请输入电费账号' })
            .onChange((value) => this.accountInfo.accountNumber = value)
        }

        FormItem({ label: '用电地址' }) {
          TextInput({ placeholder: '请输入详细地址' })
            .onChange((value) => this.accountInfo.address = value)
        }
      }

      Button('绑定账户', { type: ButtonType.Capsule })
        .width('90%')
        .margin(20)
        .onClick(() => this.bindAccount())
        .enabled(!this.isLoading && this.validateForm())

      if (this.isLoading) {
        LoadingProgress()
          .margin({ top: 20 })
      }
    }
  }

  async bindAccount() {
    this.isLoading = true
    try {
      await ElectricService.bindAccount(this.accountInfo)
      router.replace({ url: 'pages/Home' })
    } catch (error) {
      prompt.showToast({ message: '绑定失败: ' + error.message })
    } finally {
      this.isLoading = false
    }
  }
}

2. 电费查询功能

// BillQuery.ets
@Component
struct BillQuery {
  @State currentBill: ElectricBill = null
  @State historyBills: Array<ElectricBill> = []
  @State selectedMonth: string = this.getDefaultMonth()

  aboutToAppear() {
    this.loadBills()
  }

  async loadBills() {
    try {
      const [current, history] = await Promise.all([
        ElectricService.getCurrentBill(),
        ElectricService.getHistoryBills()
      ])
      this.currentBill = current
      this.historyBills = history
    } catch (error) {
      logger.error('获取账单失败:', error)
    }
  }

  build() {
    Column() {
      // 当前账单卡片
      BillCard({ 
        bill: this.currentBill,
        type: 'current'
      })

      // 历史账单查询
      Text('历史账单查询')
        .fontSize(18)
        .margin({ top: 20, bottom: 10 })
      
      MonthPicker({
        selected: this.selectedMonth,
        onAccept: (value) => {
          this.selectedMonth = value
          this.queryHistoryBill(value)
        }
      })

      List() {
        ForEach(this.historyBills, (bill) => {
          ListItem() {
            BillCard({ 
              bill: bill,
              type: 'history'
            })
          }
        })
      }
      .layoutWeight(1)
    }
  }
}

3. 电费缴纳功能

// Payment.ets
@Component
struct Payment {
  @State paymentAmount: number = 0
  @State paymentMethods: Array<PaymentMethod> = [
    { id: 'alipay', name: '支付宝', icon: 'alipay' },
    { id: 'wechat', name: '微信支付', icon: 'wechat' },
    { id: 'unionpay', name: '银联支付', icon: 'unionpay' }
  ]
  @State selectedMethod: string = 'alipay'

  build() {
    Column() {
      // 金额输入
      TextInput({ placeholder: '输入缴费金额' })
        .type(InputType.Number)
        .onChange((value) => this.paymentAmount = Number(value))
        .margin(20)

      // 支付方式选择
      Text('选择支付方式')
        .fontSize(16)
        .margin({ left: 20, top: 10, bottom: 10 })
      
      GridRow({ columns: 3 }) {
        ForEach(this.paymentMethods, (method) => {
          GridCol() {
            Column() {
              Image($r(`app.media.${method.icon}`))
                .width(60)
                .height(60)
              Text(method.name)
                .margin({ top: 5 })
            }
            .border({
              width: this.selectedMethod === method.id ? 2 : 0,
              color: '#1a73e8'
            })
            .onClick(() => this.selectedMethod = method.id)
          }
        })
      }
      .margin(20)

      // 确认支付按钮
      Button('确认支付', { type: ButtonType.Capsule })
        .width('90%')
        .margin(20)
        .enabled(this.paymentAmount > 0)
        .onClick(() => this.confirmPayment())
    }
  }

  async confirmPayment() {
    try {
      const result = await PaymentService.createPayment({
        amount: this.paymentAmount,
        method: this.selectedMethod
      })
      
      if (result.success) {
        router.push({
          url: 'pages/PaymentResult',
          params: { success: true }
        })
      }
    } catch (error) {
      prompt.showToast({ message: '支付失败: ' + error.message })
    }
  }
}

三、HarmonyOS 5特色功能集成

1. 分布式缴费提醒

// 跨设备同步缴费提醒
function syncPaymentReminder(account: ElectricAccount) {
  const devices = deviceManager.getTrustedDeviceListSync()
  devices.forEach(device => {
    featureAbility.startAbility({
      deviceId: device.deviceId,
      bundleName: 'com.example.utility',
      abilityName: 'ReminderAbility',
      parameters: {
        type: 'electric',
        account: account.accountNumber,
        balance: account.balance
      }
    })
  })
}

2. 原子化服务快捷缴费

// QuickPayment.ets
@Entry
@Component
struct QuickPayment {
  @State quickAmounts: number[] = [50, 100, 200, 500]

  build() {
    Column() {
      Text('快捷缴费')
        .fontSize(20)
        .margin({ bottom: 20 })

      GridRow({ columns: 2 }) {
        ForEach(this.quickAmounts, (amount) => {
          GridCol() {
            Button(`${amount}元`, { type: ButtonType.Normal })
              .height(80)
              .margin(10)
              .onClick(() => this.startQuickPayment(amount))
          }
        })
      }
    }
  }

  startQuickPayment(amount: number) {
    router.push({
      url: 'pages/Payment',
      params: { amount }
    })
  }
}

3. 缴费记录卡片服务

// config.json卡片配置
{
  "forms": [
    {
      "name": "PaymentCard",
      "description": "电费缴费卡片",
      "type": "JS",
      "jsComponentName": "PaymentCard",
      "colorMode": "auto",
      "isDefault": true,
      "updateEnabled": true,
      "scheduledUpdateTime": "08:00",
      "updateDuration": 1,
      "defaultDimension": "2 * 2",
      "supportDimensions": ["2 * 2", "2 * 4"]
    }
  ]
}

四、数据安全与支付处理

1. 支付安全处理

// PaymentService.ets
import payment from '@ohos.iap';

class PaymentService {
  static async createPayment(params: PaymentParams) {
    try {
      const result = await payment.purchase({
        productId: 'electric_payment',
        amount: params.amount,
        currency: 'CNY',
        extraInfo: {
          account: params.account
        }
      })
      
      if (result.paymentState === payment.PaymentState.SUCCESS) {
        await this.verifyPayment(result.purchaseToken)
        return { success: true }
      }
    } catch (error) {
      logger.error('支付处理失败:', error)
      throw error
    }
  }
}

2. 数据加密存储

// 使用HarmonyOS加密API存储敏感信息
import cryptoFramework from '@ohos.security.cryptoFramework';

async function encryptAccountData(account: ElectricAccount) {
  const cipher = cryptoFramework.createCipher('AES256|GCM|PKCS7')
  await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, secretKey)
  
  const input: cryptoFramework.DataBlob = {
    data: stringToUint8Array(JSON.stringify(account))
  }
  
  const output = await cipher.doFinal(input)
  return output.data
}

五、UI/UX优化设计

1. 用电数据可视化

// ConsumptionChart.ets
@Component
struct ConsumptionChart {
  @Prop consumptionData: Array<ConsumptionPoint>

  build() {
    Canvas(this.context) {
      ForEach(this.consumptionData, (item, index) => {
        Path()
          .width(20)
          .height(item.value * 2)
          .fill(getColorByUsage(item.value))
          .position({ x: index * 30 + 10, y: 200 - item.value * 2 })
        
        Text(item.month)
          .position({ x: index * 30 + 10, y: 210 })
      })
    }
    .height(250)
    .margin(20)
  }
}

2. 主题配色方案

// resources/base/theme/electric_theme.json
{
  "color": {
    "electric_primary": "#1a73e8",
    "electric_secondary": "#34a853",
    "electric_warning": "#fbbc05",
    "electric_danger": "#ea4335",
    "chart_bar": "#4285f4",
    "chart_line": "#34a853"
  }
}

六、测试与发布

1. 单元测试示例

// ElectricService.test.ets
describe('ElectricService Test', () => {
  beforeAll(() => {
    jest.mock('@ohos.net.http')
  })

  it('should fetch current bill correctly', async () => {
    const mockBill = { amount: 150.50, dueDate: '2023-11-20' }
    http.request.mockResolvedValue({ data: mockBill })
    
    const result = await ElectricService.getCurrentBill()
    expect(result.amount).toBe(150.50)
  })

  it('should handle payment failure', async () => {
    http.request.mockRejectedValue(new Error('Network Error'))
    
    await expect(ElectricService.payBill(100))
      .rejects
      .toThrow('支付请求失败')
  })
})

2. 应用发布准备

  1. ​签名配置​​:

    hdc appmode install --signature [签名文件] --bundle-name com.example.electric
  2. ​上架华为应用市场​​:

    • 准备支付相关资质文件
    • 确保符合金融类应用合规要求
    • 提交安全扫描报告

七、性能优化建议

  1. ​数据缓存策略​​:

    // 实现两级缓存
    const BillCache = {
      memoryCache: new Map(),
      
      async get(key) {
        if (this.memoryCache.has(key)) {
          return this.memoryCache.get(key)
        }
        
        const diskData = await preferences.get(key)
        if (diskData) {
          this.memoryCache.set(key, diskData)
          return diskData
        }
        
        return null
      },
      
      async set(key, value) {
        this.memoryCache.set(key, value)
        await preferences.set(key, value)
      }
    }
  2. ​预加载关键资源​​:

    // 应用启动时预加载
    aboutToAppear() {
      this.loadLogos()
      this.loadPaymentMethods()
    }
  3. ​按需加载账单详情​​:

    // 懒加载账单详情
    LazyForEach(this.bills, (bill) => {
      BillItem({ bill })
    })

通过以上实现,您可以构建一个功能完善、安全可靠的鸿蒙电费缴纳与查询小程序,充分利用HarmonyOS 5的分布式能力和支付服务,为用户提供便捷的生活缴费体验。