| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- /// 微信支付流程封装(fluwx 5.3.1)
- library;
- import 'package:fluwx/fluwx.dart' as fluwx;
- import '../../constants.dart';
- import '../../models/payment.dart';
- /// fluwx 回调结果码
- class WechatPayResultCode {
- WechatPayResultCode._();
- static const int success = 0; // 支付成功
- static const int failed = -1; // 支付失败
- static const int cancelled = -2; // 用户取消
- }
- /// 微信支付封装:注册 + 拉起支付 + 结果回调
- class WechatFlow {
- WechatFlow._() : _fluwx = fluwx.Fluwx();
- static final WechatFlow _instance = WechatFlow._();
- /// 获取单例
- static WechatFlow get instance => _instance;
- final fluwx.Fluwx _fluwx;
- /// 支付结果回调(由 pay_service 注册,errCode: 0 成功)
- void Function(int errCode, String errStr)? onPayResult;
- /// 注册微信 SDK(App 启动时调用一次;Web 为空实现,安全跳过)
- Future<bool> init() async {
- return _fluwx.registerApi(
- appId: kWechatAppId,
- universalLink: kWechatUniversalLink,
- doOnAndroid: true,
- doOnIOS: true,
- );
- }
- /// 是否已安装微信 App
- Future<bool> isInstalled() async {
- try {
- return await _fluwx.isWeChatInstalled;
- } catch (_) {
- return false;
- }
- }
- /// 注册支付结果订阅(App 启动时调用一次)
- void subscribe() {
- _fluwx.addSubscriber((response) {
- if (response is fluwx.WeChatPaymentResponse) {
- onPayResult?.call(response.errCode ?? 0, response.errStr ?? '');
- }
- });
- }
- /// 拉起微信支付
- /// [created] 来自后端统一下单响应
- Future<bool> payWith(
- WechatPaymentCreatedResponse created,
- ) {
- return _fluwx.pay(
- which: fluwx.Payment(
- appId: created.appId!,
- partnerId: created.partnerId!,
- prepayId: created.prepayId!,
- packageValue: created.package ?? 'Sign=WXPay',
- nonceStr: created.noncestr!,
- timestamp: int.parse(created.timestamp!),
- sign: created.sign!,
- ),
- );
- }
- }
|