@vitafon007

Как правильно загружать картинки через VK API на PHP?

Доброго времени суток, знатаки.
Уже 3 ночи мучаюсь с этим вопросом. Думал смогу сам, не смог.
Решил скрипт загрузки написать отдельным кодом, чтобы уже точно не путаться...
Перепробовал много способов из гугла. Ничего не помогает(
есть такой код

<?php

	$token = 'токен';
	$group_id = групп ид без ' - ';

	/*$url = 'http://ae01.alicdn.com/kf/UT8yr3qXJNbXXagOFbXZ.jpg_640x10000.jpg';
	$img = 'image.jpg';
	file_put_contents($img, file_get_contents($url));*/

	$url = 'https://api.vk.com/method/photos.getWallUploadServer?group_id='.$group_id.'&access_token=' . $token;
	
	$ch = curl_init( $url ); 
	curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.2 (KHTML, like Gecko) Chrome/22.0.1216.0 Safari/537.2" );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); 
	curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false ); 
	curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false ); 
	$response = curl_exec( $ch );
	curl_close( $ch ); 
	
	$json = json_decode($response, true);
	var_dump($json);
	echo '<br />';

	$url = $json['response']['upload_url'];
	$lala = dirname(__FILE__)."/image.jpg";
    $cfile = curl_file_create($lala,'image/jpeg','image1.jpg');
	
	$ch = curl_init( $url ); 
	curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.2 (KHTML, like Gecko) Chrome/22.0.1216.0 Safari/537.2" );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); 
	curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false ); 
	curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
	curl_setopt($ch, CURLOPT_POSTFIELDS, array("file1" => $cfile));	
	$response = curl_exec( $ch );
	curl_close( $ch ); 
	

	
	$json = json_decode($response, true);
	var_dump($json);
	echo '<br />';
	
	$url = 'https://api.vk.com/method/photos.saveWallPhoto?access_token=' . $token . '&server=' . $json[ 'server' ] . '&photo=' . $json[ 'photo' ] . '&hash=' . $json[ 'hash' ];
	$ch = curl_init( $url ); 
	curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.2 (KHTML, like Gecko) Chrome/22.0.1216.0 Safari/537.2" );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); 
	curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false ); 
	curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false ); 
	$response = curl_exec( $ch );
	curl_close( $ch ); 
	
	$json = json_decode($response, true);
	var_dump($json);
	echo '<br />';

	?>


