<?php
spl_autoload_register(function($classname){
$path = str_replace('\\', '/', $classname);
$path = __DIR__ . '/' . $path . '.php';
if (file_exists($path)) {
include($path);
}
});
$vk = new \VkCallbackServer();
$vk->run();
<?php
namespace core;
abstract class VkApiCallbackServer {
protected $config;
protected $data;
protected $params;
protected $url;
protected $request_params;
protected $logger;
public function __construct() {
$this->config = include("./config/config.php");
$this->params["access_token"] = $this->config["tokens"]["access_token"];
$this->params["secret"] = $this->config["tokens"]["secret"];
$this->params["v"] = $this->config["tokens"]["v"];
$this->logger = new \core\Logger();
$this->logger->add("VkApiCallback создан");
}
protected function withParams($params) {
$this->request_params = $params;
return $this;
}
protected function execute() {
$this->request_params = array_merge($this->request_params, $this->params);
$request = curl_init($this->url);
curl_setopt($request, CURLOPT_POST, 1);
curl_setopt($request, CURLOPT_POSTFIELDS, $this->request_params);
$result = json_decode(curl_exec($request));
curl_close($request);
$this->url=null;
$this->request_params=null;
//return $result;
}
protected function method($method) {
$this->url = 'https://api.vk.com/method/'.$method;
return $this;
}
public function run() {
if (!isset($_REQUEST)) {
die('ok');
}
$data = json_decode(file_get_contents("php://input"));
if ($data->secret !== $this->config["tokens"]["secret"]) {
die('ok');
};
$method = $data->type;
$this->logger->add("Пришел запрос типа " . $method);
if (method_exists($this,$method)) {
$this->$method($data);
$this->logger->add("Метод " . $method . ' существует');
}
else {
$this->logger->add("Метод " . $method . ' не существует');
die('ok');
}
}
}
<?php
class VkCallbackServer extends \core\VkApiCallbackServer {
public function message_new($data) {
if ($data->object->body == 'hi') {
$peer_id = $data->object->user_id;
$this->method('messages.send')->withParams([
'user_id' => $peer_id,
'random_id' => rand(),
'peer_id' => $this->config["group_id"],
'message' => 'hi u too',
])->execute();
}
die('ok');
}
public function message_reply() {
echo "ok";
}
public function confirmation($data) {
echo $this->config["tokens"]["confirmation"];
}
}