Thursday, April 4, 2013

send request from app to user using php


<?php

  $app_id = "YOUR_APP_ID";
  $app_secret = "YOUR_APP_SECRET";
  $token_url = "https://graph.facebook.com/oauth/access_token?" .
    "client_id=" . $app_id .
    "&client_secret=" . $app_secret .
    "&grant_type=client_credentials";
  $app_access= file_get_contents($token_url);
  $app_access_token = json_decode($app_access, true);
  $user_id ="USER_ID";
  $apprequest_url ="https://graph.facebook.com/" .
    $user_id .
    "/apprequests?message='INSERT_UT8_STRING_MSG'" .
    "&data='INSERT_STRING_DATA'&"  .  
    $app_access_token . "&method=post";
  $result = file_get_contents($apprequest_url);
  $obj = json_decode($result, true);
  print_r($app_access_token);
  print_r($obj);
  
?>

Tuesday, April 2, 2013

get user realtime update for your app

First, you should go to your app setting page in facebook developer home page.

when you reach the app setting panel or dashboard,

choose  Settings-Realtime Updates

then in the dashboard, you can
1) in fields: input some the field you like, such as hometown_location
2) in callback: input your app url
    if your app url is http://myapp.com
    and your file to preocess the realtime update is  update.php
    then you should input: http://myapp.com/update.php
  
3) in verify token, you should input one string you like, e.g.: myfacebookapp123

save the changes.

Then you should prepare the update.php file on your server, you could copy the following code to your update.php file

<?php

  $verify_token = myfacebookapp123';
  if ($_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['hub_mode'])
    && $_GET['hub_mode'] == 'subscribe' && isset($_GET['hub_verify_token'])
    && $_GET['hub_verify_token'] == $verify_token) 
 {
      echo $_GET['hub_challenge'];
   } else if ($_SERVER['REQUEST_METHOD'] == 'POST')
   {
    $post_body = file_get_contents('php://input');
    $obj = json_decode($post_body, true);
    $myFile = "testFile.txt";
    $fh = fopen($myFile, 'a+') or die("can't open file");
    $stringData = "Something updates, pls go to get it!\n";
    fwrite($fh, $stringData);
    fclose($fh);
  }
?>

Now you can go to facebook and modify one user's(who has authened your app before) hometown. after 1-2 minutes, your server could generate one testFile.txt with "Something updates, pls go to get it!" This post dose not analyze the content in  $obj . it is something like this:
  /*
  {
  "object": "user",
  "entry": [
    {
      "uid": 1335845740,
      "changed_fields": [
        "name",
        "picture"
      ],
      "time": 232323
    }, {
      "uid": 1234,
      "changed_fields": [
        "friends"
      ],
      "time": 232325
    }
  ]
}
  */

you can try to get them respectively use php. One thing we should pay attention to is that: through realtime update, we can only get the which filed has been updated, such as hometown. but we do not know what is the user's latest howntown unless we write codes to crawl that data.

get the access token and extend its lifetime for your app

1. the basic idea is : use your 'state' get 'code', then use 'code' get 'access_token', finally use current access_token to get the 60-day long access-token. thus, even the user is not logged into  facebook, you can still access his data:

<?php 
  
   $app_id = "YOUR_APP_ID";
   $app_secret = "APP_SECRET";
   $my_url = "YOUR_URL";
   session_start();
  
   $code = $_REQUEST["code"];
   if(empty($code)) {
     $_SESSION['state'] = md5(uniqid(rand(), TRUE)); // CSRF protection
     $dialog_url = "https://www.facebook.com/dialog/oauth?client_id="
       . $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
       . $_SESSION['state'] . "&scope=user_birthday,user_hometown, read_stream, friends_likes, email, user_status, publish_stream, status_update,offline_access";
     header("Location: " . $dialog_url);
  }
  
   if($_SESSION['state'] && ($_SESSION['state'] === $_REQUEST['state'])) {
     $token_url = "https://graph.facebook.com/oauth/access_token?"
       . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
       . "&client_secret=" . $app_secret . "&code=" . $code;
     $response = file_get_contents($token_url);
     $params = null;
     parse_str($response, $params);
     $_SESSION['access_token'] = $params['access_token'];
     $graph_url = "https://graph.facebook.com/me/feed?access_token="
       . $params['access_token'];
     $user = json_decode(file_get_contents($graph_url),TRUE);//get all the data related with 'feed'
  echo "</br>";
  echo "<h3>Your infomation are:</h3>";
  echo "</br>";
  print_r($user);
  echo "</br>";
  echo "</br>";
   }
   else {
     echo("The state does not match. You may be a victim of CSRF.");
   }

 ?>


2. use the short-term token to get the 60-day access token

<?php
 $my_token_url="https://graph.facebook.com/oauth/access_token
    grant_type=fb_exchange_token&          
    client_id=YOUR_APP_ID&
    client_secret=YOUR_APP_SECRET&
    fb_exchange_token=YOUR_CURRENT_ACCESS_TOKEN";

 header("Location: " . $my_token_url);

?>

If your current token is not expired yet, you are likely to get the same token but with longer life(60 days) you can also see how long it will last every time you refresh the page.

