Category Archives: api

Display Stats From Specific Project using Google Analytics API

Code snippet to Display Stats From Specific Project using Google Analytics API. Also see: Display List of Sites From Google Analytics API.

stats

Get Project ID

You can get the project id from the report url in GA (it’s the number after the p).

Get API Keys

You can setup your API account here: https://code.google.com/apis/console/

The Script

<?php
session_start();
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_AnalyticsService.php';

$scriptUri = "http://".$_SERVER["HTTP_HOST"].$_SERVER['PHP_SELF'];

$client = new Google_Client();
$client->setAccessType('online'); // default: offline
$client->setApplicationName(''); //insert key
$client->setClientId(''); //insert key
$client->setClientSecret(''); //insert key
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey(''); // insert API key

// $service implements the client interface, has to be set before auth call
$service = new Google_AnalyticsService($client);

if (isset($_GET['logout'])) { // logout: destroy token
    unset($_SESSION['token']);
    die('Logged out.');
}

if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
    $client->authenticate();
    $_SESSION['token'] = $client->getAccessToken();
}

if (isset($_SESSION['token'])) { // extract token from session and configure client
    $token = $_SESSION['token'];
    $client->setAccessToken($token);
}

if (!$client->getAccessToken()) { // auth call to google
    $authUrl = $client->createAuthUrl();
    header("Location: ".$authUrl);
    die;
}

try {

    //specific project: jquery4u.com
    $projectId = '37817190';

    // metrics
    $_params[] = 'date';
    $_params[] = 'date_year';
    $_params[] = 'date_month';
    $_params[] = 'date_day';
    // dimensions
    $_params[] = 'visits';
    $_params[] = 'pageviews';
    $_params[] = 'bounces';
    $_params[] = 'entrance_bounce_rate';
    $_params[] = 'visit_bounce_rate';
    $_params[] = 'avg_time_on_site';

    $from = date('Y-m-d', time()-2*24*60*60); // 2 days
    $to = date('Y-m-d'); // today

    $metrics = 'ga:visits,ga:pageviews,ga:bounces,ga:entranceBounceRate,ga:visitBounceRate,ga:avgTimeOnSite';
    $dimensions = 'ga:date,ga:year,ga:month,ga:day';
    $data = $service->data_ga->get('ga:'.$projectId, $from, $to, $metrics, array('dimensions' => $dimensions));

    echo "project id: ". $projectId;
    foreach($data['rows'] as $row) {
       $dataRow = array();
       foreach($_params as $colNr => $column)
       {
           echo $column . ': '.$row[$colNr].'<br/>';
       }
    }


} catch (Exception $e) {
    die('An error occured: ' . $e->getMessage()."\n");
}
?>

Display List of Sites From Google Analytics API

PHP Code snippet to Display List of Sites From Google Analytics API. Also see: Display Stats From Specific Project using Google Analytics API

The Script

<?php
session_start();
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_AnalyticsService.php';

$scriptUri = "http://".$_SERVER["HTTP_HOST"].$_SERVER['PHP_SELF'];

$client = new Google_Client();
$client->setAccessType('online'); // default: offline
$client->setApplicationName(''); //insert key
$client->setClientId(''); //insert key
$client->setClientSecret(''); //insert key
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey(''); // insert API key

// $service implements the client interface, has to be set before auth call
$service = new Google_AnalyticsService($client);

if (isset($_GET['logout'])) { // logout: destroy token
    unset($_SESSION['token']);
    die('Logged out.');
}

if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
    $client->authenticate();
    $_SESSION['token'] = $client->getAccessToken();
}

if (isset($_SESSION['token'])) { // extract token from session and configure client
    $token = $_SESSION['token'];
    $client->setAccessToken($token);
}

if (!$client->getAccessToken()) { // auth call to google
    $authUrl = $client->createAuthUrl();
    header("Location: ".$authUrl);
    die;
}

try {
    $props = $service->management_webproperties->listManagementWebproperties("~all");
    echo '<h1>Available Google Analytics projects</h1><ul>'."\n";
    foreach($props['items'] as $item) printf('<li>%1$s</li>', $item['name']);
    echo '</ul>';
} catch (Exception $e) {
    die('An error occured: ' . $e->getMessage()."\n");
}
?>

Online Currency Exchange Options

I’d probably go with the Google Calculator to grab the rates and use CURL to grab the contents and supply rates to application. You could setup a cron job which runs a script say every 15 mins to update database which stores latest rates for use with application.

 

Exchangerate-api.com

http://www.exchangerate-api.com/packages

$19 per month
40,000 api calls
Updated every 15mins
Continue reading

PHP Get Images from Bing API (new Azure API)

PHP Get Images from Bing API (new Azure API)

