Flutter电子券验证与管理插件merchant_evc_plus的使用

Flutter电子券验证与管理插件merchant_evc_plus的使用

使用

final merchantEvcPlus = MerchantEvcPlus(
    apiKey: '', // API 密钥
    merchantUid: '', // 商户 UID
    apiUserId: '', // API 用户 ID
);

final transactionInfo = TransactionInfo(payerPhoneNumber: 'xxxxxx', amount: 1);

await merchantEvcPlus.makePayment(
    transactionInfo: transactionInfo,
    onSuccess: () {
        print('支付成功');
    },
    onFailure: (error) {
        print(error);
    },
);

完整示例 Demo

示例代码

import 'package:flutter/material.dart';
import 'package:merchant_evc_plus/merchant_evc_plus.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '商户 EvcPlus API',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: '商户 EvcPlus API'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final _formKey = GlobalKey<FormState>();
  late String merchantUid, apiUserId, apiKey, phone;
  late num amount;
  bool isLoading = false;

  void makePayment() async {
    FocusScope.of(context).unfocus();
    if (_formKey.currentState != null) {
      _formKey.currentState!.save();
      if (_formKey.currentState!.validate()) {
        final merchantEvcPlus = MerchantEvcPlus(
          apiKey: apiKey,
          merchantUid: merchantUid,
          apiUserId: apiUserId,
        );
        setState(() => isLoading = !isLoading);
        await merchantEvcPlus.makePayment(
          transactionInfo: TransactionInfo(
            payerPhoneNumber: phone,
            amount: amount,
            invoiceId: 'INV-PLAN-Test',
          ),
          onSuccess: () {
            ScaffoldMessenger.of(context).showSnackBar(SnackBar(
              content: Text('支付成功'),
            ));
          },
          onFailure: (error) {
            ScaffoldMessenger.of(context).showSnackBar(SnackBar(
              content: Text(error),
            ));
          },
        );
        setState(() => isLoading = !isLoading);
      }
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        centerTitle: true,
      ),
      body: ModalProgressHUD(
        inAsyncCall: isLoading,
        child: Center(
          child: SingleChildScrollView(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
              child: Form(
                key: _formKey,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text(
                      'API 配置',
                      style: TextStyle(fontSize: 20),
                    ),
                    const SizedBox(height: 6),
                    Text(
                      '注意:为了获得这些凭证,您需要联系 Hormuud 电信。',
                      style: TextStyle(fontSize: 12),
                      textAlign: TextAlign.center,
                    ),
                    const SizedBox(height: 30),
                    TextFormField(
                      validator: (value) {
                        if (value != null) if (value.isEmpty)
                          return '字段必填';
                      },
                      onSaved: (newValue) {
                        if (newValue != null) merchantUid = newValue;
                      },
                      decoration: InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: '商户 UID',
                      ),
                    ),
                    const SizedBox(height: 16),
                    TextFormField(
                      validator: (value) {
                        if (value != null) if (value.isEmpty)
                          return '字段必填';
                      },
                      onSaved: (newValue) {
                        if (newValue != null) apiUserId = newValue;
                      },
                      decoration: InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: 'API 用户 ID',
                      ),
                    ),
                    const SizedBox(height: 16),
                    TextFormField(
                      validator: (value) {
                        if (value != null) if (value.isEmpty)
                          return '字段必填';
                      },
                      onSaved: (newValue) {
                        if (newValue != null) apiKey = newValue;
                      },
                      decoration: InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: 'API 密钥',
                      ),
                    ),
                    const SizedBox(height: 20),
                    const Text('测试部分'),
                    const SizedBox(height: 10),
                    // 测试字段
                    Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 16, vertical: 20),
                      decoration: BoxDecoration(
                        border: Border.all(color: Colors.grey.shade300),
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: Column(
                        children: [
                          TextFormField(
                            validator: (value) {
                              if (value != null) if (value.isEmpty)
                                return '字段必填';
                            },
                            onSaved: (newValue) {
                              if (newValue != null) phone = newValue;
                            },
                            decoration: InputDecoration(
                              border: OutlineInputBorder(),
                              labelText: '电话号码',
                              hintText: '25261123456',
                            ),
                          ),
                          const SizedBox(height: 10),
                          TextFormField(
                            keyboardType: TextInputType.number,
                            validator: (value) {
                              if (value != null) if (value.isEmpty)
                                return '字段必填';
                            },
                            onSaved: (newValue) {
                              if (newValue != null)
                                amount = double.tryParse(newValue) ?? 0;
                            },
                            decoration: InputDecoration(
                              border: OutlineInputBorder(),
                              labelText: '金额',
                              hintText: '0.5',
                            ),
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(height: 16),
                    RawMaterialButton(
                      onPressed: makePayment,
                      child: Text(
                        '保存并测试',
                        style: TextStyle(color: Colors.white, fontSize: 20),
                      ),
                      constraints: BoxConstraints.tightFor(
                        width: double.infinity,
                        height: 56,
                      ),
                      fillColor: Colors.blue,
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => showDialog(
          context: context,
          builder: (_) => AlertDialog(
            title: Text('开发者信息'),
            content: Text(
              '该插件由 Abdirahman Baabale 开发。 \n\n邮件: me@baabale.com \n网站: baabale.com',
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: Text('好的,知道了!'),
              ),
            ],
          ),
        ),
        tooltip: '开发者',
        child: const Icon(Icons.info),
      ),
    );
  }
}

更多关于Flutter电子券验证与管理插件merchant_evc_plus的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter电子券验证与管理插件merchant_evc_plus的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用merchant_evc_plus插件进行电子券验证与管理的示例代码。假设你已经将merchant_evc_plus插件添加到了你的pubspec.yaml文件中,并且已经运行了flutter pub get命令。

1. 添加依赖

首先,确保你的pubspec.yaml文件中包含以下依赖:

dependencies:
  flutter:
    sdk: flutter
  merchant_evc_plus: ^最新版本号

2. 导入插件

在你的Dart文件中导入merchant_evc_plus插件:

import 'package:merchant_evc_plus/merchant_evc_plus.dart';

3. 初始化插件

通常,你需要在应用的入口文件(例如main.dart)中初始化插件。不过,具体的初始化步骤可能依赖于插件的具体实现和文档。这里假设插件有一个初始化方法:

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  // 假设插件有一个初始化方法
  MerchantEvcPlus.instance.initialize();
  runApp(MyApp());
}

4. 使用插件进行电子券验证与管理

以下是一个简单的示例,展示如何使用merchant_evc_plus插件进行电子券验证:

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

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  MerchantEvcPlus.instance.initialize();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Merchant EVC Plus Example'),
        ),
        body: Center(
          child: ValidateCouponButton(),
        ),
      ),
    );
  }
}

class ValidateCouponButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () async {
        // 假设你有一个电子券的code
        String couponCode = "YOUR_COUPON_CODE_HERE";

        try {
          // 调用插件的验证方法
          var result = await MerchantEvcPlus.instance.validateCoupon(couponCode);

          // 处理验证结果
          if (result.isValid) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text('Coupon is valid')),
            );
          } else {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text('Coupon is invalid or expired')),
            );
          }
        } catch (e) {
          // 处理错误
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('Failed to validate coupon: $e')),
          );
        }
      },
      child: Text('Validate Coupon'),
    );
  }
}

5. 管理电子券

管理电子券可能涉及创建、更新和删除电子券等操作。具体的方法取决于merchant_evc_plus插件提供的API。以下是一个假设性的示例,展示如何管理电子券:

// 假设有一个创建电子券的方法
Future<void> createCoupon() async {
  try {
    var couponDetails = {
      'code': 'NEW_COUPON_CODE',
      'value': 100, // 假设电子券的价值为100
      'expiryDate': '2023-12-31', // 电子券的过期日期
    };

    var result = await MerchantEvcPlus.instance.createCoupon(couponDetails);

    if (result.isSuccess) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Coupon created successfully')),
      );
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Failed to create coupon')),
      );
    }
  } catch (e) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('Error creating coupon: $e')),
    );
  }
}

请注意,上述createCoupon方法中的参数和返回值是假设性的,具体实现应参考merchant_evc_plus插件的文档。

总结

以上代码示例展示了如何在Flutter项目中使用merchant_evc_plus插件进行电子券的验证与管理。具体实现细节和API调用应参考插件的官方文档和示例代码。

回到顶部