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.');
}
?>

Monday, April 15, 2013

Ajax Json Php and Parsing Array

Jquery

jQuery(document).ready(function() {

                var dataString = "tableName=campaign_master";
               
                $.ajax
                (
                    {                                      
                        dataType: "json",type: "POST", url: "getCampaign.php", data: dataString,
                        success:
                            function(data)
                            {    
                                console.log(data);
                               
                                $.each(
                                        data,
                                        function(intIndex, objValue ){
                                         $('#campaignid').append(
                                         $( "<option id="+objValue+">" + objValue + "</option>" )
                                        );
                                        }
                                        );
                               
                                              
                               
                            },
                        error:
                            function (XMLHttpRequest, textStatus, errorThrown)
                            {
                                                                                               
                            }
                    }
                )
               
            });



php

echo json_encode(databasecall returning array);

databasecall

$recordsArray = array();
        $qry = "Select auery" ;
       
        $recordsArray = $this->executeQuery($qry);
       
        foreach($recordsArray as $record)
        {
            $idArray[] = $record['cm_id'];
        }
       
        return $idArray; //returning array

Monday, February 25, 2013

Connect to facebook using localhost


Steps to connect to facebook from localhost

1. We need to trick facebook in believing we are from that we are from actual domain instead of localhost.

So what we need to do is create a host 

So go to /etc/hosts on ubuntu one can go in windows apache/hosts file and add the following

/etc/hosts

127.0.0.1       localhost
127.0.1.1       your local ip address or whatever
127.0.0.1       abo.mysite
127.0.1.1       abo.mysite

2. Now go to apache config
/etc/apache2/sites enabled/000-default and add the following

<VirtualHost abo.mysite:80>
 DocumentRoot /var/www/
    <Directory /var/www>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all
        </Directory>
</VirtualHost>

 Now restart apache sudo /etc/init.d/apache2 restart and test the new locahost
http://abo.mysite this should resolve now.

3. No go to http://apps.facebook.com and create a new app after you create a app you should have settings as showin in the image below.






File index.php

require_once("library/facebook.php");

$facebook= new Facebook(array(
                'appId'  => '$appid',
                'secret' => '#appsecretkey'
            ));


$me = null;
// some random permissions
$permissions = 'publish_stream, create_event, rsvp_event, manage_pages, ads_management, user_photos';

// Session based API call.

    try {
        $uid = $facebook->getUser();
        echo $uid;
        $me = $facebook->api('/' . $uid);

    } catch (FacebookApiException $e) {
        var_dump($e);
    }

// here, check if the user has the application added
if ($me == null) {
    $loginUrl = $facebook->getLoginUrl(array(
        'canvas' => 1,
        'fbconnect' => 0,
        'req_perms' => $permissions,
        'next' => CALLBACK_URL . '?installed=1', // will be redirected to this URL after pressing "allow"
        'cancel_url' => CALLBACK_URL . '?cancel', // will be redirected here if app is not allowed
    )
    ); // end of array
    // redirect the user to the $loginUrl, you can place a button if you want
  
}
$user_profile = $facebook->api('/me');
var_dump($user_profile);   
exit;