Skip to content

Instantly share code, notes, and snippets.

@alright
Last active September 19, 2022 18:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save alright/1479977 to your computer and use it in GitHub Desktop.
Save alright/1479977 to your computer and use it in GitHub Desktop.
Vkontakte API
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE);
class Vkapi {
protected $_access_token = '';
protected $_client_id = 0;
protected $_version = '5.0';
public static function factory ()
{
$class = get_class();
return new $class;
}
public function method ($method, array $params = array(), $as_array = FALSE)
{
// Build URL
$url = 'https://api.vk.com/method/'.$method.'?';
$url .= http_build_query(array_merge($params, array(
'access_token' => $this->_access_token,
'v' => $this->_version
)));
// Send request
$content = file_get_contents($url);
// Decode result
$raw_result = json_decode($content, (bool) $as_array);
$result = $as_array ? $raw_result['response'] : $raw_result->response;
if ($result === NULL)
{
throw new Exception('Some error with VK API: '.$content);
}
return $result;
}
public function auth ()
{
echo file_get_contents('http://api.vk.com/oauth/authorize?client_id='.$this->_client_id.'&scope=offline,video,wall&redirect_uri=http://api.vk.com/blank.html&display=page&response_type=token');
}
}
// Получаем access_token, один раз, не самое удачное решение — ибо мы выводим html от вконтакта. Но тем не менее, заполнив форму входа ее можно отправить и получить нужный access_token. Так как при запроса запрашиваются права оффлайн-доступа, этот токен будет работать вечно, до смены пароля аккаунта владельца. Дальше его необходимо прописать в свойство в классе. А так же не забыть, ниже в классе, указать client_id — id приложения.
echo VKApi::factory()->auth();
exit; // убрать, когда этот этап пройден
// Дальше используем API как нам хочется
VkApi::factory()->method('wall.post', array(
'owner_id' => '%id%', // id страницы, куда отправить. Если паблик или группа - добавить минус впереди.
'message' => '%message%',
'from_group' => 1
));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment