fetchToken method

Future<String> fetchToken()

Fetches the token from the OAuth server

Implementation

Future<String> fetchToken() async {
  final request = MultipartRequest('POST', Uri.parse(tokenUrl))
    ..fields['grant_type'] = 'client_credentials'
    ..fields['client_id'] = clientId!
    ..fields['client_secret'] = clientSecret!;

  final response = await request.send();
  final responseText = await response.stream.bytesToString();
  if (response.statusCode != 200) {
    throw ApiException(response.statusCode, responseText);
  }

  final data = jsonDecode(responseText);
  final int expiresIn = data['expires_in'];

  tokenExpiration = DateTime.now().add(Duration(seconds: expiresIn));
  return data['access_token'];
}