GNIP engagement API call in PHP

oauth
gnip
api

#1

Hi,
I am using GNIP engagement API trial version.Tried to get engagement API response via PHP client code but getting error - Your account could not be authenticated. Reason: Bad signature
This is my PHP code -

$url = "https://data-api.twitter.com/insights/engagement/totals";

$consumer_key = "xxxxxxxx";
$consumer_secret = "xxxxxxxx";
$oauth_access_token = "xxxxxxxx";
$oauth_access_token_secret = "xxxxxxxx";

$oauth = array( 'oauth_consumer_key' => $consumer_key,
                'oauth_nonce' => time(),
                'oauth_signature_method' => 'HMAC-SHA1',
                'oauth_token' => $oauth_access_token,
                'oauth_timestamp' => time(),
                'oauth_version' => '1.0');

$base_info = buildBaseString($url, 'POST', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;

$postfields=rawurlencode('{"tweet_ids":["746719647324483586"],"engagement_types":["favorites"],"groupings": {"group1":{"group_by":["tweet.id","engagement.type"]}}}');

function buildBaseString($baseURI, $method, $params) {
    $r = array();
    ksort($params);
    foreach($params as $key=>$value){
        $r[] = "$key=" . rawurlencode($value);
    }
    return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}

function buildAuthorizationHeader($oauth) {
    $r = 'Authorization: OAuth ';
    $values = array();
    foreach($oauth as $key=>$value)
        $values[] = "$key=\"" . rawurlencode($value) . "\"";
    $r .= implode(', ', $values);
    return $r;
}



// Make Requests
$header = array(buildAuthorizationHeader($oauth), 'Expect:');

$options = array( CURLOPT_HTTPHEADER => $header,
                  CURLOPT_POSTFIELDS => $postfields,
                  CURLOPT_HEADER => false,
                  CURLOPT_URL => $url ,
                  CURLOPT_RETURNTRANSFER => true,
                  CURLOPT_SSL_VERIFYPEER => false);


$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json);
 print_r($twitter_data);

Please check & guide me how to use GNIP engagement API in PHP


#2

There’s an example Ruby client for the Engagement API available on our Twitterdev Github page. I haven’t seen samples in PHP, but the documentation should be helpful.


#3

thanks for reply.
I have developed PHP code for GNIP engagement API call,It works fine for me.To help others posting that code here.It might be useful -

<?php
//$url = "https://data-api.twitter.com/insights/engagement/totals";
//$url = "https://data-api.twitter.com/insights/engagement/historical";
$url = "https://data-api.twitter.com/insights/engagement/28hr";

//this token from your twitter app
$consumer_key = "<your value>";
$consumer_secret = "<your value>";

//below key tokens are from authorized users - access token for above app.This can be get by implementing login with twitter functionality with above app keys.when call back url redirected to our callback page, it returns below access token & access token secrets.need to use that.
$oauth_access_token = "<your value>";
$oauth_access_token_secret = "<your value>";


$oauth = array( 'oauth_consumer_key' => $consumer_key,
                'oauth_nonce' => time(),
                'oauth_signature_method' => 'HMAC-SHA1',
                'oauth_token' => $oauth_access_token,
                'oauth_timestamp' => time(),
                'oauth_version' => '1.0');