This is how you might go about getting image details from the Bing Image Search API. The API was deprecated for the new amazon azure marketplace so you’ll need to migrate any old code to these new settings below. First off you’ll need to get your own API gets so you can access a free account of currently 5000 API call requests which is more than enough to just grab a few images. Check out the demo at iphone car backgrounds image search.
/* API SETTINGS
------------------------------------------------------------------------------------------------ */

$accountKey = 'MA1RKf5gl0rKSgc88vp3GEWSidM8YMvmZq5jTDdg='; //keys changed
$ServiceRootURL =  'https://api.datamarket.azure.com/Bing/Search/';
$WebSearchURL = $ServiceRootURL . 'Image?$format=json&amp;$Top=10&amp;Adult=%27Strict%27&amp;ImageFilters=%27Size%3aMedium%27&amp;Query='; //top5
// $WebSearchURL = $ServiceRootURL . 'Image?$format=json&amp;Adult=%27Strict%27&amp;ImageFilters=%27Size%3aMedium%27&amp;Query='; //get max
$context = stream_context_create(array(
    'http' => array(
        'method'=>'GET',
        // 'proxy' => 'tcp://127.0.0.1:8888',
        // 'proxy' => 'tcp://127.0.0.1:8080',
        'request_fulluri' => true,
        'header'  => "Authorization: Basic " . base64_encode($accountKey . ":" . $accountKey)
    )
));

/* SEARCH SETTINGS
------------------------------------------------------------------------------------------------ */

$keyphrase = '"cars"';

echo('<h3>'.$keyphrase.'</h3>');
//build search query
$request = $WebSearchURL . urlencode( '\'' . $keyphrase . '\'');
// debug($request);

$response = file_get_contents($request, 0, $context);
$jsonobj = json_decode($response);
// debug($jsonobj);

echo('<ul ID="resultList">');
foreach($jsonobj->d->results as $value)
{
  if ($value->ContentType == 'image/jpeg')
  {
      echo('<li class="resultlistitem" style="font-size:12px;float:left;padding:15px;border:1px solid blue;list-style:none;">');
        echo('<a href="' . $value->MediaUrl . '">');
        echo('<img src="' . $value->Thumbnail->MediaUrl. '" width="'.$value->Thumbnail->Width.'" height="'.$value->Thumbnail->Height.'" /></a>');
        echo('<h2>File information:</h2>');
        echo('<ul>');
          echo('<li><strong>Id:</strong> '.$value->ID.'kb</li>');
          echo('<li><strong>Title:</strong> '.$value->Title.'kb</li>');
          echo('<li>'.imgSeoPrettyFilename($value->Title).'.jpg</li>');
          echo('<li><strong>Filesize:</strong> '.round(($value->FileSize/1000), 2).'kb</li>');
          echo('<li><strong>Height:</strong> '.$value->Height.'px</li>');
          echo('<li><strong>Width:</strong> '.$value->Width.'px</li>');
          echo('<li><strong>Source:</strong> '.$value->SourceUrl.'</li>');
          echo('<li><strong>Filetype:</strong> '.$value->ContentType.'</li>');
        echo('</ul>');
      echo('</li>');
  }
}
echo('</ul>');
Example Output

All PHP Scripts on this website are provided by phpscripts4u.com where you can find all the latest PHP code snippets, plugins and libraries.

PHP Script Follow User with Twitter REST API

Simple PHP script / code snippet to follow user using the Twitter REST API.
/**
     * Follow a user using the Twitter API
     */

    private static function _followUser()
    {
        debug('calling '.__FUNCTION__.'()...');

        // Construct the parameters for the Twitter REST API call
        $tquery_data = array();
        $tquery_data['stringify_ids'] = true;
        if (isset(self::$vars['GET']['screen_name']))
        {
            $tquery_data['screen_name'] = self::$vars['GET']['screen_name'];
        }
        if (isset(self::$vars['GET']['user_id']))
        {
            $tquery_data['user_id'] = self::$vars['GET']['user_id'];
        }
        debug($tquery_data);

        // Fire off the query to Twitter REST API
        $result = get_object_vars(self::$twitteroauth->post('friendships/create', $tquery_data));
        debug($result);

        if (isset($result['id_str']))
        {
            self::_return(true, 'Successfully followed user: "' . $result["screen_name"] . '"', $result);
        }
        else
        {
            self::_return(false, 'Error following user: "' . $result['error'] . "'");
        }
    }

All PHP Scripts on this website are provided by phpscripts4u.com where you can find all the latest PHP code snippets, plugins and libraries.

Ampersands being Passed to Variable Names? Twitter API

