Friday, August 30, 2013

Facebook Story Tagging Simple Example






Steps to create Story Tagging Simple Example

0. Create an app at https://developers.facebook.com/apps - my app name is localharshal

1. Create a folder structure similar to below and place it on a server - actual server is needed for tagging.





2. On facebook create an action i have created tango and using object - myobject.



Create an object which inherits from Business - action tagging with place.





The markup which we have used below can found at OpenGraph -> Types ->Click on edit object




3.  Create a self hosted object myobject.html


<html>

<head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# localharshal: http://ogp.me/ns/fb/localharshal#">
  <meta property="fb:app_id" content="your appid" /> 
  <meta property="og:type"   content="localharshal:myobject" /> 
  <meta property="og:url"    content="{URL where the object is hosted}/facebooktest/myobject.html" /> 
  <meta property="og:title"  content="Pune" /> 
  <meta property="og:image"  content="https://fbstatic-a.akamaihd.net/images/devsite/attachment_blank.png" />
  <meta property="localharshal:location:latitude"       content="37.41452468098636" /> 
  <meta property="localharshal:location:longitude"      content="-122.07739323377609" /> 
  <meta property="business:contact_data:street_address" content="Pune" /> 
  <meta property="business:contact_data:locality"       content="Hinjewadi" /> 
  <meta property="business:contact_data:postal_code"    content="Sample Contact data: Postal Code" /> 
  <meta property="business:contact_data:country_name"   content="Sample Contact data: Country Name" /> 
  <meta property="place:location:latitude"              content="37.41452468098636" /> 
  <meta property="place:location:longitude"            content="-122.07739323377609" /> 
  </head>
  <body>
  omg
  </body>
  </html> 



4. Create a file og.php 

<html>
<head>
<title>Open Graph Getting Started App - og.likes</title>
<style type="text/css">
div { padding: 10px; }
</style>
<meta charset="UTF-8">
</head>
<body>
<div id="fb-root"></div>
<script type="text/javascript">
  var fbAppId = 'your facebook id';

  window.fbAsyncInit = function() {
    FB.init({
      appId      : fbAppId,        // App ID
      status     : true,           // check login status
      cookie     : true,           // enable cookies to allow the server to access the session
      xfbml      : true            // parse page for xfbml or html5 social plugins like login button below
    });

  FB.getLoginStatus(function(response) {
    if (response.status === 'connected') {
    var_dump(response);
    } else if (response.status === 'not_authorized') {
    
      login();
    } else {
   
     login();
    }
  });
  };

function login() {
  FB.login(function(response) {
    if (response.authResponse) {
      var_dump(response);
    } else {
      // cancelled
    }
  }, {scope: 'publish_actions'});
}

  // Load the SDK Asynchronously
  (function(d, s, id){
     var js, fjs = d.getElementsByTagName(s)[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement(s); js.id = id;
     js.src = "//connect.facebook.net/en_US/all.js";
     fjs.parentNode.insertBefore(js, fjs);
   }(document, 'script', 'facebook-jssdk'));





function postLike() {
FB.api(
 'me/localharshal:tango',
 'post',
 {
   myobject: "{URL where the object is hosted}/facebooktest/myobject.html",
   place: "{URL where the object is hosted}/facebooktest/myobject.html"
 //  place: "https://foursquare.com/v/computer-history-museum/4abd2857f964a520c98820e3"
 },
 function(response) {
 if (!response) {
          alert('Error occurred.');
        } else if (response.error) {
          document.getElementById('result').innerHTML = 'Error: ' + response.error.message;
        } else {
          document.getElementById('result').innerHTML =
            '<a href=\"https://www.facebook.com/me/activity/' + response.id + '\">' +
            'Story created.  ID is ' + response.id + '</a>';
        }
 
 }
);
}




</script>
<div>
<input type="button" value="Create a your story with tagging" onclick="postLike();">
</div>
</body>
</html>

5. You should see a story similar to below in your activity logs


Trouble shooting

1. localharshal is my app name
2. Tango is my action name.
3. Myobject is my self hosted object name. 

You have to use your settings.

Monday, August 19, 2013

Shorten to Long URL PHP Simple Example


<?php


$base_url = 'http://'.$_SERVER['HTTP_HOST'];
if ($directory = trim(dirname($_SERVER['SCRIPT_NAME']), '/\,')) {
  $base_url .= '/'.$directory;
}
define('BASE_URL', $base_url.'/');


function getlong($url){

$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_MAXREDIRS, 4);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);


$result = curl_exec($ch);
curl_close($ch);
if($result !== false){
 $inp = 1;
 $resarray = explode("\r\n",$result);
 foreach($resarray as $line){
if(stripos($line, "HTTP/1") !== FALSE){
  $temp = explode(" ",$line);
  $redirectcode = $temp[1];
}
else{
              $temp = explode(":",$line,2);
 if(strcasecmp($temp[0],"location") == 0){
 return trim($temp[1]);
 }
      }
 }
}
return '';



}


