Within the framework of one project, it became necessary to implement automatic publication of updates on the wall of the Vkontakte community. I think this problem occurs quite often. I offer a ready-made example of implementation in C #.
For this we need:
- register the app and get AppID and AppSecret. How to do this is described here ;
- send the user to the VKontakte page, where he will confirm the granting of authority to your application to act on his behalf;
- get token;
- post a message on the wall.
Step 1: register the application
After registering your application, you will receive 2 parameters that we will need further:
- Application ID ( AppID );
- Application secret key ( AppSecret ).
Step 2: Get the Code
In case of successful confirmation, the granting of permissions to your application on VKontakte returns the
Code parameter, which we will need to get
Token -a. Create a class
Vk with the
GetCode () method that will direct the user to the appropriate page.
public static class Vk
{
public static void GetCode()
{
string reqStrTemplate =
"http://api.vkontakte.ru/oauth/authorize?client_id={0}&scope=offline,wall" ;
System.Diagnostics.Process.Start(
string .Format(reqStrTemplate, Publics.Vk_AppID));
}
}
* This source code was highlighted with Source Code Highlighter .
In my case, this is a desktop application, so in order to use the Code parameter, the user must copy it from the page and transfer it to the application (enter in the appropriate edit). If you have a web application, then things are a little better, and you can specify the address for the redirect in the get request parameters (& redirect_uri = http: // yoursite), and then get the Code parameter directly to your application.
Step 3: Token
Having received the
Token (key), you can continue to perform actions on behalf of the user by omitting steps 1-3. In fact, Token is the cornerstone of authorization for any application supporting / duplicating the OAuth protocol. So, to get the Token, we need to specify
AppID ,
AppSecret and
AppCode . We received the 1st and 2nd parameters when registering the application, and the AppCode parameter was obtained in the previous step.
In case of successful receipt of Token, vkontakte returns json with Token-ohm, the expiration date of Token-a and the user ID with which Token is associated.
public class VkJsonTokenResponse
{
public string access_token { get ; set ; }
public string expires_in { get ; set ; }
public string user_id { get ; set ; }
}
* This source code was highlighted with Source Code Highlighter .
')
public static string GetToken( string Code)
{
string reqStrTemplate =
"https://api.vkontakte.ru/oauth/access_token?client_id={0}&client_secret={1}&code={2}" ;
string reqStr = string .Format(reqStrTemplate, Publics.Vk_AppID, Publics.Vk_Secret, Code);
WebClient webClient = new WebClient();
string response = webClient.DownloadString(reqStr);
JavaScriptSerializer s = new JavaScriptSerializer();
VkJsonTokenResponse jsonResponse = s.Deserialize<VkJsonTokenResponse>(response);
Token = jsonResponse.access_token;
SaveTokens();
return Token;
}
* This source code was highlighted with Source Code Highlighter .
Step 4: Final stage of publication on the wall
There is an opportunity to publish text, link / media content.
public static string PostMessage( string Message, string Link, string CapchaID, string CapchaKey)
{
string reqStr = string .Format(
"https://api.vkontakte.ru/method/wall.post?owner_id={0}=&access_token={1}&message={2}" ,
Publics.Vk_GroupID, Vk.Token, Message);
if (! string .IsNullOrEmpty(Link))
reqStr += string .Format( "&attachment={0}" , System.Web.HttpUtility.UrlEncode(Link));
if (! string .IsNullOrEmpty(CapchaID))
reqStr += string .Format( "&captcha_sid={0}" , CapchaID);
if (! string .IsNullOrEmpty(CapchaKey))
reqStr += string .Format( "&captcha_key={0}" , CapchaKey);
WebClient webClient = new WebClient();
return webClient.DownloadString(reqStr);
}
* This source code was highlighted with Source Code Highlighter .
When you publish plain text, you get
post_id in response. When you publish the text and links, you receive
processing: 1 , which means that VKontakte accepted your request, and it is possible that it will publish the post. Why is "possible", see the end of the article.
Well, the code for loading and saving Token is:
private static void SaveTokens()
{
XmlSerializer s = new XmlSerializer( typeof ( string ));
FileStream fs = new FileStream (Publics.CurrPath + "vk.xml" , FileMode .OpenOrCreate);
s.Serialize(fs, Token);
fs.Flush();
}
public static void LoadTokens()
{
try
{
XmlSerializer s = new XmlSerializer( typeof ( string ));
FileStream fs = new FileStream (Publics.CurrPath + "vk.xml" , FileMode .Open);
Token = ( string )s.Deserialize(fs);
}
catch (Exception ex)
{
Error.SaveError( "Vk.LoadTokens" , ex.Message);
}
}
* This source code was highlighted with Source Code Highlighter .
To store one parameter in xml is overkill, I agree with you, but before the code cuts for the article the parameter was not one.
Some practical advice / disappointments
- You can not publish the link anywhere except its wall. A workaround is to add a link to the text, while VKontakte recognizes it and makes it clickable. An example is here ;
- If you publish posts with a link (to your page), then make sure that the link is valid (leading to an existing page + do not forget System.Web.HttpUtility.UrlEncode (Link)). This is important, because if the link is not valid, the post will not be published and you will not be able to track it down (as I wrote above, the publication of posts with links takes place asynchronously, and in response you will receive processing: 1;
- You cannot publish both a link and a picture at the same time;
- You cannot post posts on behalf of a group;
- Send publication requests at intervals of 2-5 minutes, otherwise you will have to organize captcha recognition: in response to the publication request, you will receive a link to the captcha image, and then you will need to add 2 parameters to the repeated request for publication: captcha ID ( captcha_sid ) and recognized value ( captcha_key ).
Despite the wretchedness of the VKontakte API, it is quite simple to implement automatic posting to the VKontakte news group of your portal / magazine / blog.
References:- Documentation Vkontakte API