wechat_auth_cubit.dart 2.62 KB
import 'package:appframe/config/locator.dart';
import 'package:appframe/data/repositories/wechat_auth_repository.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fluwx/fluwx.dart';

class WechatAuthState extends Equatable {
  final String? sessionCode;
  final String? userCode;
  final String? classCode;
  final int? userType;
  final String? stuId;
  final String? result;

  const WechatAuthState(this.sessionCode, this.userCode, this.classCode, this.userType, this.stuId, this.result);

  WechatAuthState copyWith({
    String? sessionCode,
    String? userCode,
    String? classCode,
    int? userType,
    String? stuId,
    String? result,
  }) {
    return WechatAuthState(
      sessionCode ?? this.sessionCode,
      userCode ?? this.userCode,
      classCode ?? this.classCode,
      userType ?? this.userType,
      stuId ?? this.stuId,
      result ?? this.result,
    );
  }

  @override
  List<Object?> get props => [sessionCode, userCode, classCode, userType, stuId, result];
}

class WechatAuthCubit extends Cubit<WechatAuthState> {
  late final Fluwx _fluwx;
  late final WechatAuthRepository _wechatAuthRepository;

  WechatAuthCubit(super.initialState) {
    _fluwx = Fluwx();
    _register();
    _subscribe();

    _wechatAuthRepository = getIt<WechatAuthRepository>();
  }

  Future<void> _register() async {
    await _fluwx.registerApi(appId: "wx8c32ea248f0c7765", universalLink: "https://univerallink.banxe.cn/link/");
  }

  void _subscribe() {
    _fluwx.addSubscriber((response) async {
      if (response is WeChatAuthResponse) {
        var result = 'state :${response.state} \n code:${response.code}';
        // emit(state.copyWith(result: result));

        dynamic data = await _wechatAuthRepository.codeToSk(response.code!);
        print("===============================================");
        print(data.toString());

        var dd = data['data'];
        var role = dd['roles'][0];

        print(dd['sessionCode']);
        print(dd['userCode']);
        print(role['classCode']);
        print(role['userType']);
        print(role['stuId']);

        emit(
          state.copyWith(
            sessionCode: dd['sessionCode'],
            userCode: dd['userCode'],
            classCode: role['classCode'],
            userType: role['userType'],
            stuId: role['stuId'],
          ),
        );
      }
    });
  }

  void auth() async {
    var result = await _fluwx.authBy(
      which: NormalAuth(scope: 'snsapi_userinfo', state: 'wechat_sdk_test'),
    );
    print("++++++++++++++++++++++++++++++++++++++++++++++++++++++");
    print(result);
  }
}