в ответ получаю:
array(1) { ["response"]=> array(3) { ["upload_url"]=> string(189) "https://pu.vk.com/c626420/upload.php?act=do_add&mid=63304746&aid=-14&gid=ид группы&hash=8c791b973c407226faa94e4d674e5897&rhash=f08c4b2265110bc92633b1a03e8ad2ca&swfupload=1&api=1&wallphoto=1" ["aid"]=> int(-14) ["mid"]=> int(63304746) } }
array(3) { ["server"]=> int(626420) ["photo"]=> string(536) "[{"photo":"0618480e2f:z","sizes":[["s","626420746","3e7a3","a_WzJNPiXc4",56,75],["m","626420746","3e7a4","ETTmFXgdEHw",97,130],["x","626420746","3e7a5","MeVgijSc5WY",453,604],["y","626420746","3e7a6","7HTZiQQ9BwA",605,807],["z","626420746","3e7a7","DQiEcry29t8",640,853],["o","626420746","3e7a8","_xPuK1YsWfc",130,173],["p","626420746","3e7a9","4WwNGzc4pYI",200,267],["q","626420746","3e7aa","BrYNwvRTbIk",320,427],["r","626420746","3e7ab","y0is0yCyM6M",510,680]],"kid":"9876ff088dc3168b95c8f31326fc49ca","debug":"xszmzxzyzzzozpzqzrz"}]" ["hash"]=> string(32) "062c80b517bea2666f2fd02df25ea9d0" }
array(1) { ["error"]=> array(3) { ["error_code"]=> int(121) ["error_msg"]=> string(12) "Invalid hash" ["request_params"]=> array(5) { [0]=> array(2) { ["key"]=> string(5) "oauth" ["value"]=> string(1) "1" } [1]=> array(2) { ["key"]=> string(6) "method" ["value"]=> string(20) "photos.saveWallPhoto" } [2]=> array(2) { ["key"]=> string(6) "server" ["value"]=> string(6) "626420" } [3]=> array(2) { ["key"]=> string(5) "photo" ["value"]=> string(536) "[{"photo":"0618480e2f:z","sizes":[["s","626420746","3e7a3","a_WzJNPiXc4",56,75],["m","626420746","3e7a4","ETTmFXgdEHw",97,130],["x","626420746","3e7a5","MeVgijSc5WY",453,604],["y","626420746","3e7a6","7HTZiQQ9BwA",605,807],["z","626420746","3e7a7","DQiEcry29t8",640,853],["o","626420746","3e7a8","_xPuK1YsWfc",130,173],["p","626420746","3e7a9","4WwNGzc4pYI",200,267],["q","626420746","3e7aa","BrYNwvRTbIk",320,427],["r","626420746","3e7ab","y0is0yCyM6M",510,680]],"kid":"9876ff088dc3168b95c8f31326fc49ca","debug":"xszmzxzyzzzozpzqzrz"}]" } [4]=> array(2) { ["key"]=> string(4) "hash" ["value"]=> string(32) "062c80b517bea2666f2fd02df25ea9d0" } } } }


как решить проблему?(
  • Вопрос задан
  • 7141 просмотр
Пригласить эксперта
Ответы на вопрос 1
@Nc_Soft
<?php
$token = '**************************************';
$group_id = '1111111';
$vk = new Vk($token);

$image_path = 'image.png';
copy('https://www.google.ru/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png', 'image.png');

$upload_server = $vk->photosGetWallUploadServer($group_id);

$upload = $vk->uploadFile($upload_server['upload_url'], $image_path);

$save = $vk->photosSaveWallPhoto([
        'group_id' => $group_id,
        'photo' => $upload['photo'],
        'server' => $upload['server'],
        'hash' => $upload['hash']
    ]
);

$attachments = sprintf('photo%s_%s', $save[0]['owner_id'], $save[0]['id']);


$post = $vk->wallPost([
    'owner_id' => "-$group_id",
    'from_group' => 1,
    'message' => "блаблабла",
    'attachments' => $attachments
]);


class Vk
{
    private $token;
    private $v = '5.37';

    public function __construct($token)
    {
        $this->token = $token;
    }

    public function wallPost($data)
    {
        return $this->request('wall.post', $data);
    }

    public function photosGetWallUploadServer($group_id)
    {
        $params = [
            'group_id' => $group_id,
        ];
        return $this->request('photos.getWallUploadServer', $params);
    }

    /**
     * @param $params [user_id, group_id, photo, server, hash]
     * @return mixed
     * @throws \Exception
     */
    public function photosSaveWallPhoto($params)
    {
        return $this->request('photos.saveWallPhoto', $params);
    }

    public function uploadFile($url, $path)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, true);

        if (class_exists('\CURLFile')) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, ['file1' => new \CURLFile($path)]);
        } else {
            curl_setopt($ch, CURLOPT_POSTFIELDS, ['file1' => "@$path"]);
        }

        $data = curl_exec($ch);
        curl_close($ch);
        return json_decode($data, true);
    }

    private function request($method, array $params)
    {
        $params['v'] = $this->v;

        $ch = curl_init('https://api.vk.com/method/' . $method . '?access_token=' . $this->token);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        $data = curl_exec($ch);
        curl_close($ch);
        $json = json_decode($data, true);
        if (!isset($json['response'])) {
            throw new \Exception($data);
        }
        usleep(mt_rand(1000000, 2000000));
        return $json['response'];
    }
}
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы