Showing posts with label tutorial. Show all posts
Showing posts with label tutorial. Show all posts

Monday, September 3, 2012

Social and Mobile Engagement Mechanism - engage-reward-shop


A new mechanism illustration through an idea for a freemium mobile and social game.. 

Nothing begins without a name, so let's call it Go-Woo (based on Gòuwù 购物 translated from “shopping”). The corresponding app  for Advertising is titled Wo-Goo which works in tandem with the game.

The Target Segment -  Chinese young and mid aged women


Target Market: Singapore, Hong Kong, China & other techno-commercial places

Alternate Markets: A re-branded game for other markets, like US, Europe, India employing the same concept but targeting different sentiments, culture etc..

Background Philosophy:
  • Chinese like to shop. They are especially drawn to shops offering special discounts or offers. They generally wait to buy something until a seasonal sale starts.
  • Chinese are drawn to simple, colorful, cute games on iPhone/iPad.
  • Urban dwellers are having less access to play with pets and it’s getting more and more expensive to own a pet.
  • Current Groupon style offers are less popular in the region, or the people are too busy playing the free games to notice the offers.

Friday, January 2, 2009

Facebook Application Part 2 : Scripting your App

(If you missed the Part-1 click here)
Now time to get hands on php. What I will do here is show you how to get access to the different parts of facebook API and also indicate my experiences. I would just indicate how to get the integration going and won’t dwell into what the app will do. You are a better judge to identify what the app can and should do. I am for this tutorial just show you how to load a flash file and also show you how to communicate with this flash file using php and XML. I will not be providing you with any sample files. Its left to your imagination and engineering what you want to make out of the app.

You will need to add the official Facebook PHP Client Library package into the webserver which is included in the package found here.

I will divide my app into these files:

  • Index.php: will be the main producer of the app. It will load the flash file and render the fbml part of the page. You will need to include facebook.php from the client library in the include.php
  • Invite.php: This is an optional page which includes some description how to get access of different friends
  • config.php: This will include all the application related stuff. It will be used to
  • db.php: Will hold all the library functions related to connection to the database, queries, and other support functions
  • xml.php: This is to read and write as xml format – intercommunication between flash and php.
The architecture of the app is a simple one:
Lets deal with the index.php for the starters. It would need to have the initial debugging information.

config.php
Then in the config file would contain the api_key and secret information regarding the facebook in this way.
$appapikey = 'gdhsgdhgsdjgsgadkshgdjgsadjgsadhg';
$appsecret  = 'dhfdsvfbvdsfnvdsnbfvbsdvfhdskhfiu';
Also include the details regarding the database as follows
$host = "localhost:3306"; //hostname is usually localhost by default
$db_user = "root"; //insert the name of the user here
$pass = "y6ju808";  //insert the password here
$database = "DATABASE_NAME";  //insert name of database
$table = "TABLE_NAME";  //insert
Some information regarding the invite page:
$app_name = "APP_NAME";
$app_url = "";
$app_image = "";
$invite_href = "invite.php"; //invite page
index.php
By adding the following in the index.php

error_reporting(E_ALL); // in the beginning to be able to debug errors in the file.
Also you will need to include another text file by name .htaccess, its contents are just a line:

php_flag display_errors on //to enable the debug flag
Next thing required is to include the config file and the facebook.php (from the client library)
require_once('config.php');
require_once(‘facebook.php’);
You need to add the following stuff to get a facebook object and to specify a user login
$facebook = new Facebook($appapikey, $appsecret);
$user = $facebook->require_login();  //Makes the user login to facebook
At this point of time, it’s ready for testing... You could try to login to your app through facebook by calling it in the browser – the link
You will just be asked to login if you haven’t to facebook due to the last line that requires to login in the index.php.

Next, it’s time to include the flash file. You would require having it as a swf format to be included. You would be using the tag from the facebook API.
Use it as follows:

          >fb:swf
            swfsrc='/flash.swf'
            Align='center'
            scale='showall'
            Width='100' Height='100'
quality = 'high' >
Here we are now…. We must have the flash file now when you launch the link in the browser.
FQL is a way to query the Facebook data you can access through the other API functions, but with a SQL-style interface. In fact, many of the normal API calls are simple wrappers for FQL queries. Some examples of how to run some queries to the fb database through fql are as follows. Please refer to the original documentation of fql for more examples and detailed references here.

This is a function to return an associative array of friends of UID who are using the APP:
function get_fb_friends($facebook, $user) {
      $result_friends = $facebook->api_client->fql_query('SELECT uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = '.$user.') AND is_app_user = 1');
$l_Friends_app_user = array();
foreach($result_friends  as $f_list){
            $l_Friends_app_user[] = $f_list['uid'];
}
      return $l_Friends_app_user;
}
invite.php
Next step is to include an invite page in the application. You could get the contents and documentation for the invite page from here.

db.php
I am providing some explanations to helper functions to connect to the database in this file. It provides some basic database related functions. I am providing a very generic list of functions and will help you in setting up your custom application and database based on these.
You can use phpMyAdmin to create the database and manage them. The user interface of this DB Admin tool is quite friendly and also provides a mechanism to import or export complete databases.

When talking about a database, the following are some of the common list of functions that you one would most commonly require. The config.php file would have the information required by these functions specified. So, make sure config.php is evaluated before calling any of the following helper functions.

  • Connection to the database: A connection has to be made to the database before executing any query to the databse.
function get_db_conn() {
$conn = @mysql_connect($GLOBALS['host'], $GLOBALS['db_user'],
 $GLOBALS['pass']) or
      die("Could not connect: " . mysql_error());
     
  mysql_select_db($GLOBALS['database'], $conn);
  return $conn; 
}
  • Query to add a list of records: Here, I have created a Table called USERS in my database using phpMyAdmin. I will get store the facebook user id of all the users who visit my app in facebook. You could optionally include other information regarding the user collected from the fb database or any other custom created information liked to your app. This function need to be passed the UID (stored in the $user created earlier) as an argument.
function add_user($user){          
      $l_query = "INSERT INTO USERS SET USER_ID = '$user'; 
      $l_add_user = mysql_query($l_query, $conn) or
            die("could not add the user..");
           
      $l_query = "FLUSH PRIVILEGES";
     mysql_query($l_query) or 
die('Error, insert query failed');           
      return $l_add_user;
}
  • Query to get a list of records: This is an example of a query being made to the MySql database to get a list of records from the database after a connection is made. This particular query would get all the details regarding the current user from the database.
function get_user_data($user){
 $query = "SELECT * FROM USERS WHERE USER_ID='$user'";
       $res = mysql_query($query, $conn);
       
       $l_query = "FLUSH PRIVILEGES";
       mysql_query($l_query) or 
die('Error, insert query failed');     
return $res;
}
You can call the function from anywhere by passing the current facebook user id (UID in $user that we have created above).

xml.php
There comes a need to get transfer data across from php to flash. XML would prove to be the best way for this purpose.  This is an example of the php script to print out the xml data which can be accessed from flash and used appropriately in flash. There are many methods to write xml data in php, I have chosen the dom object model method to accomplish this. It’s an efficient and an easy way to write xml data without any syntax errors. More about this can be found here.

In the following example, I am printing the UID under the USER -UID tag.
//Creates XML string and XML document using the DOM
 $dom = new DomDocument('1.0');
//add tag
$t_user = $t_person->appendChild($dom->createElement('USER'));
 //add tag under the tag
 $UID = $t_user->appendChild($dom->createElement('UID'));
 //add text node element to tag
 $UID->appendChild($dom->createTextNode($user));
$dom->formatOutput = true; // set the formatOutput to true
 // save XML as string or file
 $test = $dom->saveXML(); // put string in test
 print($test1);
Depending on the needs, you could print the specific information of your app. The page will print out the XML information when run which can be grabbed and used in flash. For more information regarding the usage of XML in flash can be found here.

Also there might be instances where you might have to read the information sent from flash as xml as text/xml. This data that is posted from flash to this php file can be read by listening to it using these following commands:
// Make sure the user is posting
    if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
    {
        // Read the input from stdin
        $postText = trim(file_get_contents('php://input'));
    }
$postText = $GLOBALS['HTTP_RAW_POST_DATA'];

Now you could access the data in this xml string using the built-in function simplexml as follows:
$xmlobj = simplexml_load_string($postText);
print header("Content-type: text/plain");
//Say the XML DATA has the USER ID in it..
$l_user = $xmlobj->UID;
Now you get hold of the UID which has been passed from the flash…..

I have come to the end of this tutorial. My sole intention of this tutorial is to fill some gaps generally present in the many of the tutorials available on the net.. Good luck with your ventures.. Have fun.. 

Monday, December 29, 2008

Facebook Application Part 1

I have been working on development of a facebook app from the last few weeks. I had some initial hiccups initially with trying to figure out where what was and what that does and why and so on.. I found some tutorials on the net, some of them were outdated, some were incomplete.. It seemed complete, but never worked after I did what it asked me to do... Some of the reasons were because of facebook updating their API quite often, some changes in the way the API is used by different code writers and so on... Well, to add to this, I am an amateur web developer and had little programming stints with MySql and PHP. Well it was first hard to figure out what $_POST["name"] does while trying to figure out the bigger picture of getting the app working..

I have wondered always why some of the things are not as straight as they should be always. Well I have found an answer to suit me.. Things are not straight after all.. Where's the fun if everything is straight and what would celebrations mean after something is accomplished. I have been successful in getting the stuff to work after some struggle with each of the different components. I would like to celebrate it with a toast to facebook, PHP, MySql and notepad++... Well Also I would like to contribute this programmer's tutorial of “how to write a facebook app?" Well its targeted at people like me: who wants to get it work, but are struggling to understand a lot of things that are necessary to make it work...

Well, I assume there must be a number of tutorials on the internet out there by now.. How is this different from the rest? Well, for one it’s new and updated to the latest facebook API, and secondly as I mentioned earlier, my target audience is slightly novice and people who want to make things work, but struggling to find the smaller pieces of the huge Jigsaw puzzle. Well for the professionals, there might be some stuff that I might be doing wrong too... You could add to the community by commenting on the right and wrong parts... Third and most importantly, I shall also target my tutorial in helping the people setup a web hosting service for the facebook app. This could be quite a challenge as I faced it myself. Will try to keep it easy read, and detailed, so bear with the stuff you already know...

I will divide the tutorial into 2 parts..

FACEBOOK APP TUTORIAL

Target Platform: Windows OS, Requirements: Text Editor, SSH Connectivity Tool, Web Browser, facebook account, web hosting account, SFTP/FTP Client, Database Admin,
For the starters, download a copy of Notepad++. This will be your editor for editing PHP files. You could simple use the windows notepad too, but only it does not support syntax highlighting, Multi-File View, Brace and Indent Guide, and lot other feature which will help in writing syntax free php scripts. Believe me, you will NEED it.

Now to create an app, first you need to have the facebook developer app in your profile. Login to facebook and add it here. Once you have allowed the app to have access to your profile, you are ready to create your first app...

CREATING YOUR APPLICATION: GETTING THE API KEY

Go into developers and you will need to setup a new application.



After you agree to the terms and conditions of facebook and give it a name, you will see the settings screen for your app. It’s got some important information about your app like the Application ID, API key and Secret... These are the keys used by facebook to authenticate and differentiate your app from others. Keep it a secret.

The URL to return Call is the next thing that needs to be entered. This is the location of the actual web server where you will be adding the files. There are a lot of free hosting services available out there. I used the Solaris based- Joyent FB accelerator. They support Facebook application hosting specifically and are configured to handle the traffic trend for a popular facebook app. Well, What’s more it’s free for the first year.



“Well, just wanted to add here that all the apps used by me are free and mostly open source. If you like to use them, then please be generous in donating to these communities. It takes a lot of hard work to create a free application that ease out some of your daily work load and costs them money. Every bit of your support will encourage us and them to do more for the community. “

WEB HOSTING AND CONFIGURATION

So next step is to create a free account with the Joyent web hosting service. Create using a simple form here. You will need to add the API key in the form. Once created, you will be mailed a list of passwords to your mail id. Don’t get alarmed, I will go through each and every one for your benefit.

You have just got the domain name for your new facebook app which becomes the base for URL to return Call to be entered in the app settings. For now just add the domain name created by the hosting service as the URL to return Call. You will need a SSH connectivity tool like Putty or OpenSSH. I have used the Putty in this tutorial which has whole load of other utilities too.



You will have to configure Putty to access your Shell. Under configuration, Create a hostname as SSHShellUserName@domainName. Select SSH, port 22, and when the port is opened, you will type the password. This terminal has just logged you in as a user on your web server. So you can access the web files here type :

cd /home//web/public

to access the web server directory. This is where all your web files will go into.. Another thing you would need is a SFTP client. I used filezilla client for this purpose and works amazing. You could also use the FireFTP addon for Mozilla.


“I moved from using Mozilla to Chrome recently and am really loving the way chrome looks and feels. The only thing I was not happy with the initial release was the inability to open closed tabs. With this feature, and the fantastic homepage which includes your bookmarks (instead of taking menu space) and the recently visited sites and their thumbnails and of course a list of the recently closed sites. I am falling in love with chrome... “
With filezilla, you need to again create a profile under the site manager and add the SFTPUserName (same as the ShellUserName) and the password also. Under servertype, choose SFTP SSH file transfer type. I chose Putty and Filezilla both to accomplish different operations easily. Putty would help you in passing some specific instruction and listing and grep. You could do it with Filezilla also but more elegant in doing it on the terminal. To increase productivity under advanced tab in the site manager in filezilla, you could specify the default directories to be opened when a connection is successful. Once in, on your right is the web server and you can access the various directories here. Careful while doing anything erratic here, unless you know what you are doing. You could as well see the Public directory of your web server in the explorer type view.
I created a folder under the public folder for the new facebook app. So you might be required to make the modification in the Facebook >> Developer >> App Settings. Change the URL to return Call value from

“DomainName” to “DomainName//”*

*Do not forget to end it with the slash.

Next step is to configure the MySQL for Joyent for which the details can be found here. Its a straight forward process using the combination of Filezilla and Putty.
Joyent has a decent site admin to manage databases, but I prefer phpMyAdmin over the default one. You could download it here and unzip the zipped file and copy it in the public folder. So your structure looks like this


Public >> phpMyAdmin

Documentation regarding the configuration of phpMyAdmin for your site can be found here. This step is required to setup the username and password to access the phpMyAdmin configuration page from the browser.


CREATING YOUR APPLICATION: CONFIGURING YOUR APP


We are nearly there.. Now it’s time to get back to our facebook app. Here just complete the other text fields. I am including some of the confusing ones only. The rest are straight forward.  


BASIC>


  • ICON: Choose an Icon for your app
  • DEVELOPERS: A list of developers who can access the app when in sandbox mode (developmental stage) Careful who you give access to, S/he can access the API Key as well as the Secret if he is a developer.
USER PROFILES>
  • DEFAULT CANVAS: Wide
PAGES>
  • POST Add Redirect URL: Could be the same as the domain URL or in this format http://apps.facebook/
CANVAS>
  • CANVAS Page URL: Include the in here
  • BOOKMARK URL: same as the CANVAS URL
  • RENDER METHOD: Choose FBML as the app I will be describing wil be in FBML. You could later change it to IFrame as and when required
  • CANVAS WIDTH: Full Width (760 px)
ADVANCED>
  • SANDBOX MODE: Enable it during the developmental stage
  • MOBILE INTEGRATION: not needed for this application so DISABLED
  • JavaScript API Library White list Exception: DISABLED for this application
Once the above values have been changed, just save the changes and the configuration is complete….

This is the end of Part 1 . Rest in Part 2…