wechat_qr_bind_dialog.dart 12.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
import 'dart:convert';
import 'dart:typed_data';

import 'package:appframe/config/constant.dart';
import 'package:appframe/config/locator.dart';
import 'package:appframe/data/repositories/user_auth_repository.dart';
import 'package:appframe/data/repositories/wechat_auth_repository.dart';
import 'package:appframe/utils/login_util.dart';
import 'package:crypto/crypto.dart';
import 'package:flutter/material.dart';
import 'package:fluwx/fluwx.dart';
import 'package:shared_preferences/shared_preferences.dart';

///
/// 微信二维码绑定弹窗
/// 内部自管理二维码生成、扫码回调、绑定请求等完整流程
///
class WechatQrBindDialog extends StatefulWidget {
  @override
  State<WechatQrBindDialog> createState() => _WechatQrBindDialogState();
}

class _WechatQrBindDialogState extends State<WechatQrBindDialog> {
  // 0: 加载中  1: 显示二维码  2: 已扫码待确认  3: 用户取消  4: 过期/错误  5: 绑定成功
  int _status = 0;
  String _tip = '正在生成二维码...';
  Uint8List? _qrImage;

  late final Fluwx _fluwx;
  late final FluwxCancelable _fluwxCancelable;
  late final WechatAuthRepository _wechatAuthRepository;
  late final UserAuthRepository _userAuthRepository;

  @override
  void initState() {
    super.initState();
    _fluwx = getIt.get<Fluwx>();
    _wechatAuthRepository = getIt.get<WechatAuthRepository>();
    _userAuthRepository = getIt.get<UserAuthRepository>();
    _fluwxCancelable = _fluwx.addSubscriber(_responseListener);
    _initQrCode();
  }

  Future<void> _initQrCode() async {
    try {
      var resultData = await _wechatAuthRepository.getTicket() as Map<String, dynamic>?;
      if (resultData == null) {
        _setError('生成二维码失败');
        return;
      }
      if (resultData['resultCode'] != '001') {
        _setError('生成二维码状态错误');
        return;
      }

      var sdkTicket = resultData['data'];
      var timestamp = DateTime.now().millisecondsSinceEpoch;
      var signature = _sig(Constant.wxAppId, '$timestamp', sdkTicket, '$timestamp');

      var authResult = await _fluwx.authBy(
        which: QRCode(
          appId: Constant.wxAppId,
          scope: 'snsapi_userinfo',
          nonceStr: '$timestamp',
          timestamp: '$timestamp',
          signature: signature,
        ),
      );

      if (!authResult) {
        _setError('请求微信失败');
      }
    } catch (e) {
      debugPrint('wechatQrBind initQrCode error: $e');
      _setError('生成二维码异常');
    }
  }

  void _responseListener(WeChatResponse response) async {
    if (response is WeChatAuthGotQRCodeResponse) {
      int? errCode = response.errCode;
      if (errCode != null && errCode == 0) {
        if (!mounted) return;
        setState(() {
          _status = 1;
          _qrImage = response.qrCode;
          _tip = '打开微信,扫描二维码绑定';
        });
      } else {
        _setError('错误 $errCode');
      }
    } else if (response is WeChatQRCodeScannedResponse) {
      int? errCode = response.errCode;
      if (errCode != null && errCode == 0) {
        if (!mounted) return;
        setState(() {
          _status = 2;
          _tip = '在微信中轻触允许即可绑定';
        });
      } else {
        _setError('错误 $errCode');
      }
    } else if (response is WeChatAuthByQRCodeFinishedResponse) {
      int? errCode = response.errCode;
      if (errCode != null && errCode == 0) {
        await _doBind(response.authCode!);
      } else if (errCode == -4) {
        if (!mounted) return;
        setState(() {
          _status = 3;
          _tip = '你已取消此次绑定';
        });
      } else {
        if (!mounted) return;
        setState(() {
          _status = 4;
          _tip = '请刷新二维码,重新绑定';
        });
      }
    }
  }

  Future<void> _doBind(String code) async {
    try {
      var resultData = await _wechatAuthRepository.codeToSk(code) as Map<String, dynamic>?;
      if (resultData == null) {
        _setError('绑定请求处理失败');
        return;
      }
      if (resultData['resultCode'] != '001') {
        _setError('绑定请求状态失败');
        return;
      }

      var data = resultData['data'] as Map<String, dynamic>;
      var wechatUserCode = data['userCode'] as String;

      var sharedPreferences = getIt.get<SharedPreferences>();
      var visitorId = sharedPreferences.getString('auth_visitor_id') ?? '';
      var visitorType = sharedPreferences.getString('auth_visitor_type') ?? '';

      if (visitorId.isEmpty || visitorType.isEmpty) {
        _setError('用户信息获取失败,请重新登录');
        return;
      }

      if (visitorType != 'apple' && visitorType != 'phone') {
        _setError('用户信息错误,请重新登录');
        return;
      }

      var bindResult = await _userAuthRepository.newBinding(
        visitorId,
        wechatUserCode,
        visitorType,
      ) as Map<String, dynamic>?;

      if (!mounted) return;
      if (bindResult != null && bindResult['code'] == 0) {
        setState(() {
          _status = 5;
          _tip = '微信绑定成功';
        });
        // 延迟关闭弹窗
        Future.delayed(const Duration(milliseconds: 1200), () {
          if (mounted) Navigator.of(context).pop();
        });

        LoginUtil.handleLoginSuccess(data, 0, 'reload');

      } else {
        var errorMsg = bindResult?['error'] ?? '微信绑定失败';
        _setError(errorMsg);
      }
    } catch (e) {
      debugPrint('wechatQrBind doBind error: $e');
      _setError('微信绑定异常');
    }
  }

  void _setError(String tip) {
    if (!mounted) return;
    setState(() {
      _status = 4;
      _tip = tip;
    });
  }

  Future<void> _refresh() async {
    setState(() {
      _status = 0;
      _tip = '正在重新生成二维码...';
      _qrImage = null;
    });
    try {
      _fluwx.stopAuthByQRCode();
    } catch (e) {
      debugPrint('stopAuthByQRCode error: $e');
    }
    await _initQrCode();
  }

  String _sig(String appId, String nonceStr, String sdkTicket, String timestamp) {
    String str = 'appid=$appId&noncestr=$nonceStr&sdk_ticket=$sdkTicket&timestamp=$timestamp';
    return sha1.convert(utf8.encode(str)).toString();
  }

  @override
  void dispose() {
    _fluwxCancelable.cancel();
    try {
      _fluwx.stopAuthByQRCode();
    } catch (e) {
      debugPrint('stopAuthByQRCode error: $e');
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
      ),
      child: Container(
        width: 300,
        padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 28),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              '微信扫码绑定',
              style: TextStyle(
                fontSize: 17,
                fontWeight: FontWeight.bold,
                color: Color(0xFF333333),
              ),
            ),
            const SizedBox(height: 20),
            SizedBox(
              height: 230,
              child: _buildContent(),
            ),
            const SizedBox(height: 16),
            // 底部按钮区域
            _buildBottomActions(),
          ],
        ),
      ),
    );
  }

  Widget _buildContent() {
    if (_status == 0) {
      // 加载中
      return Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const SizedBox(
            width: 48,
            height: 48,
            child: CircularProgressIndicator(
              color: Color(0xFF7691FA),
              strokeWidth: 3,
            ),
          ),
          const SizedBox(height: 16),
          Text(
            _tip,
            style: TextStyle(fontSize: 14, color: Color(0xFF666666)),
            textAlign: TextAlign.center,
          ),
        ],
      );
    } else if (_status == 1) {
      // 显示二维码
      return Column(
        children: [
          Container(
            width: 190,
            height: 190,
            decoration: BoxDecoration(
              border: Border.all(color: Color(0x29265ECF), width: 0.5),
              borderRadius: BorderRadius.circular(12),
            ),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(12),
              child: Image.memory(_qrImage!, width: 190, height: 190),
            ),
          ),
          const SizedBox(height: 8),
          Text(
            _tip,
            style: TextStyle(fontSize: 14, color: Color(0xFF333333)),
            textAlign: TextAlign.center,
          ),
        ],
      );
    } else if (_status == 2) {
      // 已扫码,等待确认
      return Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.check_circle, color: Color(0xFF07C160), size: 64),
          const SizedBox(height: 12),
          Text(
            '已扫码',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: Color(0xFF333333),
            ),
          ),
          const SizedBox(height: 8),
          Text(
            _tip,
            style: TextStyle(fontSize: 14, color: Color(0xFF666666)),
            textAlign: TextAlign.center,
          ),
        ],
      );
    } else if (_status == 3) {
      // 用户取消
      return Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.cancel, color: Color(0xFFE64340), size: 64),
          const SizedBox(height: 12),
          Text(
            '已取消绑定',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: Color(0xFF333333),
            ),
          ),
          const SizedBox(height: 8),
          Text(
            _tip,
            style: TextStyle(fontSize: 14, color: Color(0xFF666666)),
            textAlign: TextAlign.center,
          ),
        ],
      );
    } else if (_status == 4) {
      // 错误/过期
      return Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.error_outline, color: Color(0xFFE64340), size: 64),
          const SizedBox(height: 12),
          Text(
            '绑定失败',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: Color(0xFF333333),
            ),
          ),
          const SizedBox(height: 8),
          Text(
            _tip,
            style: TextStyle(fontSize: 14, color: Color(0xFF666666)),
            textAlign: TextAlign.center,
          ),
        ],
      );
    } else if (_status == 5) {
      // 绑定成功
      return Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.check_circle, color: Color(0xFF07C160), size: 64),
          const SizedBox(height: 12),
          Text(
            _tip,
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: Color(0xFF07C160),
            ),
          ),
        ],
      );
    }
    return SizedBox.shrink();
  }

  Widget _buildBottomActions() {
    if (_status == 1 || _status == 2) {
      // 二维码显示中,提供关闭按钮
      return TextButton(
        onPressed: () => Navigator.of(context).pop(),
        child: Text(
          '取消',
          style: TextStyle(fontSize: 15, color: Color(0xFF999999)),
        ),
      );
    } else if (_status == 3 || _status == 4) {
      // 取消或错误,提供重试和关闭按钮
      return Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          TextButton(
            onPressed: _refresh,
            child: Text(
              '重试',
              style: TextStyle(fontSize: 15, color: Color(0xFF7691FA)),
            ),
          ),
          const SizedBox(width: 16),
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text(
              '关闭',
              style: TextStyle(fontSize: 15, color: Color(0xFF999999)),
            ),
          ),
        ],
      );
    }
    return SizedBox.shrink();
  }
}