authorize method

Future<AccessToken> authorize()

Manually get a new access token. You shouldn't need to call this as the client will automatically request one as needed

Implementation

Future<AccessToken> authorize() async {
  var uri = Uri.https(paypalEnvironment.host, '/v1/oauth2/token');

  var headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization': paypalEnvironment.authorizationString(),
  };

  var body = 'grant_type=client_credentials';

  if (_loggingEnabled) {
    log.info('Request: POST $uri');
    log.info('Headers: $headers');
    log.info('Body: $body');
  }

  var response = await super.post(uri, headers: headers, body: body);

  if (_loggingEnabled) {
    log.info('Response: ${response.statusCode}');
    log.info('Headers: $headers');
    log.info('Body: ${response.body}');
  }

  if (response.statusCode == HttpStatus.ok) {
    accessToken = AccessToken.fromJson(jsonDecode(response.body));
    accessToken!.expiryDateTime =
        DateTime.now().add(Duration(seconds: accessToken!.expiresIn));

    accessTokenUpdatedStream.add(accessToken!);

    if (_accessTokenUpdatedCallback != null) {
      await _accessTokenUpdatedCallback!(accessToken!);
    }

    return accessToken!;
  } else if (response.body.isNotEmpty) {
    var apiError = AuthorizationError.fromJson(jsonDecode(response.body));

    if (apiError.error.isNotEmpty) {
      throw ApiException(
        response.statusCode,
        error: apiError.error,
        errorDescription: apiError.errorDescription,
      );
    }
  }

  throw Exception('Error: $response');
}