Flutter (Dart 2) accessing twitter GET api

Issue

I am having trouble calling on the Twitter api in my Flutter app. I have used the twitter sign in library to get my token and secret token, and I have my consumer and consumer secret. But I am unable to form an https request correctly. I have tried using an Oauth2 client as well as a straight request and neither has worked.

I found this repo with a dart 1 Twitter and Oauth implementation, but I have been unable to figure out how to convert this to Dart 2. All help is greatly appreciated.

Edit: Here is most recent code:

final response = await http.get(new Uri.https(
        "api.twitter.com", "/1.1/statuses/home_timeline.json", {
      "count": "200",
      "tweet_mode": "extended",
      "exclude_replies": "false"
    }), headers: {
      "Authorization": 'Bearer ${twitter.token}', //twitter.token is the token recieved from Twitter sign in process
      "Content-Type": "application/json"
    });

returns "errors":[{"code":89,"message":"Invalid or expired token."}]
I know that the token is valid

Edit 2:

Future<List<Tweet>> getTimeline() async {
    print("Getting timeline");
    var query = https.get(
        "https://api.twitter.com/1.1/statuses/home_timeline.json?count=2&tweet_mode=extended&exclude_replies=false",
    headers: {
      "Authorization":
          'oauth_consumer_key="$_consumerKey", oauth_token="${twitter.token}"',
      "Content-Type": "application/json"
    }).timeout(Duration(seconds: 15));

    print("Before await");
    final response = await query;
    print("code: ${response.statusCode}");
    ...
}

After more debugging there was a possible null exception with twitter.token. After fixing that, I am still getting bad authorization data. I will keep trying to add more info to the header and see if something will help it.

Edit 3:

Here is my generate signature method:

static String generateSignature(String method, String base, List<String> sortedItems) {
    String sig = '$method&${Uri.encodeComponent(base)}&';
    String param = '';

    for (int i = 0; i < sortedItems.length; i++) {
      if (i == 0)
        param = sortedItems[i];
      else
        param += '&${sortedItems[i]}';
    }

    sig += Uri.encodeComponent(param);
    String key = '${Uri.encodeComponent(_secretKey)}&${Uri.encodeComponent(twitter.secret)}';
    var digest = Hmac(sha1, utf8.encode(key)).convert(utf8.encode(sig));
    print("base: ${digest.bytes}");
    print("sig: ${base64.encode(digest.bytes)}");
    return base64.encode(digest.bytes);
  }

Here is the timeline method:

Future<List<Tweet>> getTimeline() async {
    print("Getting timeline");
    Future<http.Response> query;

    try {
      String base = 'https://api.twitter.com/1.1/statuses/home_timeline.json';
      String count = 'count=2';
      String mode = 'tweet_mode=extended';
      String replies = 'exclude_replies=false';
      String oauthConsumer = 'oauth_consumer_key="$_consumerKey"';
      String oauthToken = 'oauth_token="${twitter.token}"';
      String oauthNonce = 'oauth_nonce="${randomAlphaNumeric(20)}"';
      String oauthVersion = 'oauth_version="1.0"';
      String oauthTime =
      'oauth_timestamp="${DateTime.now().millisecondsSinceEpoch}"';
      String oauthMethod = 'oauth_signature_method="HMAC-SHA1"';
      String oauthSig = 'oauth_signature="${generateSignature("GET", base, [
    count,
    replies,
    oauthConsumer,
    oauthNonce,
    oauthTime,
    oauthToken,
    oauthVersion,
    mode
  ])}"';

  query = http.get(
      new Uri.https("api.twitter.com", "/1.1/statuses/home_timeline.json", {
        "count": "2",
        "tweet_mode": "extended",
        "exclude_replies": "false"
      }),
      headers: {
        "Authorization": '$oauthConsumer, $oauthToken, $oauthVersion, $oauthTime, $oauthNonce, $oauthMethod, $oauthSig',
        "Content-Type": "application/json"
      }).timeout(Duration(seconds: 15));
} catch (e) {
  print(e);
}

Thanks!

Solution

Here is the code that ended up working:

Generate string method:

static String generateSignature(
      String method, String base, List<String> sortedItems) {
    String param = '';

    for (int i = 0; i < sortedItems.length; i++) {
      if (i == 0)
        param = sortedItems[i];
      else
        param += '&${sortedItems[i]}';
    }

    String sig =
        '$method&${Uri.encodeComponent(base)}&${Uri.encodeComponent(param)}';
    String key =
        '${Uri.encodeComponent(_secretKey)}&${Uri.encodeComponent(twitter.secret)}';
    var digest = Hmac(sha1, utf8.encode(key)).convert(utf8.encode(sig));
    return base64.encode(digest.bytes);
  }

Convenience method for twitter get calls:

Future<http.Response> _twitterGet(
      String base, List<List<String>> params) async {
    if (twitter == null) await _startSession();

    String oauthConsumer =
        'oauth_consumer_key="${Uri.encodeComponent(_consumerKey)}"';
    String oauthToken = 'oauth_token="${Uri.encodeComponent(twitter.token)}"';
    String oauthNonce =
        'oauth_nonce="${Uri.encodeComponent(randomAlphaNumeric(42))}"';
    String oauthVersion = 'oauth_version="${Uri.encodeComponent("1.0")}"';
    String oauthTime =
        'oauth_timestamp="${(DateTime.now().millisecondsSinceEpoch / 1000).toString()}"';
    String oauthMethod =
        'oauth_signature_method="${Uri.encodeComponent("HMAC-SHA1")}"';
    var oauthList = [
      oauthConsumer.replaceAll('"', ""),
      oauthNonce.replaceAll('"', ""),
      oauthMethod.replaceAll('"', ""),
      oauthTime.replaceAll('"', ""),
      oauthToken.replaceAll('"', ""),
      oauthVersion.replaceAll('"', "")
    ];
    var paramMap = Map<String, String>();

    for (List<String> param in params) {
      oauthList.add(
          '${Uri.encodeComponent(param[0])}=${Uri.encodeComponent(param[1])}');
      paramMap[param[0]] = param[1];
    }

    oauthList.sort();
    String oauthSig =
        'oauth_signature="${Uri.encodeComponent(generateSignature("GET", "https://api.twitter.com$base", oauthList))}"';

    return await http
        .get(new Uri.https("api.twitter.com", base, paramMap), headers: {
      "Authorization":
          'Oauth $oauthConsumer, $oauthNonce, $oauthSig, $oauthMethod, $oauthTime, $oauthToken, $oauthVersion',
      "Content-Type": "application/json"
    }).timeout(Duration(seconds: 15));
  }

Example call:

Future<User> getUser(String tag) async {
    String base = '/1.1/users/show.json';
    final response = await _twitterGet(base, [
      ["screen_name", tag],
      ["tweet_mode", "extended"]
    ]);

    if (response.statusCode == 200) {
      try {
        return User(json.decode(response.body));
      } catch (e) {
        print(e);
        return null;
      }
    } else {
      print("Error retrieving user");
      print(response.body);
      return null;
    }
  }

Answered By – Nick Mowen

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *