Search code examples
phpcurladdthis

addthis API Authentication


I'm attempting to grab some analytics data via the addthis API (https://www.addthis.com/academy/addthis-analytics-api/) which works fine via a web browser when I type in the username and password, but can't figure out how I'll be able to do this as a daily cron job. On addthis's dev page it says look at the authentication methods, but that link just takes you back to the top of the same page, and Googling doesn't appear to find any examples of how to authenticate programatically.

So far I've tried adding headers and sending data as post fields, but part of the problem is I don't know what field names I should be using, so I'm fumbling a bit in the dark. Has anyone else had experience of the addthis API, and know how to access via a script?

Here's an attempt using headers

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://api.addthis.com/analytics/1.0/pub/shares/url.json?pubid=PUB_ID&period=day');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
$headers = array();
$headers[] = "userid: $user"; 
$headers[] = "password: $pass"; 
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
echo $result;

... and then using POST fields

$data = array('userid' => $user, 'password' => $pass);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://api.addthis.com/analytics/1.0/pub/shares/url.json?pubid=PUB_ID&period=day');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Content-Length: '.strlen($data);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
echo $result;

Solution

  • You can pass authentication username and password in the url. Please see sample code:

    $url = 'https://api.addthis.com/analytics/1.0/pub/shares/url.json?pubid=PUB_ID&period=day';
    $username = 'username';
    $password = 'password';
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
    $result = curl_exec($ch);
    echo $result;
    

    OR another way around:

    $url = 'https://username:password@api.addthis.com/analytics/1.0/pub/shares/url.json?pubid=PUB_ID&period=day';
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
    $result = curl_exec($ch);
    echo $result;