if(isset($_GET['api'])){
//called via api
$result = array();
if(is_array($_GET['url'])){
foreach($_GET['url'] as $url){
//array_push($result,array($url=>getlong($url)));
$result[$url] = getlong($url);
}
}
else{
//array_push($result,array($_GET['url']=>getlong($_GET['url'])));
$result[$_GET['url']] = getlong($_GET['url']);
}

if($_GET['callback']){
header('Content-type: application/json');
echo $_GET['callback'].'('.json_encode($result).')';
exit;
}
else{
header('Content-type: application/json');
echo json_encode($result);
exit;
}

}
?>
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="utf-8" />
<title>Tiny2Long</title>
<link type="text/css" rel="stylesheet" href="style.css"/>
<body onload='document.forms[0].tinyurl.focus();'>
<h1><a href="<?php echo BASE_URL; ?>">Tiny2Long</a></h1>
<div id='result'>
<?php

if(isset($_POST['tinyurl'])){
$longurl=getlong($_POST['tinyurl']);
if($longurl == ''){
echo "<p class='error' ><a target='_blank' href='".$_POST['tinyurl']."'>".$_POST['tinyurl']."</a> this url doesn't seem to be a short url!</p>";
}
else{
echo "<p><a target='_blank' href='".$_POST['tinyurl']."' >".htmlentities($_POST['tinyurl'])."</a><br/> redirects to <br/> <a target='_blank' class='longurl' href='".$longurl."'>".htmlentities($longurl)."</a></p>";
}
}

?>
</div>
<form class="urlinput" id="tiny2long" name="geturl" action="" method="POST">
Small Url :<input name="tinyurl" type="text" value="<?php echo $_POST['tinyurl']; ?>" size="32" /> <input name="submit" type="submit" value="Get long url" />
</form>

<p class='c'>tiny2long also has an <a href='api.html'>API</a>. The source code is available <a href='index.phps'>here</a>.</p>



</body>
</html>

Shorten URL PHP Simple Code


<?php

$longUrl = 'http://www.google.com';
$apiKey = 'MyAPIKey';
//Get API key from : http://code.google.com/apis/console/

$postData = array('longUrl' => $longUrl, 'key' => $apiKey);
$jsonData = json_encode($postData);

$curlObj = curl_init();

curl_setopt($curlObj, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url');
curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curlObj, CURLOPT_HEADER, 0);
curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
curl_setopt($curlObj, CURLOPT_POST, 1);
curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData);

$response = curl_exec($curlObj);

//change the response json string to object
$json = json_decode($response);

curl_close($curlObj);

echo 'Shortened URL is: '.$json->id;

Sunday, August 18, 2013

Twitter Hashtag Php Search Simple example



1. Create a app at dev.twitter.com/apps
2. php code below also download the library should work as it is

require_once('TwitterAPIExchange.php');



/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'oauth_access_token' => "get from dev.twitter.com/apps/your apps settings",
'oauth_access_token_secret' => "get from dev.twitter.com/apps/your apps settings",
'consumer_key' => "get from dev.twitter.com/apps/your apps settings",
'consumer_secret' => "get from dev.twitter.com/apps/your apps settings"
);

$twitter = new TwitterAPIExchange($settings);


$url = 'https://api.twitter.com/1.1/search/tweets.json';
$requestMethod = 'GET';
$getfield = '?q=#HarshalTestingTwitter&result_type=recent';

// Perform the request
$twitter = new TwitterAPIExchange($settings);
print_r( $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest());

Login /Connect Php Twitter Very simple example


<?php


1. Create a app at
https://dev.twitter.com/apps

2. In Settings set - Allow Signin

3. Download the library from

https://github.com/abraham/twitteroauth

4. Php code below

session_start();
require_once('twitteroauth/twitteroauth.php');


// Set consumerkey and secret
$twitteroauth = new TwitterOAuth('consumerkey from app step 2', 'consumerSecret from app settings step 2');
// Requesting authentication tokens, the parameter is the URL we will be redirected to

// Requesting authentication tokens, the parameter is the URL we will be redirected to
$request_token = $twitteroauth->getRequestToken();

// Saving them into the session
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];

// If everything goes well..
if($twitteroauth->http_code==200){
    // Let's generate the URL and redirect
    $url = $twitteroauth->getAuthorizeURL($request_token['oauth_token']);
    header('Location: '. $url);
} else {
    // It's a bad idea to kill the script, but we've got to know when there's an error.
    die('Something wrong happened.');
}
?>