redirect out of iFrame

In that case, you should use:
echo "<script>self.parent.location.href = 'YOUR_URL'</script>";
instead of

echo "<script>location.href = 'YOUR_URL'</script>";

But first, you should realize that you are located in one iFrame then.

all the 'scope' options in facebook app development

our app always ask for user permission, but you should type the correct offcial permission in the scope parameter. e.g

    function authUser() {
        
        FB.login(checkLoginStatus, {scope:'user_hometown, read_stream, friends_likes, email, user_status, publish_stream, status_update,offline_access'});
      }
    

if you want get the user's hometowm permission, you should type user_hometown instead of just hometown, otherwise you can never get this permission.
all below is all the latest scope options supported by facebook
   /*
   Supported scopes: ads_management create_event create_note email export_stream friends_about_me friends_activities friends_birthday 

   friends_checkins friends_education_history friends_events friends_games_activity friends_groups friends_hometown friends_interests 

   friends_likes friends_location friends_notes friends_online_presence friends_photo_video_tags friends_photos friends_questions 

   friends_relationship_details friends_relationships friends_religion_politics friends_status friends_subscriptions friends_videos 

   friends_website friends_work_history manage_friendlists manage_notifications manage_pages offline_access photo_upload publish_actions 

   publish_checkins publish_stream read_friendlists read_insights read_mailbox read_page_mailboxes read_requests read_stream rsvp_event share_item sms 

   status_update user_about_me user_activities user_birthday user_checkins user_education_history user_events user_games_activity user_groups user_hometown 

   user_interests user_likes user_location user_notes user_online_presence user_photo_video_tags user_photos user_questions user_relationship_details user_relationships
 
   user_religion_politics user_status user_subscriptions user_videos user_website user_work_history video_upload xmpp_login
   */
  

user login using FB for facebook app development

All you need to do is to replace the Uppercase Variables with your own real parameter. If the user dose not log into facebook, then it will redirect the user to the facebook login page; if the user user has loged into facebook but not authened your required permission, then it will prompt the user permission pannel. if the uer has loged into facebook and authened all your permission, it would direcly redirect the user into your app;




 
  
    YOUR_APP_NAME
  
  
   
    

Standard C++

1. <string> is the C++ version for string type, <cstring> is the C++ version for string in C, <string.h>is the C version;

2.
 
   // In C, it is correct: 
         int *pr=NULL;
   // in C++, it is correct:
         int *pr=0;
   // if you want keep
          int *pr=NULL;
   //in C++ code, you should  #include<cstdlib>
3.  // 1)
 
            int a=10;
            int b=20;
            int const  *pt=&a; // same as: const int  *pt=&a ;
            *pt=11;  //error
             pt=&b;  // correct
      //2) 
 
            int a=10;
            int b=20;
            int *const  pt=&a;
            *pt=11;  //correct
             pt=&b;  // error
4. conversion between string and char
 
      //1)
          char * ch="caozhiguang";
          string str(ch); // from char to string;
           string str=ch; // same with above
      //2)
           string str("caozhiguang");
           char *ch;
           ch=str.c_str(); // from string to char;
5. avoid repeating include, also a  better file framework(at least for me)
 
    //Zhiguang.h
    #include <string>
    using namespace std;
    #ifndef  ZHIGUANG_H
    #define ZHIGUANG_H
       Class Zhiguang
       {
             public:
                     Zhiguang();
                     Zhiguang(string the_name, string the_addr);
                     string getinfo();
             private:
                     string name;
                     string address;
                     static double salary;
        }
    #endif

  //Zhiguang.cpp
  //you'd better initialize the static var in this file
  #include  "Zhiguang.h"
  salary=3500; //initialize the static var;
  Zhiguang::Zhiguang() { }
  Zhiguang::Zhiguang(string the_name, string the_addr)  { }
  string Zhiguang::getinfo(){    }

  //main.cpp
  #include "Zhiguang.h" // no need to include the cpp file
  using namespace std;
  int main()
  {
     Zhiguang zg;
    // do whatever you want
   }

6.  create one object for the class

 
   //1)  
         Zhiguang zg;
         zg.name;
         zg.address;
         zg.getinfo();
   //2) 
         Zhiguang zg=Zhiguang();
         zg.name;
         zg.address;
         zg.getinfo();

   //3)
         Zhiguang *zg=new Zhiguang();
         zg->name;
         zg->address;
         zg->getinfo();

7. default constructor needed to initialize members of built-in type

 
    Zhiguang() : name("zhiguang"), address("Singapore"){  }

   Note: for the real initialize order, it would be based on the declaration order in the class declaration.
   e.g:  
 
                private:
                     string address;
                     string name;
            in this case, the default constructor would initialize the address first even it is listed in the second  place in the constructor.

8.  1) if the member method is const, it means it can not change the object's member variable;
     2) for const member, there should be keyword const both in declaration and definition;
     3) the const object can only use its const member, while non-const object can access both const and non-const members;
     4) for non-const member method, this could not be changed while *this could;
          for const member method,  both this and *this could not be changed.