Hu FA
Hu FA

Reputation: 31

Retrieving the Authorization Code from Fitbit API with Flutter

I am trying to build an app with flutter that uses Fitbit API, I tried different packages to do Web Authentication like Fitbitter that uses flutter-web-auth for authentication. Also tried web-view Widget.

in case of Fitbitter :

the issue is when I logged in the fitbit account and get the response that content authorization code https://example.com/callback?code=<authorization_code>#_=_0.
authorize method in FitbitConnector class doesn't redirect me back to the app with authorization code instead stays in the chrome custom tab.

authorize method

static Future<String?> authorize(
    {BuildContext? context,
    String? clientID,
    String? clientSecret,
    required String redirectUri,
    required String callbackUrlScheme}) async {
  // Instantiate Dio and its Response
  Dio dio = Dio();
  Response response;

  String? userID;

  // Generate the fitbit url
  final fitbitAuthorizeFormUrl = FitbitAuthAPIURL.authorizeForm(
      userID: userID, redirectUri: redirectUri, clientID: clientID);

  // Perform authentication
  try {
    final result = await FlutterWebAuth.authenticate(
        url: fitbitAuthorizeFormUrl.url!,
        callbackUrlScheme: callbackUrlScheme);
    //Get the auth code
    final code = Uri.parse(result).queryParameters['code'];

    // Generate the fitbit url
    final fitbitAuthorizeUrl = FitbitAuthAPIURL.authorize(
        userID: userID,
        redirectUri: redirectUri,
        code: code,
        clientID: clientID,
        clientSecret: clientSecret);

    response = await dio.post(
      fitbitAuthorizeUrl.url!,
      data: fitbitAuthorizeUrl.data,
      options: Options(
        contentType: Headers.formUrlEncodedContentType,
        headers: {
          'Authorization': fitbitAuthorizeUrl.authorizationHeader,
        },
      ),
    );

    // Debugging
    final logger = Logger();
    logger.i('$response');

    // Save authorization tokens
    final accessToken = response.data['access_token'] as String;
    final refreshToken = response.data['refresh_token'] as String;
    userID = response.data['user_id'] as String?;

    GetIt.instance<SharedPreferences>()
        .setString('fitbitAccessToken', accessToken);
    GetIt.instance<SharedPreferences>()
        .setString('fitbitRefreshToken', refreshToken);
  } catch (e) {
    print(e);
  } // catch

  return userID;
}

Do you know a way to do web authentication and get redirected to the app with user Token and ID?

Upvotes: 1

Views: 942

Answers (0)

Related Questions