B
B
Barders2022-03-20 13:44:29
API
Barders, 2022-03-20 13:44:29

How to publish photos in classmates via API?

I want to publish posts via API to the classmates group, but there is a problem with the photo.

function getUrl($url, $type = "GET", $params = array(), $timeout = 30, $image = false, $decode = true)
{
    if ($ch = curl_init())
    {
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, false);

        if ($type == "POST")
        {
            curl_setopt($ch, CURLOPT_POST, true);

            // Картинка
            if ($image) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            }
            // Обычный запрос       
            elseif($decode) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, urldecode(http_build_query($params)));
            }
            // Текст
            else {
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
            }
        }

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_USERAGENT, 'PHP Bot');
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

        $data = curl_exec($ch);

        curl_close($ch);

        // Еще разок, если API завис
        if (isset($data['error_code']) && $data['error_code'] == 5000) {
            $data = getUrl($url, $type, $params, $timeout, $image, $decode);
        }

        return $data;

    }
    else {
        return "{}";
    }
}

// Массив аргументов в строку
function arInStr($array)
{
    ksort($array);

    $string = "";

    foreach($array as $key => $val) {
        if (is_array($val)) {
            $string .= $key."=".arInStr($val);
        } else {
            $string .= $key."=".$val;
        }
    }

    return $string;
}

// 1. Получим адрес для загрузки 1 фото

$params = array(
    "application_key"   =>  $ok_public_key,
    "method"            => "photosV2.getUploadUrl",
    "count"             => 1,  // количество фото для загрузки
    "gid"               => $ok_group_id,
    "format"            =>  "json"
);

// Подпишем запрос
$sig = md5( arInStr($params) . md5("{$ok_access_token}{$ok_private_key}") );

$params['access_token'] = $ok_access_token;
$params['sig']          = $sig;

// Выполним
$step1 = json_decode(getUrl("https://api.ok.ru/fb.do", "POST", $params), true);
echo "step1";
echo "<pre>";
print_r($step1);
echo "</pre>";
// Если ошибка
if (isset($step1['error_code'])) {
  // Обработка ошибки
    exit();
}
// Идентификатор для загрузки фото
$photo_id = $step1['photo_ids'][0];

// 2. Закачаем фотку

// Предполагается, что картинка располагается в каталоге со скриптом
$params = array(
    "pic1" => "https://localhost/DSC_0794.JPG",
);

// Отправляем картинку на сервер, подписывать не нужно
$step2 = json_decode( getUrl( $step1['upload_url'], "POST", $params, 30, true), true);
echo "step2";
echo "<pre>";
print_r($step2);
echo "</pre>";

// Если ошибка
if (isset($step2['error_code'])) {
   // Обработка ошибки
    exit();
}

// Токен загруженной фотки
$token = $step2['photos'][$photo_id]['token'];

// Заменим переносы строк, чтоб не вываливалась ошибка аттача
$message_json = str_replace("\n", "\\n", $message);

// 3. Запостим в группу
$attachment = '{
                    "media": [
                        {
                            "type": "text",
                            "text": "'.$message_json.'"
                        },
                        {
                            "type": "photo",
                            "list": [
                                {
                                    "id": "'.$token.'"
                                }
                            ]
                        }
                    ]
                }';

$params = array(
    "application_key"   =>  $ok_public_key,
    "method"            =>  "mediatopic.post",
    "gid"               =>  $ok_group_id,
    "type"              =>  "GROUP_THEME",
    "attachment"        =>  $attachment,
    "format"            =>  "json",
);

// Подпишем
$sig = md5( arInStr($params) . md5("{$ok_access_token}{$ok_private_key}") );

$params['access_token'] = $ok_access_token;
$params['sig']          = $sig;

$step3 = json_decode( getUrl("https://api.ok.ru/fb.do", "POST", $params, 30, false, false ), true);
echo "step3";
echo "<pre>";
print_r($step3);
echo "</pre>";

// Если ошибка
if (isset($step3['error_code'])) {
    // Обработка ошибки
    echo "<pre>";
    print_r($step3);
    echo "</pre>";
    exit();
}

// Успешно
echo "<pre>";
    print_r($step3);
    echo "</pre>";
echo 'OK';


https://localhost/DSC_0794.JPG replaced, the photo is taken from the variable, and in it the full path to the photo

and step 1 passes and stumbles on step2:
step1

Array
(
    [photo_ids] => Array
        (
            [0] => hWBrpxnOpViyYLm9RgX65slCRq8LdTBehNlKheK0jxPyI/bUVn57FQ==
        )

    [upload_url] => https://gup.mycdn.me/uploadImage?apiToken=hK9jdyoSHchfHSxSdqQftSnVlasQTydxqlB8C18ey3hjHovokySWlqYhOs2ZHxfhpkeaBKQ5jnahGzqnRCwyzV2XZ4R36RnhbO7w%2FkV%2Buk9h392tHJ06Xwz02ZnSzgmbQyJeae5pAhll%2Bcvv5%2Bwv0NTsy0SADmNeSH%2BtjD6APvc%3D&photoIds=hWBrpxnOpViyYLm9RgX65slCRq8LdTBehNlKheK0jxPyI%2FbUVn57FQ%3D%3D
    [expires] => 2022.03.21 13:31
    [expires_ms] => 1647858704374
    [ttl_ms] => 86399994
)

step2

Array
(
    [error_msg] => one.image.upload.client.ContentUploadServerException: NO_IMAGE
    [error_code] => 505
    [error_data] => NO_IMAGE
)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Barders, 2022-03-20
@Barders

Understood. you can not pass the path in pic, you must explicitly transfer the file.
I did this:
$params = array(
"pic1" => new CurlFile(" https://localhost/DSC_0794.JPG "),
);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question