Ampersands being passed to variable names? Twitter API
Are there ampersands (&) being passed to variable names like this, why?
No Ampersands showing my on Localhost look!
no-ampersand-on-localhost
$token = OAuthUtil::parse_parameters($request);
pass-parameter-functions
So I decided to fix the code in

OAuth.php

library:

public static function parse_parameters( $input ) {
if (!isset($input) || !$input) return array();

$pairs = explode('&amp;', $input);

foreach($pairs AS $i => $v)
{
   $pairs[$i] = str_replace('amp;','',$v);
}

new dBug($pairs);

This fixed it! :)

All PHP Scripts on this website are provided by phpscripts4u.com where you can find all the latest PHP code snippets, plugins and libraries.

Database Table Structure for Store Twitter API User Data

This post will show you Database Table Structure for Store Twitter API User Data. The tweets received from the Twitter streaming API are stored in the database in two steps as described in the code architecture.

First: The entire payload for each tweet is stored in the

json_cache

table by

get_tweets.php

. No parsing is done at this point, instead all the data for the tweet is inserted into the

raw_tweet field

.

Second:

parse_tweets.php

parses each new tweet and distributes the data across a series of tables:

tweets

,

tweet_mentions

,

tweet_tags

,

tweet_urls

, and

users

.

Note: Each

json_cache

row contains the

tweet_id

to make it possible to go back later and reparse the raw API results.

