[Examples] Authorization (obtaining an access token) using OAuth 2.0 VKontakte (VK) and working with the VKontakte API in PHP and JS


Let's get started

To work, we need a token with wall and offline permissions.
To receive a token, create your own Vk Standalone application. And save its ID. Next, follow the link: oauth.vk.com/authorize?client_id=IDAPP&scope=wall,offline&redirect_uri=https://api.vk.com/blank.html&response_type=token And replace IDAPP with your application ID. Or use the link that I prepared especially for you. If everything is done correctly, you will be transferred to another site, and in the URL page in the GET parameter access_token there will be a token, which is what we need, we save it.

XML work

To store the settings, create a file in .xml format with the following content: token Text post 120 attachment copyright 5.122 short name group Replace:

  • "token" to the token we got above
  • “Text post” to the message that should be in the post
  • "attachment" to the object that will be attached to the post
  • "copyright" to the source link
  • “short name group” to the short name (without vk.com) community/user page where the publication will take place (the wall must be open for publication)

Let's start writing code

Let's import all the necessary libraries, create an instance of our module and log in to VKontakte on behalf of the user using a token.
import vk_api import time from modules import XML as moduleXml XML = moduleXml.XML("settings") VK = vk_api.VkApi(token=XML.parsingFile("token")) Next, we will get all the short addresses where records will be published. import vk_api import time from modules import XML as moduleXml XML = moduleXml.XML("settings") VK = vk_api.VkApi(token=XML.parsingFile("token")) groupsId = [] groupsShortName = "" for child in XML. parsingFile("groups", False): groupsShortName += child.text + "," for group in VK.method("groups.getById", {"group_ids": groupsShortName}): groupsId.append(group["id" ] * -1) del groupsShortName Now we get the message that will be in the post, the interval at which posts will be published and the source of the post. import vk_api import time from modules import XML as moduleXml XML = moduleXml.XML("settings") VK = vk_api.VkApi(token=XML.parsingFile("token")) groupsId = [] groupsShortName = "" for child in XML. parsingFile("groups", False): groupsShortName += child.text + "," for group in VK.method("groups.getById", {"group_ids": groupsShortName}): groupsId.append(group["id" ] * -1) del groupsShortName textPost = XML.parsingFile("textPost") intervalPost = int(XML.parsingFile("interval")) Now we get all the objects that will be attached to the post. import vk_api import time from modules import XML as moduleXml XML = moduleXml.XML("settings") VK = vk_api.VkApi(token=XML.parsingFile("token")) groupsId = [] groupsShortName = "" for child in XML. parsingFile("groups", False): groupsShortName += child.text + "," for group in VK.method("groups.getById", {"group_ids": groupsShortName}): groupsId.append(group["id" ] * -1) del groupsShortName textPost = XML.parsingFile("textPost") intervalPost = int(XML.parsingFile("interval")) attachments = [attachment.text for attachment in XML.parsingFile("attachments", False)] copyright = XML.parsingFile("copyright") v = XML.parsingFile("v") We already have all the data we need to publish. All that remains is to create a function for publishing and a loop that will call the publishing function. First we will make a loop and leave the function empty. Also, the code will only work if it is launched from the console.

import vk_api import time from modules import XML as moduleXml XML = moduleXml.XML("settings") VK = vk_api.VkApi(token=XML.parsingFile("token")) groupsId = [] groupsShortName = "" for child in XML. parsingFile("groups", False): groupsShortName += child.text + "," for group in VK.method("groups.getById", {"group_ids": groupsShortName}): groupsId.append(group["id" ] * -1) del groupsShortName textPost = XML.parsingFile("textPost") intervalPost = int(XML.parsingFile("interval")) attachments = [attachment.text for attachment in XML.parsingFile("attachments", False)] copyright = XML.parsingFile("copyright") v = XML.parsingFile("v") done = False def publicPosts(): pass if __name__ == "__main__": done = True while done: publicPosts() time.sleep( intervalPost) To publish a post, we will call the API method “wall.post” and pass the receiving parameters earlier. If everything works correctly, a corresponding message will be displayed in the console. import vk_api import time from modules import XML as moduleXml XML = moduleXml.XML("settings") VK = vk_api.VkApi(token=XML.parsingFile("token")) groupsId = [] groupsShortName = "" for child in XML. parsingFile("groups", False): groupsShortName += child.text + "," for group in VK.method("groups.getById", {"group_ids": groupsShortName}): groupsId.append(group["id" ] * -1) del groupsShortName textPost = XML.parsingFile("textPost") intervalPost = int(XML.parsingFile("interval")) attachments = [attachment.text for attachment in XML.parsingFile("attachments", False)] copyright = XML.parsingFile("copyright") v = XML.parsingFile("v") done = False def publicPosts(): for groupId in groupsId: for i in range(1, 5): result = VK.method(" wall.post", { "owner_id": groupId, "message": textPost, "attachments": attachments, "copyright": copyright, "v": v }) if result["post_id"]: print("Good post , id post - " + str(result["post_id"])) else: print("Error posting") if __name__ == "__main__": done = True while done: publicPosts() time.sleep(intervalPost)

