Flash + on VK API


    The steps describe the registration and creation of a flash application for the VKontakte social network using the VKontakte API calls. The AS3 wrapper class for the VK API is written.
    Application , the creation process under the cat.

    At the end of the post, the archive with the project code.

    Item 1. Register vKontakte application


    For this you will need to register you in contact, the procedure is trivial, it makes no sense to describe. After registration, go to http://vkontakte.ru/gsearch.php?from=apps , this is a general list of applications. At the top, select “create an application”.


    Fill in the name, description, type and proceed to download the application.



    At this stage, your application has already been created and registered in the database. The following screen is available for each application you create. Description of the important elements after the picture.



    Blue highlighted application download form. Unlike facebook, here you need to upload the application to the server, and not specify the external CanvasURL where it lies. The so-called “sandbox mode” is highlighted in purple - if the application is “turned off”, either you or your friends will be able to download itand all requests to it must contain the parameter "test_mode = 1" (for query parameters see below). Fields that uniquely identify your application are highlighted in green; they are used in vKontakteAPI requests (see below).

    Item 2. TK applications under vKontakte API


    Above write “Hello,% username%”, under the greeting show a list of friends.
    A few words about the VKontakte API:
    - all documentation is available at http://vkontakte.ru/pages.php?id=2369267 (you must have a VKontakte account for reading)
    - the linear dimensions of the flash application should not exceed 607x590
    - more than three requests per second From one application it is chopped off.

    Point 3. Writing an application under vKontakte API


    Written under flex, the wrapper class of the API does not pull flex components, so it can be used in pure flash.
    So (the VKontakteAPI class description in the next paragraph).

    main.mxml

    After starting the application, it calls for receiving information about the current user and a list of his friends, then receives information about friends and displays them as a list.

    There is a little problem here. Information about the current user can always be obtained, but the application will not receive a list of friends until the user specifically indicates that this application can do this. Therefore, the received data is checked for this error and the user is asked to allow the application access to his friends (state "enable_friends"). Error codes for each function are described on the documentation page..

    the code:

      layout="absolute"
      width="607" height="590"
      applicationComplete="onAppStart()">

      
        Text,Label
        {
          color: "0xFFFFFF";
          font-size: 24;
        }
      

      
      
        
          
          
                       text="Приложение не может получить доступ к вашим друзьям. Вверху нажмите на 'Настройки' и в меню выберите 'Разрешить приложению доступ к друзьям'. После чего перегрузите страницу."
              selectable="false"
              horizontalCenter="0" verticalCenter="0"
              width="570" height="200"/>
          

        

      

      
           id="mainContainer"
        horizontalCenter="0" verticalCenter="0"
        width="590"
        maxHeight="570"
        horizontalAlign="center">
               id="userNameLabel"
          text="Привет, %username%"/>
        
      
      
      
             
          import vkontakte.VKontakteAPI;
          
          private function onAppStart() : void
          {
            // pass flashvars to the vKontakte init
            VKontakteAPI.init(this.parameters);
            // request user info for current user
            VKontakteAPI.getProfiles([VKontakteAPI.uid], onGetUserInfo);
            // request friends
            VKontakteAPI.getFriends(onGetFriends);
          }
          
          private function onGetUserInfo(result : Object) : void
          {
            // set user label text to the user first_name + last_name
            userNameLabel.text =
              "Привет, " +
              result.response[0].first_name +
              " " +
              result.response[0].last_name;
          }
          
          private function onGetFriends(result : Object) : void
          {
            if(result.error)
            {
              // if app have not access to friends
              if(result.error.error_code == 7)
              {
                // tell user to allow access
                currentState = "enable_friends";
                return;
              }
              return;
            }
            
            // no error
            
            // have not friends
            if(result.response.length <= 0)
            {
              var no_friends_label : Label = new Label();
              no_friends_label.text = "их нет (";
              mainContainer.addChild(no_friends_label);
              return;
            }
            
            // have friends, get info
            VKontakteAPI.getProfiles(result.response, onGetFriendsInfo);
          }
          
          private function onGetFriendsInfo(result : Object) : void
          {
            for(var i : int = 0; i < result.response.length; i++)
            {
              var friend_label : Label = new Label();
              friend_label.text = result.response[i].first_name + " " + result.response[i].last_name;
              mainContainer.addChild(friend_label);
            }
          }
          
        ]]>
      



    * This source code was highlighted with Source Code Highlighter.


    Item 4. vKontakte as3 API


    Actually, the class that is involved in generating and sending requests to the VKontakte server
    is no error handling, because It was written for verification and it is not known whether I will seriously write under VKontakte.

    APP_SECRET is available on the application editing page. API_ID and USER_ID are populated so that you can debug locally. TEST_MODE is set to 1 because the application is still in development and is “off”. In the code of a real application, this value is set to 0.
      public class VKontakteAPI
      {
        // application secret key
        private static const APP_SECRET : String = "SuxPmMMxDj";

        // stored application id to use when running locally
        private static var API_ID  : String = "1643226";
        // stored user id to use when running locally
        private static var UID    : String = "52531344";
        // test mode for running in sandbox mode
        // replace by "0" after switching application to public access
        private static var TEST_MODE : String = "1";

    * This source code was highlighted with Source Code Highlighter.


    The name of the function speaks for itself; these parameters are included in all requests. Json was selected as the type of returned data (by default xml).
    To work with json, the JSWOOF library is used
        // return array of values included in all requests
        private static function getBaseValues() : Array
        {
          return [
            "api_id=" + API_ID,
            "v=2.0",
            "format=json",
            "test_mode=" + TEST_MODE
          ];
        }

    * This source code was highlighted with Source Code Highlighter.


    Creating an MD5 request hash. According to the rules of VKontakte, it must be equal to md5 (UID + param1 + ... paramN + APP_SECRET), and the parameters must be concatenated in alphabetical order. The MD5 class is carbonized.
        // returns MD5 as required by vKontakte API
        private static function getMD5(values : Array) : String
        {
          // sort values alphabetically
          values.sort();
          
          var hash_str : String = "";      
          hash_str += UID;
          for(var i : int = 0; i < values.length; i++)
            hash_str += values[i];
          hash_str += APP_SECRET;
          
          return MD5.hex_md5(hash_str);
        }

    * This source code was highlighted with Source Code Highlighter.


    Creating a request URL.
        // combine request string
        private static function getRequestString(values : Array) : String
        {
          var request : String = "http://api.vkontakte.ru/api.php";
          for(var i : int = 0; i < values.length; i++)
            request += (i == 0 ? "?" : "&") + values[i];
          return request;
        }

    * This source code was highlighted with Source Code Highlighter.


    The main function sending a request to the vkontakte server. In it, the method name, additional parameters (if any) are added to the basic request parameters. Md5 calculated from them is also added to the parameters.
    Next, URLLoader is launched, which, upon completion of the request, parses the json string into an object and sends this object to a callback.
        // main request function
        // method - vKontakteAPI method name (like "getUserInfo" or "getProfiles")
        // add_values - addition method parameters (ex. for "getProfiles"
        //   add_values must contain list of uids like "uids=123,3124,3123")
        // callback - function called after completing request
        private static function makeRequest(method : String, add_values : String, callback : Function) : void
        {
          // base values for all requests
          var values : Array = getBaseValues();
          // add method name
          values.push("method=" + method);
          // add additional values if have any
          if(add_values)
            values.push(add_values);
          // calculate md5 hash and add it to values array
          values.push("sig=" + getMD5(values));
          
          // request loader
          var loader : URLLoader = new URLLoader();
          // register listener for COMPLETE event
          loader.addEventListener(
            Event.COMPLETE,
            function (event : Event) : void 
            {
              // extract loader from event
              var loader : URLLoader = URLLoader(event.target);
              // parse json data and pass it
              // to callback function
              callback(JParser.decode(loader.data));
            });
          // fire request with url created from values
          loader.load(new URLRequest(getRequestString(values)));
        }

    * This source code was highlighted with Source Code Highlighter.


    Initialization function. Just populates the uid of the current user from the transferred flashvars.
         // must be called at application start
        // to init API variables (or left default values when running locally)
        public static function init(flashvars : Object) : void
        {
          // if have viewer_id in flashvars
          if(flashvars.viewer_id)
          {
            // then it means that application started in vKontakte framework
            // update userID for user whos started application
            UID = flashvars.viewer_id;
          }
        }

    * This source code was highlighted with Source Code Highlighter.


    This is all you need to wrap the vkontakte API functions.
    For example, two functions used in this application.
        // get basic user(s) data (uid, first_name, last_name) for provided uids array
        public static function getProfiles(uids : Array, callback : Function) : void
        {
          var uids_str : String = "uids=" + uids[0];
          for(var i : int = 1; i < uids.length; i++)
            uids_str += "," + uids[i];
          makeRequest("getProfiles", uids_str, callback);
        }
        
        // returns friends of the current user
        public static function getFriends(callback : Function) : void
        {
          makeRequest("getFriends", null, callback);
        }

    * This source code was highlighted with Source Code Highlighter.


    The project archive for Eclipse + FlexBuilder is available at the link , in the same place build.xml for building antom in the console.

    PS

    On some systems, instead of their name and the names of friends, krakozyabras are displayed. There is a suspicion that this is due to the encoding of the returned json object. Therefore, an application using "format = xml" in the request parameters has been reloaded on vKontakte. Accordingly, the data comes in XML format, UTF-8 encoding.
    The link to the source XML version is Turk .


    Also popular now: