S
S
Shlyahten2017-01-09 20:58:52
PHP
Shlyahten, 2017-01-09 20:58:52

Why is the request signed incorrectly in the OK API?

Hello, I've run into a strange problem. I'm trying to add a picture to a media topic, but after that the script incorrectly signs the request. Please help me figure it out. Without the photo line, everything works fine.
Just in case, here is the whole code:

<?php
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

 function getUrl($url, $type="GET", $params=array(), $timeout=30) {
    if ($ch = curl_init()) {
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        if ($type == "POST") {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, urldecode(http_build_query($params)));
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_USERAGENT, 'PHP Bot');
        $data = curl_exec($ch);
        curl_close($ch);
        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;
}

function uploadPhoto($url_upload){
  $target=$url_upload;
  
  $cfile = curl_file_create('testpic.jpg','image/jpg','pic1');
  
  $imgdata = array('myimage' => $cfile);
  
  $curl = curl_init();
  curl_setopt($curl, CURLOPT_URL, $target);
  curl_setopt($curl, CURLOPT_USERAGENT,'PHP Bot');
  curl_setopt($curl, CURLOPT_HTTPHEADER,array('Content-Type: multipart/form-data'));
  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // stop verifying certificate
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 
  curl_setopt($curl, CURLOPT_POST, true); // enable posting
  curl_setopt($curl, CURLOPT_POSTFIELDS, $imgdata); // post images 
  curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); // if any redirection after upload
  return $r = curl_exec($curl); 
  curl_close($curl);
}

$ok_access_token = "";//Наш вечный токен
$ok_private_key = "";//Секретный ключ приложения
$ok_public_key = "";//Публичный ключ приложения
$ok_group = ""; //ID группы

//
// Для photo
$params_p = array(
    "application_key"=>$ok_public_key,
    "method"=>"photosV2.getUploadUrl",
    "gid"=>$ok_group,//ID нашей группы
  "count"=>"1",//количество фото
    "format"=>"json"
);
$sig = md5(arInStr($params_p).md5("{$ok_access_token}{$ok_private_key}"));
$params_p["access_token"]=$ok_access_token;
$params_p["sig"]=$sig;

$result = json_decode(getUrl("https://api.ok.ru/fb.do", "POST", $params_p), true);
//Если парсер не смог открыть нашу ссылку (иногда он это делает со второй попытки), то отправляем ещё раз
if (isset($result['error_code']) && $result['error_code'] == 5000) {
    $result = json_decode(getUrl("https://api.ok.ru/fb.do", "POST", $params_p), true);
}
//var_dump($result);
echo 'Photo id: '.$photo_id=$result['photo_ids'][0];
echo '<br>';
echo 'URL: '.$url_upload=$result['upload_url'];

var_dump($result = json_decode(uploadPhoto($url_upload), true));
echo 'Photo token: '.$photo_token=$result['photos'][$photo_id]['token'];
// Конец photo
//


$params = array(
    "application_key"=>$ok_public_key,
    "method"=>"mediatopic.post",
    "gid"=>$ok_group,//ID нашей группы
    "type"=>"GROUP_THEME",
    "attachment"=>'{"media": [
    	{"type": "photo", "list": [
        	{"id": "'.$photo_token.'"}
    	]},
    	{"type": "link","url": "https://www.google.com"},
    	{"type": "text", "text": "Текст в придачу"}
    ]}',
    "format"=>"json"
);
$sig = md5(arInStr($params).md5("{$ok_access_token}{$ok_private_key}"));
$params["access_token"]=$ok_access_token;
$params["sig"]=$sig;

$result = json_decode(getUrl("https://api.ok.ru/fb.do", "POST", $params), true);
//Если парсер не смог открыть нашу ссылку (иногда он это делает со второй попытки), то отправляем ещё раз
if (isset($result['error_code']) && $result['error_code'] == 5000) {
    $result = json_decode(getUrl("https://api.ok.ru/fb.do", "POST", $params), true);
}
var_dump($result);
?>

Part of the code, including the signature, was taken from the Internet. I immediately apologize for the poor quality of the code)
The problem appears at the end with the last request. An error message appears:
array (size=3)
  'error_code' => int 104
  'error_msg' => string 'PARAM_SIGNATURE : Invalid signature ********, calculated by string application_key=*******Aattachment={"media": [
    	{"type": "photo", "list":[{"id": "hVyr0BrE6e pWLr2ULGgLrJ869Pfl 8797DbUoYbISX3bUxfxtkkEZXjdROoRkF6sLGbL2p6ARyzvM7447VWuuqxlJqazdYPxOqf4biSQQ/bYwU/2Dovj41EFmNIvLJPNYrzIBQ3BHy/b4FAuxiKHDAFgUP4sJXnnA2lgttIk8mc2VRdQf2nVQ=="}]},
    	{"type": "link","url": "https://www.google.com"},
    	{"type": "text", "text": "Текст в придачу"}
    ]}format=jsongi'... (length=591)
  'error_data' => null

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Ruchiev, 2017-01-09
@Shlyahten

test the request with your data here https://apiok.ru/dev/methods/rest/mediatopic/media...
there is a glitch that the values ​​in the array must be in a certain order, otherwise it gives such an error

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question