CREATE TABLE IF NOT EXISTS `json_cache` (
  `tweet_id` bigint(20) unsigned NOT NULL,
  `cache_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `cache_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `raw_tweet` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `parsed` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`cache_id`),
  KEY `tweet_id` (`tweet_id`),
  KEY `cache_date` (`cache_date`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `tweets` (
  `tweet_id` bigint(20) unsigned NOT NULL,
  `tweet_text` varchar(160) NOT NULL,
  `entities` text NOT NULL,
  `created_at` datetime NOT NULL,
  `geo_lat` decimal(10,5) DEFAULT NULL,
  `geo_long` decimal(10,5) DEFAULT NULL,
  `user_id` int(10) unsigned NOT NULL,
  `screen_name` char(20) NOT NULL,
  `name` varchar(40) DEFAULT NULL,
  `profile_image_url` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`tweet_id`),
  KEY `created_at` (`created_at`),
  KEY `user_id` (`user_id`),
  KEY `screen_name` (`screen_name`),
  KEY `name` (`name`),
  FULLTEXT KEY `tweet_text` (`tweet_text`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `tweet_mentions` (
  `tweet_id` bigint(20) NOT NULL,
  `source_user_id` bigint(20) NOT NULL,
  `target_user_id` bigint(20) NOT NULL,
  KEY `tweet_id` (`tweet_id`),
  KEY `source` (`source_user_id`),
  KEY `target` (`target_user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `tweet_tags` (
  `tweet_id` bigint(20) NOT NULL,
  `tag` varchar(100) NOT NULL,
  KEY `tweet_id` (`tweet_id`),
  KEY `tag` (`tag`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `tweet_urls` (
  `tweet_id` bigint(20) NOT NULL,
  `url` varchar(140) NOT NULL,
  KEY `tweet_id` (`tweet_id`),
  KEY `url` (`url`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `users` (
  `user_id` bigint(20) unsigned NOT NULL,
  `screen_name` varchar(20) NOT NULL,
  `name` varchar(40) DEFAULT NULL,
  `profile_image_url` varchar(200) DEFAULT NULL,
  `location` varchar(30) DEFAULT NULL,
  `url` varchar(200) DEFAULT NULL,
  `description` varchar(200) DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `followers_count` int(10) unsigned DEFAULT NULL,
  `friends_count` int(10) unsigned DEFAULT NULL,
  `statuses_count` int(10) unsigned DEFAULT NULL,
  `time_zone` varchar(40) DEFAULT NULL,
  `last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
     ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`user_id`),
  KEY `user_name` (`name`),
  KEY `last_update` (`last_update`),
  KEY `screen_name` (`screen_name`),
  FULLTEXT KEY `description` (`description`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

All PHP Scripts on this website are provided by phpscripts4u.com where you can find all the latest PHP code snippets, plugins and libraries.

PHP Create User Profile Dynamically from LinkedIn Profile

Create User Profile from LinkedIn Data

What were trying to achieve here is to save the user time creating a user profile from LinkedIn profile by typing in everything from scratch and simply click “Create Profile” and it grabs the data from LinkedIn to create the users profile dynamically. This way of creating the LinkedIn data and storing it in a seperate table instead of directly into the user profile table is that you could do an import from any Social Network most likely Facebook or Twitter and then specify individual fields for each peice of profile information. Ie – the user could use thier Facebook profile pic, LinkedIn employment history and twitter status giving them great flexibility and speed for thier profile.

What you need:

  • SQL Database with a LinkedIn table and User Profile table
  • The LinkedIn API PHP class includes
  • A LinkedIn API secret oAuth key
  • Some PHP (below)
  • Some JavaScript/jQuery (below)

How it works:

The user clicks “Import from LinkedIn” on profile page.

import-from-linkedin

The user allows access to thier LinkedIn profile.

importlinkedin-2

This is an example of the data which gets returned.

linkedin-data

The profile is auto generated and displayed using AJAX.

linked-in-userprofile-complete

How to do it:

1. Setup your SQL database tables

[code lanf="js"]
--
-- Table structure for table `prof_linkedin_data`
--

CREATE TABLE IF NOT EXISTS `prof_linkedin_data` (
`profLinkedinId` int(10) NOT NULL AUTO_INCREMENT,
`uid` int(10) NOT NULL,
`first-name` varchar(255) NOT NULL,
`last-name` varchar(255) NOT NULL,
`picture-url` varchar(255) NOT NULL,
`public-profile-url` varchar(255) NOT NULL,
`headline` varchar(255) NOT NULL,
`current-status` varchar(255) NOT NULL,
`summary` text NOT NULL,
`industry` varchar(255) NOT NULL,
`specialties` varchar(255) NOT NULL,
`location` varchar(100) NOT NULL,
PRIMARY KEY (`profLinkedinId`),
UNIQUE KEY `uid` (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

--
-- Table structure for table `prof_data`
--

CREATE TABLE IF NOT EXISTS `prof_data` (
`profId` bigint(10) NOT NULL AUTO_INCREMENT,
`uid` bigint(10) NOT NULL,
`profFirstName` varchar(50) NOT NULL,
`profLastName` varchar(50) NOT NULL,
`profProfilePic` varchar(255) NOT NULL,
`profCurrentPosition` varchar(100) NOT NULL,
`profIndustry` varchar(255) DEFAULT NULL,
`profOrganisation` varchar(255) DEFAULT NULL,
`profLocation` varchar(100) NOT NULL,
`profSummary` text NOT NULL,
`profSpecialties` varchar(255) NOT NULL,
`default` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`profId`),
KEY `profIndustryId` (`profIndustry`),
KEY `profOrganisationId` (`profOrganisation`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
[/cc]

2. Include and Setup your LinkedIn API Classes

To load in your classes you could use a function like this (the DIR constant is a reference to your server root directory).

private function _loadLinkedInIncs()
{
    require_once(DIR."social/classes/linkedin.class.php");
    require_once(DIR."social/classes/oauth.php");
    require_once(DIR."social/classes/config.php");
}

This is an example of the LinkedIn config.php file.

define('CALLBACK_URL', DOMAIN.'/storeLinkedInData.php');
define('BASE_API_URL', 'https://api.linkedin.com');

define('REQUEST_PATH', '/uas/oauth/requestToken');
define('AUTH_PATH', '/uas/oauth/authorize');
define('ACC_PATH', '/uas/oauth/accessToken');

define('CUSTOMER_KEY', '03e3kh3b8w6'); //i've changed so update to your keys
define('CUSTOMER_SECRET', 'yLGbunMaSWMkApf');

3. Create your PHP

This is how you go about asking the user for access to thier LinkedIn data(references to $this refer to the PHP object which holds these functions). I'll have to assume you know all about Object Oriented programming in PHP, I'll try to cover some basics in another post.

public function importLinkedIn()
{
    $this->_loadLinkedInIncs(); // load linkedIn includes
    $this->linkedin = new linkedin(); //create linkedIn obj
    $this->linkedin->init(); // start (not needed for public profile calls)
}

4. Create your JavaScript/jQuery

Here is the code for the button handler event for "Import from LinkedIn". When the button is clicked the LinkedIn API window appears in a popup and a setInterval function monitors for when the popup window closes. When it does close it knows to refresh with the profile information.

[code lanf="js"]
$('#import-linkedin-btn').live('click', function(e)
{
e.preventDefault();
var containerElem = $('#container'),
loadingElem = $('#loading');

//show loading image
container.html(loadingElem.clone().show());

//monitor the closing of a popup window
var win = window.open("http://domain.com/importLinkedIn.php",'','height=400,width=700');
var winTimer = window.setInterval(function()
{
if (win.closed !== false)
{
// !== is required for compatibility with Opera
window.clearInterval(winTimer);

//load the users profile
setTimeout(function()
{
/*----------------------------------------------
load in profile data from database using AJAX
----------------------------------------------*/
}, 1000);
}
}, 200);
});
[/cc]

I'm working on a demo which I'll post soon.
Sorry there is no demo and the code is slightly vague, feel free to ask any questions and I'll get a demo online for you soon.