The best libraries for working with VK API in C++, Java, Python and other languages

Share

Many of us have had the opportunity to work with the VKontakte API, and everyone can say: working with it directly is inconvenient. Of course, many libraries have been written that provide a convenient interface for working with it. They can and even should be used to make work easier and speed up development. Today tproger presents a selection of libraries with the most stars and forks on GitHub for almost all of the most popular languages ​​today.

Java

VKontakte recently released an official SDK for working with the API using Java. The project page on GitHub contains many examples, here is one of them for publishing a photo on a user page:

PhotoUpload serverResponse = vk.photos().getWallUploadServer(actor).execute(); WallUploadResponse uploadResponse = vk.upload().photoWall(serverResponse.getUploadUrl(), file).execute(); List photoList = vk.photos().saveWallPhoto(actor, uploadResponse.getPhoto()) .server(uploadResponse.getServer()) .hash(uploadResponse.getHash()) .execute(); Photo photo = photoList.get(0); String attachId = "photo" + photo.getOwnerId() + "_" + photo.getId(); GetResponse getResponse = vk.wall().post(actor) .attachments(attachId) .execute();

C#

InTouch is a cross-platform library for C# that is being developed very actively. At the time of publication, full compatibility with version 5.57 of the VK API was declared. Here is an example of working with the library:

var clientId = 12345; // API client Id var clientSecret = "super_secret"; // API client secret var client = new InTouch(clientId, clientSecret); // Authorization works only in Windows (and WinPhone) Store Apps // otherwise you'll need to set received "access_token" manually // using SetSessionData method. await client.Authorize(); // Gets a list of a user's friends. var friends = await client.Friends.Get(); if (friends.IsError == false) { ShowFriendsList(friends.Data.Items.Where(friend => friend.Online)); } client.Dispose();

Or even shorter:

