📜 ⬆️ ⬇️

Flash + vkontakte API


The steps describe the registration and creation of a flash application for the social network vkontakte, using vkontakte API calls. AS3 class wrapper for vKontakte API is written.
Application , the process of creating under the cut.

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

Item 1. Register the application vKontakte


For this you 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 is registered in the database. The following screen is available for each application you create. Description of the important elements after the picture.



Blue highlights the application download form. Unlike facebook, here you have to download the application to the server, and not specify the external CanvasURL where it lies. Violet is selected so-called “sandbox mode”, - if the application is “off”, then you or your friends can download it, and all requests to it should contain the parameter “test_mode = 1” (see below for the query parameters). Greens highlight fields that uniquely identify your application, they are used in vKontakteAPI queries (see below).

Item 2. Application TK under the vKontakte API


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

Item 3. Writing an application under the vKontakte API


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

main.mxml

After the application starts, it causes receiving information about the current user and its friends list, then receives information about friends and displays them with a list.

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

code:
<?xml version= "1.0" encoding= "utf-8" ?>
<mx:Application xmlns:mx= "http://www.adobe.com/2006/mxml"
layout= "absolute"
width= "607" height= "590"
applicationComplete= "onAppStart()" >

<mx:Style>
Text,Label
{
color: "0xFFFFFF" ;
font-size: 24;
}
</mx:Style>

<mx:states>
<mx:State name= "enable_friends" >
<mx:RemoveChild target= "{mainContainer}" />
<mx:AddChild position= "lastChild" >
<mx:Text
text= " . '' ' '. ."
selectable= "false"
horizontalCenter= "0" verticalCenter= "0"
width= "570" height= "200" />
</mx:AddChild>
</mx:State>
</mx:states>

<mx:VBox
id= "mainContainer"
horizontalCenter= "0" verticalCenter= "0"
width= "590"
maxHeight= "570"
horizontalAlign= "center" >
<mx:Label
id= "userNameLabel"
text= ", %username%" />
<mx:Label id= "friendsCaptionLabel" text= " :" />
</mx:VBox>

<mx:Script>
<![CDATA[

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);
}
}

]]>
</mx:Script>
</mx:Application>

* This source code was highlighted with Source Code Highlighter .


Item 4. vKontakte as3 API


Actually, the class that deals with the formation and sending of requests to the server vKontakte
Error handling is missing because It was written for verification and it is not known whether I would seriously write under VK.

APP_SECRET is available on the application editing page. API_ID and USER_ID are filled in order to be locally debugged. TEST_MODE is set to 1, because the application is still in development and "off". In the real application code, 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 function name speaks for itself; these parameters are included in all requests. Json is selected as the return type (default is xml)
JSWOOF library is used to work with json
// 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. Class MD5 is goodled.
// 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 .


Create 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 that sends a request to the server vkontakte. It adds the name of the method to the basic parameters of the request, additional parameters (if any). The parameters are also added md5 calculated from them.
Next, a URLLoader is launched, which, when the request is completed, parses the json string into the object and sends this object to the 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. It just fills 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 that is needed to wrap the functions vkontakte API.
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 archive of the project under Eclipse + FlexBuilder is available via the link , in the same place build.xml for assembling the ant in the console.

PS

On some systems, cracks are displayed instead of their name and friend names. There is a suspicion that this is due to the encoding of the returned json object. Therefore, an application that uses “format = xml” in the request parameters has been reloaded on vKontakte. Corresponding data comes in XML format, UTF-8 encoding.
Link to the XML source version - tyrk .

Source: https://habr.com/ru/post/71814/


All Articles