Faced a problem, ideas have already run out. The bottom line is this: there is a page on which there is a WYSIWYG editor in which news is written. When sending a form, the data is written to the database. It was necessary to add the crossposting to the VKONTATE group. Because without crutches on PHP, this will not work, then I use OpenApi and jQuery. Wrote function:

function postVK(text, news_id, id_tape) { //функция редиректа function redirectToMain() { if (action == 'subscribe'){ location.href='subscribes.php'; } else { location.href='index.php?id_tape='+id_tape; } } //преобразование мнемоники var HTML=function(){ var x,mnem= {34:"quot",38:"amp",39:"apos",60:"lt",62:"gt",402:"fnof", 338:"OElig",339:"oelig",352:"Scaron",353:"scaron", 376:"Yuml",710:"circ",732:"tilde",8226:"bull",8230:"hellip", 8242:"prime",8243:"Prime",8254:"oline",8260:"frasl",8472:"weierp", 8465:"image",8476:"real",8482:"trade",8501:"alefsym",8592:"larr", 8593:"uarr",8594:"rarr",8595:"darr",8596:"harr",8629:"crarr", 8656:"lArr",8657:"uArr",8658:"rArr",8659:"dArr",8660:"hArr", 8704:"forall",8706:"part",8707:"exist",8709:"empty",8711:"nabla", 8712:"isin",8713:"notin",8715:"ni",8719:"prod",8721:"sum", 8722:"minus",8727:"lowast",8730:"radic",8733:"prop",8734:"infin", 8736:"ang",8743:"and",8744:"or",8745:"cap",8746:"cup",8747:"int", 8756:"there4",8764:"sim",8773:"cong",8776:"asymp",8800:"ne", 8801:"equiv",8804:"le",8805:"ge",8834:"sub",8835:"sup",8836:"nsub", 8838:"sube",8839:"supe",8853:"oplus",8855:"otimes",8869:"perp", 8901:"sdot",8968:"lceil",8969:"rceil",8970:"lfloor",8971:"rfloor", 9001:"lang",9002:"rang",9674:"loz",9824:"spades",9827:"clubs", 9829:"hearts",9830:"diams",8194:"ensp",8195:"emsp",8201:"thinsp", 8204:"zwnj",8205:"zwj",8206:"lrm",8207:"rlm",8211:"ndash", 8212:"mdash",8216:"lsquo",8217:"rsquo",8218:"sbquo",8220:"ldquo", 8221:"rdquo",8222:"bdquo",8224:"dagger",8225:"Dagger",8240:"permil", 8249:"lsaquo",8250:"rsaquo",8364:"euro",977:"thetasym",978:"upsih",982:"piv"}, tab=("nbsp|iexcl|cent|pound|curren|yen|brvbar|sect|uml|"+ "copy|ordf|laquo|not|shy|reg|macr|deg|plusmn|sup2|sup3|"+ "acute|micro|para|middot|cedil|sup1|ordm|raquo|frac14|"+ "frac12|frac34|iquest|Agrave|Aacute|Acirc|Atilde|Auml|"+ "Aring|AElig|Ccedil|Egrave|Eacute|Ecirc|Euml|Igrave|"+ "Iacute|Icirc|Iuml|ETH|Ntilde|Ograve|Oacute|Ocirc|Otilde|"+ "Ouml|times|Oslash|Ugrave|Uacute|Ucirc|Uuml|Yacute|THORN|"+ "szlig|agrave|aacute|acirc|atilde|auml|aring|aelig|ccedil|"+ "egrave|eacute|ecirc|euml|igrave|iacute|icirc|iuml|eth|ntilde|"+ "ograve|oacute|ocirc|otilde|ouml|divide|oslash|ugrave|uacute|"+ "ucirc|uuml|yacute|thorn|yuml").split("|"); for(x=0;x<96;x++)mnem[160+x]=tab[x]; tab=("Alpha|Beta|Gamma|Delta|Epsilon|Zeta|Eta|Theta|Iota|Kappa|"+ "Lambda|Mu|Nu|Xi|Omicron|Pi|Rho").split("|"); for(x=0;x<17;x++)mnem[913+x]=tab[x]; tab=("Sigma|Tau|Upsilon|Phi|Chi|Psi|Omega").split("|"); for(x=0;x<7;x++)mnem[931+x]=tab[x]; tab=("alpha|beta|gamma|delta|epsilon|zeta|eta|theta|iota|kappa|"+ "lambda|mu|nu|xi|omicron|pi|rho|sigmaf|sigma|tau|upsilon|phi|chi|"+ "psi|omega").split("|"); for(x=0;x<25;x++)mnem[945+x]=tab[x]; return { encode:function(text){ return text.replace(/[\u00A0-\u2666<>\&]/g,function(a){ return "&"+(mnem[a=a.charCodeAt(0)]||"#"+a)+";" }) }, decode:function(text){ return text.replace(/\&#?(\w+);/g,function(a,b){ if(Number(b))return String.fromCharCode(Number(b)); for(x in mnem){ if(mnem[x]===b)return String.fromCharCode(x); } }) } } }(); //Спрашиваем, нужно ли добавлять запись в ВК if(confirm("Отправить запись в группу ВКонтакте?")) { //если да, то проверяем авторизацию, если нет, запрашиваем ее. VK.Auth.getLoginStatus(authInfo); //основная часть функции. function authInfo(auth) { //если авторизация есть if (auth.session) { //удаляем все HTML-тэги из него var strippedText = HTML.decode(text.replace(/(<([^>]+)>)/ig,"")); //вызываем АПИ для добавления на стену VK.Api.call('wall.post', {owner_id: -123456789, from_group: 1, message: strippedText, attachments: 'http://www.site.ru/news/'+news_id}, function(r) { //если пришел ответ - запись добавлена if(r.response){ //сообщаем об успехе alert("Запись успешно добавлена в группу ВКонтакте"); //и редиректим redirectToMain(); } //если ответ не пришел - репост отменен else { //сообщаем об этом alert("Запись в группу ВКонтакте отменена"); //редиректим redirectToMain(); } }); //если авторизации нет } else { //вызываем АПИ авторизации, и делаем рекурсию VK.Auth.login(authInfo); } } //ну а коль барин не желает репостить запись }else{ //просто посылаем его редиректом redirectToMain(); } } 

It accepts the text of the post when sending it from the editor, cleans it of HTML tags and entities and sends a request for wall.post. The function of sending such (do not kick who did this - xs):

 function save_message(){ $("#bg_form_div").css('display','block'); params = { id_tape:id_tape, action:action, id_message:id_message }; var fields = $('#mess_form').serializeArray(); for (i in fields ) { params[fields [i].name] = fields [i].value; } if ($('#t_content')[0]){ var txt = CKEDITOR.instances.t_content; params['t_content']=txt.getData(); } if ($('#foto')[0]) params['file']=$('#foto')[0]; params['is_cats']=a_cats; var message=''; JsHttpRequest.query('message.ajax.php', params,function(result, errors) { $("#bg_form_div").css('display','none'); if (result&&!result.success){ $.each( result.messages, function(i,n){ message+=n+"\n"; }); alert(message); } if (result&&result.success){ $.each(result.messages, function(i,n){ message+=n+"\n"; ///////////////////////////////////////////////////////////////////////////////////////////////// var news_id=message.substring(0,message.indexOf(':')); $.when(alert(message)).done(postVK($("#t_content").text(), news_id, id_tape)); ///////////////////////////////////////////////////////////////////////////////////////////////// }); } },true); } 

slashes indicated the place where he pushed the function of sending to VC. In fact, here the function simply sends the data by Ajax to a php file, which loads everything into the database.

The problem itself:

when sending one text (for example, 2000 characters long) - VK accepts it without problems, and when sending another (for example 3000 characters or 1500 characters) - VK rejects and breaks the connection, but at the same time accepts the same text after cropping to, for example , 500 characters. There are suspicions that this is due to the limitations of the GET method (8192 bytes), but I am not quite sure that 1k characters can occupy so much (encoding of CP-1251 files)

What is this secret magic and how to avoid it? Thank!

PS: jQuery version 1.5 (above in any way)

UPD: rights requested by the application, with scope = wall, groups, offline: enter image description here

    1 answer 1

    The Open API and JavaScript SDK use JSONP to access API methods. JSONP, as you know, with each request creates a <script> element, where the src attribute substitutes the query string with the parameters you passed. So browsers have a limit on the length of the link - 2000 characters . Since JSONP does not support the POST protocol due to its implementation, you cannot do anything on the client side.

    If this WYSIWYG editor is part of the site admin panel (i.e. if only the editors of your site can write news), then it makes sense to put the cross-posting of news on the backend, in your case PHP. You just need to create an application like standalone (it’s important to create this type; other applications cannot use the wall.post method from the server side), get an unlimited key with the necessary rights, save this key somewhere in the site’s configs and access API methods directly using cURL or any other solution for HTTP requests.

    • The application is standalone, but through PHP it was impossible to access wall.post - api returns an access error. But there I received the token through the authorization code, apparently the problem is this. - Constantine
    • @Constantine, get the access key according to the scheme Implicit Flow . - neluzhin
    • He killed three hours now on crutches to get a token according to this scheme. Received, but when accessing the browser https: / / api.vk.com/method/wall.post?access_token=1234567 ..... etc. Received a familiar response: {"error": {"error_code": 15, "error_msg": "Access denied: no access to call this method", "request_params": [{"key": "oauth", "value": "1"}, {"key": "method", "value": "wall.post"}]}} - Constantine
    • @Konstantin, simply open the link https://api.vk.com/oauth/authorize?client_id=APPLICATION_ID&scope=SCOPE&response_type=token&v=5.60 , replacing APPLICATION_ID and SCOPE with your own values. When specifying access rights, do not forget to add the right offline . - neluzhin
    • one