using (var client = new InTouch(12345, "super_secret")) { await client.Authorize(); var friends = await client.Friends.Get(); // … }

Node.js

Node-vkapi is a modern promise-based library for JavaScript. It is also available in npm:

npm install node-vkapi --only=prod --save

Here is an example code that posts text to a user's wall using node-vkapi:

const VKApi = require('node-vkapi'); const VK = new VKApi({ app: { id: 1234567890, secret: 'app-secret-key' }, auth: { login: '+79871234567', pass: 'password123' } }); VK.auth.user({ scope: ['audio', 'photos', 'friends', 'wall', 'offline'] }).then(token => { return VK.call('wall.post', { owner_id: token.user_id, friends_only: 0, message: 'Post to wall via node-vkapi' }).then(res => { // wall.post response return 'https://vk.com/wall' + token.user_id + '_' + res.post_id; }); }).then(link => { // returned data from previous .then console.log('Post was published: ' + link); }).catch (error => { // catching errors console.log(error); });

C++

VK API Lib is a small API library written in pure C++. The only dependency required is Curl. The library provides a base class VK::Client with methods for authorization and making requests to the API.

Based on it, you can create your own classes for working with sections. The example shows the VK::Messages class. Basic usage example:

#include "src/api.h" ... VK::Client api; if(api.auth(login, pass, access_token)) { cout << “Auth ok” << endl; cout << "Access token: " << api.access_token() << endl << endl; cout << api.call("wall.post", "owner_id=12345&message=Test"); } else{ cout << “Auth fail” << endl; }

Python

Python library that provides very simple work with the VKontakte API. Judge for yourself: >>> import vk >>> session = vk.Session() >>> api = vk.API(session) >>> api.users.get(user_ids=1) [{'first_name': 'Pavel ', 'last_name': 'Durov', 'id': 1}]

Currently, the library is developing quite actively, but before that there was a break in its development for about a year. You always want to use the latest tools, so it's worth mentioning another Python library. This is what uploading a photo to the server using it looks like (comments saved):

import vk_api def main(): """ Example: uploading photos """ login, password = ' [email protected] ', 'mypassword' vk_session = vk_api.VkApi(login, password) try: vk_session.authorization() except vk_api .AuthorizationError as error_msg: print(error_msg) return """ VkUpload implements methods for uploading files to VK. (Not everything, if you need something, I can add it) """ upload = vk_api.VkUpload(vk_session) photo = upload.photo( # Substitute your data 'D:/downloads/tube.jpg', album_id=200851098, group_id =74030368 ) vk_photo_url = 'https://vk.com/photo{}_{}'.format( photo[0]['owner_id'], photo[0]['id'] ) print(photo, '\ nLink: ', vk_photo_url) if __name__ == '__main__': main()

PHP

A PHP library that uses, according to the author, “Sakhalin technologies” to make the developer’s work easier. Written in OOP style. One of its coolest features is the generation of ready-made code for the special VK execute method based on a PHP request.

Example of viewing the last 200 messages:

//MESSAGES $data = $vk->request('messages.get', ['count' => 200]); $userMap = []; $userCache = []; $user = new \getjump\Vk\Wrapper\User($vk); $fetchData = function($id) use($user, &$userMap, &$userCache) { if(!isset($userMap[$id])) { $userMap[$id] = sizeof($userCache); $userCache[] = $user->get($id)->response->get(); } return $userCache[$userMap[$id]]; }; //REQUEST WILL ISSUE JUST HERE! SINCE __get overrided $data->each(function($key, $value) use($fetchData) { $user = $fetchData($value->user_id); printf("[%s] %s ", $user- >getName(), $value->body); return; });

Ruby

vkontakte_api - ruby ​​adapter for VKontakte API. It allows you to call API methods, upload files to VKontakte servers, and also supports all 3 available authorization methods (while allowing you to use a third-party solution).

You can work with it, for example, like this:

# create a client @vk = VkontakteApi::Client.new # and call API methods @vk.users.get(uid: 1) # in ruby ​​it is common to use snake_case in method names, # so likes.getList becomes likes.get_list @vk. likes.get_list # also names of methods that return '1' or '0', # end with '?', and return values ​​are set to # true or false @vk.is_app_user? # => false # if VKontakte expects to receive a parameter in the form of a list # separated by commas, then it can be passed as an array users = @vk.users.get(uids: [1, 2, 3]) # most methods return Hashie structures:: Mash # and arrays of them users.first.uid # => 1 users.first.first_name # => “Pavel” users.first.last_name # => “Durov” # if a method returning an array is called with a block, # then the block will be executed for each element, # and the method will return the processed array fields = [:first_name, :last_name, :screen_name] @vk.friends.get(uid: 2, fields: fields) do |friend| "#{friend.first_name} '#{friend.screen_name}' #{friend.last_name}" end # => ["Pavel 'durov' Durov"]

Perl

A simple, completely asynchronous AnyEvent::VK library that performs all requests via https. Essentially a client. The author recommends using Async::Chain to combine nested callbacks.

useAnyEvent; use AnyEvent::VK; use Data::Dumper; my $vk = AnyEvent::VK->new( app_id => 'Your APP ID', email => 'Email/Mobile of user', password => 'User Password', scope => 'Application permissions', ); # or my $vk = AnyEvent::VK->new( app_id => 'Your APP ID', email => 'Email/Mobile of user', password => 'User Password', scope => 'Application permissions', token => 'Your access_token', expires => 'Token expires timestamp', user_id => 'user_id', ); my $cv = AE::cv; $cv->begin; $vk->auth(sub { my $success = shift; if ($success) { my ($token, $expires_in, $user_id) = @_; $vk->request('users.get', { user_ids = > '1', fields => 'bdate,sex,city,verified', }, sub { my $response = shift; if ($response) { my $meta = shift; say Dumper($response); } else { my $meta = shift; warn 'Request failed'; say Dumper($meta); } $cv->end; }); } else { my ($stage, $headers, $body, $cookie) = @_; warn 'Auth failed'; say Dumper(@_); } $cv->end; }); $cv->recv;

For mobile development

Android (Java)

Another official library, this time for Android. It is written in Java and allows you to greatly simplify working with the VKontakte API from this language.

Example of sending a request:

request.executeWithListener(new VKRequestListener() { @Override public void onComplete(VKResponse response) { //Do complete stuff } @Override public void onError(VKError error) { //Do error stuff } @Override public void onProgress(VKRequest.VKProgressType progressType, long bytesLoaded, long bytesTotal) { //I don't really believe in progress } @Override public void attemptFailed(VKRequest request, int attemptNumber, int totalAttempts) { //More luck next time } });

Windows Phone (C#)

The last official development on this list: a basic library for WP development written in C#, similar in functionality to its counterparts for Android and iOS.

Sending a friend list request:

private void GetUserInfoButton_Click(object sender, RoutedEventArgs e) { VKRequest.Dispatch>( new VKRequestParameters( "users.get", "fields", "photo_200, city, country"), (res) => { if (res.ResultCode = = VKResultCode.Succeeded) { VKExecute.ExecuteOnUIThread(() => { var user = res.Data[0]; userImage.Source = new BitmapImage(new Uri(user.photo_200, UriKind.Absolute)); userInfo.Text = user .first_name + » » + user.last_name; }); } }); }

iOS (Objective C)

The official library from VKontakte, designed for writing applications for iOS. Written in Objective-C.

Example code for sending a request:

; } else { NSLog(@"VK error: %@", error); } }];

For hipsters

Rust

There is a library for this language on Github - vkrs. It's not actively developing, but it's at least something. This is what it looks like in action:

extern crate vkrs; use std::{env, io}; use vkrs::*; fn main() { let api = api::Client::new(); let oauth = api.auth( env::var("VK_APP_ID").unwrap(), env::var("VK_APP_SECRET").unwrap()); let auth_uri = oauth.auth_uri(auth::Permission::Audio).unwrap(); // Or if you want to get permissions for specific request: // let auth_uri = oauth.auth_uri_for:: (); println!("Go to {} and enter code below...", auth_uri); let inp = io::stdin(); let code = { let mut buf = String::new(); inp.read_line(&mut buf).unwrap(); buf }; // You may want to save this token for future use to avoid asking user // to authorize the app on each run. let token = oauth.request_token(code.trim()).unwrap(); // The access token is JSON serializable with serde, so you can do it this way: // File::create(TOKEN_FILE).ok().map(|mut f| serde_json::to_writer(&mut f, &token). ok()).unwrap(); // // And then you can load it again: // let token: auth::AccessToken = File::open(TOKEN_FILE).ok().and_then(|mut f| serde_json::from_reader(&mut f).ok ()).unwrap(); let songs = api.get(Some(&token), audio::Search::new() .q(“Poets Of The Fall”) .performer_only(true) .count(200)) .unwrap(); for song in &songs.items { println!("{:?}", song); } }

Golang

Oddly enough, a wrapper for the VK API was also written in Go. Just like the others, it is available on Github. Hello World looks like this:

package main import ( "github.com/urShadow/go-vk-api" "log" "strconv" ) func main() { api := vk.New("ru") // set http proxy //api.Proxy = "localhost:8080" err := api.Init("TOKEN") if err != nil { log.Fatalln(err) } api.OnNewMessage(func(msg *vk.LPMessage) { if msg.Flags&vk.FlagMessageOutBox = = 0 { if msg.Text == “/hello” { api.Messages.Send(vk.RequestParams{ “peer_id”: strconv.FormatInt(msg.FromID, 10), “message”: “Hello!”, “forward_messages ": strconv.FormatInt(msg.ID, 10), }) } } }) api.RunLongPoll() }

If you know a more relevant or functional library for any language, write in the comments, we will definitely update the article.

A hint for programmers: if you register for the Huawei Cup competition, you will get free access to the online school for participants. You can improve your skills and win prizes in the competition itself. Go to registration

C#C++JavaNode.jsOpen SourcePerlPHPPythonRubyTools

Share

Rating
( 1 rating, average 5 out of 5 )
Did you like the article? Share with friends:
For any suggestions regarding the site: [email protected]
Для любых предложений по сайту: [email protected]