signInByWx method

Future<CloudBaseAuthState> signInByWx(
  1. String? wxAppId,
  2. String? wxUniLink
)

Implementation

Future<CloudBaseAuthState> signInByWx(
    String? wxAppId, String? wxUniLink) async {
  if (wxAppId == null || wxUniLink == null) {
    throw CloudBaseException(
        code: CloudBaseExceptionCode.EMPTY_PARAM,
        message: "wxAppid or wxUniLink is null");
  }

  String code = await _getWxCode(wxAppId, wxUniLink);
  final CloudBaseResponse? res = await CloudBaseRequest(super.core)
      .postWithoutAuth('auth.getJwt', {
    'appid': wxAppId,
    'loginType': 'WECHAT-OPEN',
    'code': code,
    'syncUserInfo': true
  });

  if (res == null) {
    throw new CloudBaseException(
        code: CloudBaseExceptionCode.NULL_RESPONSE,
        message: "unknown error, res is null");
  }

  if (res.code != null) {
    throw new CloudBaseException(code: res.code, message: res.message);
  }

  if (res.data != null && res.data['refresh_token'] != null) {
    String refreshToken = res.data['refresh_token'];
    await setRefreshToken(refreshToken);
    await setAuthType(CloudBaseAuthType.WX);

    if (res.data['access_token'] != null &&
        res.data['access_token_expire'] != null) {
      await cache.setStore(cache.accessTokenKey, res.data['access_token']);
      await cache.setStore(
          cache.accessTokenExpireKey,
          res.data["access_token_expire"] +
              DateTime.now().millisecondsSinceEpoch);
    } else {
      await refreshAccessToken();
    }

    return CloudBaseAuthState(
        authType: CloudBaseAuthType.WX, refreshToken: refreshToken);
  } else {
    throw CloudBaseException(
        code: CloudBaseExceptionCode.AUTH_FAILED, message: '微信登录失败');
  }
}