Skip to main content

cashbox 0.0.8 copy "cashbox: ^0.0.8" to clipboard
cashbox: ^0.0.8 copied to clipboard

钱箱插件,打开钱箱,支持联迪设备.

example/lib/main.dart

import 'dart:convert';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:cashbox/cashbox.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  String _lastResult = '(暂无结果)';
  final _cashboxPlugin = Cashbox();

  /// 统一处理插件返回:成功是 JSON 字符串,失败会以 PlatformException 抛出
  /// (0.0.8 起对 ActivityNotFoundException 等返回干净错误码而非崩溃栈)。
  void han(String? sss) {
    debugPrint('[cashbox] raw result: $sss');
    String display;
    if (sss == null || sss.isEmpty) {
      display = '返回为空';
    } else {
      try {
        final map = jsonDecode(sss) as Map<String, dynamic>;
        final base = map['baseResult'];
        // 工银收单约定:baseResult.RESULT == 0 表示交易成功
        final result = base is Map ? base['RESULT'] : null;
        display =
            'RESULT=$result\n${const JsonEncoder.withIndent('  ').convert(map)}';
      } catch (_) {
        // 非 JSON(例如设备侧直接返回文本)
        display = sss;
      }
    }
    if (mounted) setState(() => _lastResult = display);
  }

  /// 捕获 PlatformException 并在 UI 展示错误码,验证非 POS 设备不再崩溃。
  void handlePlatformError(Object e) {
    String msg;
    if (e is PlatformException) {
      msg = 'PlatformException\ncode: ${e.code}\nmessage: ${e.message}';
    } else {
      msg = '异常: $e';
    }
    debugPrint('[cashbox][error] $msg');
    if (mounted) setState(() => _lastResult = msg);
  }

  open() async {
    try {
      final ss = await _cashboxPlugin.openBox();
      han(ss);
    } catch (e) {
      handlePlatformError(e);
    }
  }

  /// 「7.1 收银」MULTI_PURCHASE 测试用例。
  /// 文档要求:完整支付类接口(startTrans),Action =
  /// com.icbc.smartpos.transservice.startTrans,交易类型用 transType key,
  /// AMOUNT 单位为分(Long)。这里直接传 int 100,验证插件 0.0.8 起按 Long 下发。
  Future<void> startPurchase() async {
    try {
      final result = await _cashboxPlugin.startActivityForResult({
        'action': 'com.icbc.smartpos.transservice.startTrans',
        'transType': 'MULTI_PURCHASE',
        'ctrlData': {'APP_NAME': '保信云', 'BANKPAY_VER': '1011000L'},
        // AMOUNT = 1.00 元(单位分)。直接传数字,插件应 putLong。
        'transData': {
          'AMOUNT': 100,
          'TRANS_LIST': ['PURCHASE', 'QRPURCHASE']
        },
      });
      han(result);
    } catch (e) {
      handlePlatformError(e);
    }
  }

  readM1Card() {
    _cashboxPlugin
        .startActivityForResult({
          "action": "com.icbc.smartpos.transservice.devices",
          "cmd": "MIFARE1_CARD",
          "ctrlData": {"APP_NAME": "管理帮手", "BANKPAY_VER": "1020700L"},
          "transData": {
            "MODE": "1L",
            "BLOCK_NO": "0L",
            "TIME_OUT": "20L",
            "KEY_A": Uint8List.fromList([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]),
            "KEY_B": Uint8List.fromList([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]),
          },
        })
        .then(han)
        .catchError(handlePlatformError);
  }

  readCard() {
    _cashboxPlugin
        .startActivityForResult({
          "action": "com.icbc.smartpos.transservice.devices",
          "cmd": "READ_MAGCARD",
          "ctrlData": {"APP_NAME": "管理帮手", "BANKPAY_VER": "1020700L"},
          "transData": {"TIME_OUT": "10L"},
        })
        .then(han)
        .catchError(handlePlatformError);
  }

  startScan() {
    _cashboxPlugin
        .startActivityForResult({
          "action": "com.icbc.smartpos.transservice.devices",
          "cmd": "START_SCAN",
          "ctrlData": {"APP_NAME": "管理帮手", "BANKPAY_VER": "1020700L"},
          "transData": {"CAMERA_ID": "1L"},
        })
        .then(han)
        .catchError(handlePlatformError);
  }

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      platformVersion = await _cashboxPlugin.getPlatformVersion() ??
          'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Plugin example app')),
        body: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Text('Running on: $_platformVersion\n'),
              ElevatedButton(
                onPressed: startPurchase,
                child: const Text("收银"),
              ),
              Row(
                children: [
                  Expanded(
                    child: FloatingActionButton(
                      onPressed: open,
                      child: const Text("打开钱箱"),
                    ),
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: FloatingActionButton(
                      onPressed: startScan,
                      child: const Text("A90扫码"),
                    ),
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: FloatingActionButton(
                      onPressed: readCard,
                      child: const Text("A90读磁卡"),
                    ),
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: FloatingActionButton(
                      onPressed: readM1Card,
                      child: const Text("A90读M1卡"),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 16),
              const Align(
                alignment: Alignment.centerLeft,
                child: Text(
                  "调用结果:",
                  style: TextStyle(fontWeight: FontWeight.bold),
                ),
              ),
              Expanded(
                child: SingleChildScrollView(
                  child: SelectableText(_lastResult),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
1
likes
140
points
581
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

钱箱插件,打开钱箱,支持联迪设备.

License

MIT (license)

Dependencies

flutter, plugin_platform_interface

More

Packages that depend on cashbox

Packages that implement cashbox