$base_info = buildBaseString($url, 'POST', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;

// this tweet id from authorized users tweet

$arrayPostFields['tweet_ids'] = array('757783811392364544');


//$arrayPostFields['engagement_types'] = array('impressions','engagements','favorites','retweets','replies','url_clicks','hashtag_clicks','detail_expands','permalink_clicks','media_clicks','app_install_attempts','app_opens','email_tweet','user_follows','user_profile_clicks','video_views');
$arrayPostFields['engagement_types'] = array('impressions','engagements','favorites','retweets','replies');
$arrayPostFields['groupings']['group1']['group_by'] = array('tweet.id','engagement.type');

$postfields = json_encode($arrayPostFields);
//print_r($json_post);echo "\n";die;


//$postfields='{"tweet_ids":["746719647324483586"],"engagement_types":["favorites"],"groupings": {"group1":{"group_by":["tweet.id","engagement.type"]}}}';

function buildBaseString($baseURI, $method, $params) {
    $r = array();
    ksort($params);
    foreach($params as $key=>$value){
        $r[] = "$key=" . rawurlencode($value);
    }
    return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}

function buildAuthorizationHeader($oauth) {
    $r = 'Authorization: OAuth ';
    $values = array();
    foreach($oauth as $key=>$value)
        $values[] = "$key=\"" . rawurlencode($value) . "\"";
    $r .= implode(', ', $values);
    return $r;
}



// Make Requests
$header = array(buildAuthorizationHeader($oauth), 'Accept-Encoding: gzip','Content-Type: application/json');

//Accept-Encoding: gzip

$options = array( CURLOPT_HTTPHEADER => $header,
                  CURLOPT_POSTFIELDS => $postfields,
                  CURLOPT_HEADER => false,
                  CURLOPT_URL => $url ,
                  CURLOPT_RETURNTRANSFER => true,
                  CURLOPT_SSL_VERIFYPEER => false);


$ch = curl_init();
curl_setopt_array($ch, $options);

$buffer = curl_exec($ch);

 //echo 'errno:' . curl_errno($ch);
 //echo 'error text:' . curl_error($ch);
 //echo "\n";
 
curl_close($ch);

$twitter_data_json = gzinflate(substr($buffer, 10, -8));
if($twitter_data_json!="")
{ 
$twitter_data = json_decode($twitter_data_json, true);
}

print_r($twitter_data);echo "\n";



?>

#4

Thanks for sharing, this is really helpful!


#5

This is my version on JAVA, maybe also could be helpful for someone working with GNIP


  public String createAuthorizationHeader(String callbackUrl) {

    String consumerKeyl = "";
    String consumerSecretl = "";

    String token = "";
    String secret = "";

    String url = "https://data-api.twitter.com/insights/engagement/28hr";

    
    Map<String, String> oauth = new HashMap();
    oauth.put("oauth_consumer_key", consumerKeyl);
    oauth.put("oauth_nonce", String.valueOf((Calendar.getInstance().getTimeInMillis())));
    oauth.put("oauth_signature_method", "HMAC-SHA1");
    oauth.put("oauth_token", token);
    oauth.put("oauth_timestamp", String.valueOf((Calendar.getInstance().getTimeInMillis() / 1000)));
    oauth.put("oauth_version", "1.0");

    String baseInfo = buildBaseString(url, "POST", oauth);
    String compositeKey = OAuthUtil.URLEncode(consumerSecretl) + "&" + OAuthUtil.URLEncode(secret);
    String oauthSignature = OAuthUtil.getSignature(baseInfo, compositeKey);
    oauth.put("oauth_signature", oauthSignature);

    try {
      GnipRequest request = new GnipRequest(
        Arrays.asList("755578400476127233"),
        Arrays.asList("impressions", "engagements", "favorites", "retweets", "replies"),
        new Grouping());
      List<String> groupBy = Arrays.asList("engagement.type", "engagement.day");
      request.getGroupings().getGrouping_name().setGroup_by(groupBy);

      ObjectMapper mappe = new ObjectMapper();
      String body = mappe.writeValueAsString(request);

      Future<Response> f = client.preparePost(url)
        .addHeader("Content-Type", "application/json")
        .addHeader("Accept-Encoding", "gzip")
        .addHeader("Authorization", buildAuthorizationHeader(oauth))
        .setBody(body)
        .execute();
      String responseBody = GZipDecoderToString(f.get().getResponseBodyAsBytes());
   

    } catch (Exception e) {
      _log.error("Exception while getting people" + e, e);
    }

    return null;
  }


  private String buildBaseString(String baseURI, String method, Map<String, String> params) {
    List<String> r = new ArrayList<>();
    params.keySet().stream().sorted().forEach(key -> {
      r.add(String.format("%s=%s", key, OAuthUtil.URLEncode(params.get(key))));
    });
    return method + "&" + OAuthUtil.URLEncode(baseURI) + "&" + OAuthUtil.URLEncode(String.join("&", r));
  }

  private String buildAuthorizationHeader(Map<String, String> oauth) {
    String r = "OAuth ";
    List<String> values = new ArrayList<>();
    oauth.keySet().stream().sorted().forEach(key -> {
      values.add(String.format("%s=%s", key, OAuthUtil.URLEncode(oauth.get(key).toString())));
    });

    return (r + String.join(",", values)).replace("%25", "%");
  }

  public static String GZipDecoderToString(byte[] data) {
    GZIPInputStream gzipInputStream = null;
    try {
      gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(data));
      BufferedReader in;
      String json;
      try (InputStreamReader reader = new InputStreamReader(gzipInputStream)) {
        in = new BufferedReader(reader);
        StringBuilder sb = new StringBuilder();
        String read;
        while ((read = in.readLine()) != null) {
          sb.append(read);
        }
        json = sb.toString();
      }
      in.close();
      gzipInputStream.close();
      return json;
    } catch (IOException e) {
      _log.error("Error decompresing from GNIP", e);
    }
    return null;
  }

#6

Thanks for sharing knowledge smccyogesh. When I use the script above, always showing the message error ‘Your Application ID is not authorized.’, I made the app in ‘apps.twitter.com’ and successfully. Please help and guidance. Thank you…


#7

Do you have a Gnip account? This is not part of the public Twitter API, so your account and application would need to be whitelisted by the Gnip team.


#8

Although we have created GNIP account, it gives us “Your Application ID is not authorized.” error. What to do next?

How GNIP team will approve our application?

Thanks in advance.


#9

You’ll need to contact your Gnip support channel and share your Gnip account username and Twitter App ID with them in order to be whitelisted for access.


#11

I tried to run the code that you have posted. I am getting package issues so can you please share the import packages also so that I can check where it went wrong for me. It will be helpful for me.


#12

What errors are you seeing?


#13

URLEncode, getSignature , client, getResponseBodyAsBytes
I am getting errors in the above mentioned methods and trying to run the code in eclipse. Should I add any packages to those methods ?? Or is there anything else should i do