How to use publish_action permission of facebook api? - javascript

I want to post base64 encoded images in facebook. Below is my code
function postImageToFacebook(authToken, filename, mimeType, imageData, message) {
// this is the multipart/form-data boundary we'll use
var boundary = '----ThisIsTheBoundary1234567890';
// let's encode our image file, which is contained in the var
var formData = '--' + boundary + '\r\n'
formData += 'Content-Disposition: form-data; name="source"; filename="' + filename + '"\r\n';
formData += 'Content-Type: ' + mimeType + '\r\n\r\n';
for (var i = 0; i < imageData.length; ++i) {
formData += String.fromCharCode(imageData[i] & 0xff);
}
formData += '\r\n';
formData += '--' + boundary + '\r\n';
formData += 'Content-Disposition: form-data; name="message"\r\n\r\n';
formData += message + '\r\n'
formData += '--' + boundary + '--\r\n';
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://graph.facebook.com/me/photos?access_token=' + authToken, true);
xhr.onload = xhr.onerror = function () {
console.log(xhr.responseText);
};
xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
if(!xhr.sendAsBinary){
xhr.sendAsBinary = function(datastr) {
function byteValue(x) {
return x.charCodeAt(0) & 0xff;
}
var ords = Array.prototype.map.call(datastr, byteValue);
var ui8a = new Uint8Array(ords);
this.send(ui8a.buffer);
}
}
xhr.sendAsBinary(formData);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert('Your image has been successfully shared');
}
}
};
var data = yourDesigner.getProductDataURL();
var encodedPng = data.substring(data.indexOf(',') + 1, data.length);
var decodedPng = Base64Binary.decode(encodedPng);
// var decodedPng = dataURItoBlob(test,"png");
FB.getLoginStatus(function (response) {
var request = {};
if (response.status === "connected") {
request = postImageToFacebook(response.authResponse.accessToken, "test", "image/png", decodedPng, "www.captivations.com.au");
} else if (response.status === "not_authorized") {
FB.login(function (response) {
request = postImageToFacebook(response.authResponse.accessToken, "test", "image/png", decodedPng, "www.captivations.com.au");
}, {scope: "publish_actions"});
} else {
FB.login(function (response) {
request = postImageToFacebook(response.authResponse.accessToken, "test", "image/png", decodedPng, "www.captivations.com.au");
}, {scope: "publish_actions"});
}
});
I can post images when i logged into my facebook account . But when i tried to post the images from other accounts i got following error
"error": {
"message": "(#200) Requires extended permission: publish_actions",
"type": "OAuthException",
"code": 200,
"fbtrace_id": "EAcb5VG/eFS"
}
I think its permission issue of the facbook api. Can you help me on managing "publish action" permission of facebook?

From https://developers.facebook.com/docs/facebook-login/permissions:
The "publish_actions" provides access to publish Posts, Open Graph actions, achievements, scores and other activity on behalf of a person using your app.
Your app does not need to request the publish_actions permission in order to use the Feed Dialog, the Requests Dialog or the Send Dialog.
If you use the "publish_actions" permission in another way you have to requests Facebook to review how your app uses the "publish_actions" permission.

Related

Where my mistake in converting jquery ajax to pure js ajax request

That's my JQuery code which is currently working ->
$("#newsLetter-form").on('submit',function(event){
event.preventDefault();
email = $('#emailId').val();
console.log(email);
$.ajax({
url: '/subscribes/emailSubscribe',
type:'POST',
data:{
"_token": "{{ csrf_token() }}",
email:email,
},
success:function(response){
console.log(response);
$('#responseFromSub').text("Registred!");
$('#responseFromSub').css('background','lightgreen')
$('#newsLetter-form').css('display','none');
$('.sucsessMessage').fadeIn(1);
setTimeout(function(){$('.sucsessMessage').fadeOut(1);$('#newsLetter-form').css('display','flex');},3000);
},
error:function(response){
console.log(response);
var val = 'asdasd:111122:123123123';
var response1 = response.responseJSON.message.substring(response.responseJSON.message.indexOf("\"title\":"));
response1 = response1.split(":").pop();
response1 = response1.split(',')[0];
response1 = response1.replace("\"", "");
response1 = response1.replace("\"", "");
console.log(response1);
$('#responseFromSub').text(response1);
$('#responseFromSub').css('background','red');
$('#newsLetter-form').css('display','none');
$('.sucsessMessage').fadeIn(1);
setTimeout(function(){$('.sucsessMessage').fadeOut(1);$('#newsLetter-form').css('display','flex');},3000);
},
});
});
And this is my converted code which isn't working, it says 400 bad request wrong data. I'm using laravel and mailchimp for newsletter with jquery everything is working but with this pure js code, no ->
function myFunc123() {
var email1 = document.getElementById("emailId").value;
alert(email1);
var data = {
"_token": '{{ csrf_token() }}',
email: email1
};
var boundary = String(Math.random()).slice(2);
var boundaryMiddle = '--' + boundary + '\r\n';
var boundaryLast = '--' + boundary + '--\r\n'
var body = ['\r\n'];
for (var key in data) {
body.push('Content-Disposition: form-data; name="' + key + '"\r\n\r\n' + data[key] + '\r\n');
}
body = body.join(boundaryMiddle) + boundaryLast;
var xhr = new XMLHttpRequest();
xhr.open('POST', '/subscribes/emailSubscribe', true);
xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
xhr.onreadystatechange = function () {
if (this.readyState != 4) return;
alert(this.responseText);
}
xhr.send(body);
}
I fixed it the problem was here ->
var email1 = document.getElementById("emailId").value;
alert(email1);
var data = {
"_token": '{{ csrf_token() }}',
email: email1
Now it's working..
BUT the page is refreshing after request how can I disable refreshing ?
You forgot event.preventDefault(), which was in the jQuery code. The default behaviour is to refresh the page on submit (which is a very dumb default), you want to prevent this.
Okay, final converted version looks like that.
var ele = document.getElementById("newsLetter-form");
ele.addEventListener("submit", handleEmail, false);
function handleEmail(event) {
event.preventDefault();
var email1 = document.getElementById("emailId").value;
var data = {
"_token": '{{ csrf_token() }}',
email: email1
};
var boundary = String(Math.random()).slice(2);
var boundaryMiddle = '--' + boundary + '\r\n';
var boundaryLast = '--' + boundary + '--\r\n'
var body = ['\r\n'];
for (var key in data) {
body.push('Content-Disposition: form-data; name="' + key + '"\r\n\r\n' + data[key] + '\r\n');
}
body = body.join(boundaryMiddle) + boundaryLast;
var xhr = new XMLHttpRequest();
xhr.open('POST', '/subscribes/emailSubscribe', true);
xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
xhr.onreadystatechange = function () {
if(xhr.status===200)
{
document.getElementById("responseFromSub").innerHTML="Registered";
document.getElementById("responseFromSub").style.background="lightgreen";
document.getElementById("newsLetter-form").style.display="none";
document.getElementsByClassName("sucsessMessage")[0].style.display="block";
setTimeout(function () {
document.getElementsByClassName("sucsessMessage")[0].style.display="none";
document.getElementById("newsLetter-form").style.display="flex";
}, 3000);
}
else
{
document.getElementById("responseFromSub").innerHTML="Something goes wrong..";
document.getElementById("responseFromSub").style.background="red";
document.getElementById("newsLetter-form").style.display="none";
document.getElementsByClassName("sucsessMessage")[0].style.display="block";
setTimeout(function () {
document.getElementsByClassName("sucsessMessage")[0].style.display="none";
document.getElementById("newsLetter-form").style.display="flex";
}, 3000);
}
}
xhr.send(body);
}

Azure Log Analytics POST / Search Query in Plain HTML using javascript

I want to Upload an event to Azure LOG Analytics and Retrieve an event using plain JavaScript with XMLHTTPRequest or JQuery rest .
1.Using powershell invoke-webrequest, i am able to Upload the event but not through the below request from html
2. Need help in retrieving an event from Azure Log Analytics RestApi
for the first one Here is the sample code HTTP405: BAD METHOD - The HTTP verb used is not supported.
var strBody = {
"Hostname": "sdfsfsdf",
"Customer": "sdfsfdsfdsf",
"RoundTripLatencyInMs": 67,
};
debugger;
customerId = "xxxxxxxxxxxxxxx";
sharedkey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
logType = "xxxxxxxxx";
TimeStampField = "YYYY-MM-DDThh:mm:ssZ";
// encodebody = stringToUtf16ByteArray(JSON.stringify(strBody).toString('utf8'));//encode_utf8(JSON.stringify(strBody));
str = strBody;
var byteArray = [];
for (var i = 0; i < str.length; i++)
if (str.charCodeAt(i) <= 0x7F)
byteArray.push(str.charCodeAt(i));
else {
var h = encodeURIComponent(str.charAt(i)).substr(1).split('%');
for (var j = 0; j < h.length; j++)
byteArray.push(parseInt(h[j], 16));
}
// return byteArray;
encodebody = byteArray;
method = 'POST';
resource = '/api/logs';
//contentType = 'application/json; charset=utf-8';
var d =new Date();
msdate = d.toUTCString(); //'Thu, 14 Jul 2017 06:35:52 GMT';
contentLength = encodebody.length;
//Signature
xHeaders = "x-ms-date:" + msdate;
stringToHash = method + "\n" + contentLength + "\n" + xHeaders + "\n" + resource;
//message=stringToHash;
var hash = CryptoJS.HmacSHA256(stringToHash, sharedkey);
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
// document.write(hashInBase64);
//authorization = 'SharedKey ' + customerId +':'+ hashInBase64 ;
signature = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(CryptoJS.enc.Utf8.parse(stringToHash), CryptoJS.enc.Base64.parse(sharedkey)));
authorization = 'SharedKey ' + customerId + ':' + signature;
uri = "https://" + customerId + ".ods.opinsights.azure.com" + resource + "?api-version=2016-04-01";
var myHttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
debugger;
$.ajax({
url: uri,
type: 'POST',
success: function (data) {
//do something to data
},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', "SharedKey " + customerId + ":" + signature);
xhr.setRequestHeader('x-ms-date', msdate);
xhr.setRequestHeader('x-ms-version', '2014-02-14');
xhr.setRequestHeader('Accept-Charset', 'UTF-8');
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
//xhr.setRequestHeader('Accept', 'application/json;odata=nometadata');
xhr.setRequestHeader("Log-Type", logType);
xhr.setRequestHeader("time-generated-field", TimeStampField);
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
//xhr.setRequestHeader('DataServiceVersion', '3.0;NetFx');
//xhr.setRequestHeader('MaxDataServiceVersion', '3.0;NetFx');
},
datatype:'json',
//contentType: 'application/json',
data:encodebody,
error: function (rcvData) {
console.log("ERRor");
console.log(rcvData);
}
});
Any pointers will be helpfull
As you made a REST call from browser side using javascript, the browser would first send an HTTP request by the OPTIONS method to the resource to look for CORS headers. See Preflighted requests. And Log Analytics REST API doesn't allow the OPTIONS HTTP verb. It means that the API doesn't support CORS. So, it raises your issue.
So, you should call the REST API by using server side language like PHP, Python, Node.js, etc.

Export to excel in MVC application returns error

I want to export some data in MVC application. I keep getting an error, which is very strange - I can't resolve that error from Fiddler.
Here is java script which calls controller action:
var exportXLSDeadlinesParent = function () {
if ($('#hiddenParentCount').val() > 0) {
$.ajax({
url: '../../Administration/UserManagement/exportUserProp',
type: 'POST',
data: 'typeToExport=PARENT',
success: function (data) {
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
}
};
And here is action controller:
[HttpPost]
public virtual void exportUserProp(string typeToExport, string validFrom = null)
{
var query = ModelPropSessions:
using (ExcelPackage pck = new ExcelPackage())
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add(string.Format("{0} - {1}", "historyData", typeToExport));
ws.Cells[1, 1].Value = "ID user";
ws.Cells[1, 2].Value = "Agent number";
ws.Cells[1, 3].Value = "Deadline type";
for (int z = 0; z < query.Count(); z++)
{
ws.Cells[z + 2, 1].Value = query[z].USERID;
ws.Cells[z + 2, 2].Value = query[z].USER_INT_NUM;
ws.Cells[z + 2, 3].Value = query[z].DESC;
}
string myFile = "FileToExport";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=" + myFile);
Response.BinaryWrite(pck.GetAsByteArray());
Response.End();
}
}
In debugger everything is cool - call comes to server side and creates excel file. But, on the client side I am receiving an error:
readyState = 4
status = OK
and for the responseText I receive some characters which I can not read. It seems that this is excel file, which should be saved. Why I can't save it
and keep getting an error response ?

Posting Image Event on javascript facebook api

Ok I'm stuck, I want to create an event in facebook, using javascript facebook api, and I want to load an image on the event cover. I can not figure out how I can do it.
I create an image in a canvas and I can upload to facebook using an sendAsBinnary function
from: https://stackoverflow.com/a/5303242/945521
And this function
Facebook.prototype.postImageToFacebook = function(authToken, filename, mimeType, imageData, message){
try {
showMessage("Creating post...");
// this is the multipart/form-data boundary we'll use
var boundary = '----------RaNdOm_crAPP' + getBoundary();
// let's encode our image file, which is contained in the var
var formData = '--' + boundary + '\r\n';
formData += 'Content-Disposition: form-data; name="source"; filename="' + filename + '"\r\n';
formData += 'Content-Type: ' + mimeType + '\r\n\r\n';
for (var i = 0; i < imageData.length; ++i)
{
formData += String.fromCharCode(imageData[ i ] & 0xff);
}
formData += '\r\n';
formData += '--' + boundary + '\r\n';
formData += 'Content-Disposition: form-data; name="message"\r\n\r\n';
formData += message + '\r\n';
formData += '--' + boundary + '--\r\n';
//var xhr = new XMLHttpRequest();
var xhr = null;
if (window.XDomainRequest) {
xhr = new XDomainRequest();
}
else if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onload = function() {
window.alert("The photo was published successfully!!");
};
showMessage("Sending request...");
xhr.open("POST", "https://graph.facebook.com/me/photos?access_token=" + authToken, true);
if (xhr.setRequestHeader)
xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
xhr.sendAsBinary(formData);
} catch (ex) {
stopWaitingSpin();
debugLog(ex);
}
};
and with this
FB.api("/me/events", "POST", {
"name": name,
"start_time": start_time,
//"end_time":end_time,
"description": description,
"location": location,
//"location_id":location_id,
"privacy_type": privacy_type
},
function(response) {
if (response && !response.error) {
var event_id = response.id;
console.log(response);
}
});
I can create a event.
But what need to call to send the image to the cover on event???
Thank's to all
Actually its nowhere mentioned in the documentation yet, but to publish a cover photo on an event you need to call \POST /{event-id} with param cover_url:
{event-id} could be obtained as a result when you created an event.
FB.api("/{event-id}", "POST", {
cover_url: {image-url}
},
function(response) {
console.log(response); // you'll get the response as 'true' or 'false'
});

Javascript: Upload image from Canvas to FB via Graph API

I am composing an image in a canvas, I get the base64 image data by using canvas.toDataURL('png') and trimming the additional information.
var dataUrl = canvas.toDataURL('png');
var escapedBase64Data = dataUrl.replace("data:image/png;base64,","");
After that I try to post to facebook using:
FB.api('/me/photos', 'post', { source:data});
Photos (https://developers.facebook.com/docs/reference/api/user/) has a source property. This is where you will place the data content (multipart/form-data) of your photo.
I convert my base64 encoded data to multipart/form-data by specifying the headers.
The result looks like this:
--0.2242348059080541
Content-Disposition: file; name="file"; filename="image.png"
Content-Type: image/png
Content-Transfer-Encoding: base64
iVBORw0KGgoAAAANSUhEUgAAAfQAAAH0CAYAAADL1t+KAAAbBElEQVR4Xu3dP4jre0LG4V2xsFVYEKy
...
QAAAABJRU5ErkJggg==
--0.2242348059080541--
After I complete the FB api call I receive the following error:
Object {message: "(#324) Requires upload file", type: "OAuthException", code: 324}
Any suggestions?
Thanks
Here a working code example :
var boundary = '----ThisIsTheBoundary1234567890';
var formData = '--' + boundary + '\r\n'
formData += 'Content-Disposition: form-data; name="source"; filename="' + filename + '"\r\n';
formData += 'Content-Type: ' + mimeType + '\r\n\r\n';
for (var i = 0; i < imageData.length; ++i)
{
formData += String.fromCharCode(imageData[ i ] & 0xff);
}
formData += '\r\n';
formData += '--' + boundary + '\r\n';
formData += 'Content-Disposition: form-data; name="message"\r\n\r\n';
formData += f.message + '\r\n'
formData += '--' + boundary + '--\r\n';
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://graph.facebook.com/me/photos?access_token=' + authToken, true);
xhr.onload = xhr.onerror = function() {
// error managment
};
xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
//Send the request
xhr.sendAsBinary(formData);
Here is an easy solution:
const dataURItoBlob = (dataURI) => {
let byteString = atob(dataURI.split(',')[1]);
let ab = new ArrayBuffer(byteString.length);
let ia = new Uint8Array(ab);
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {
type: 'image/jpeg'
});
}
const upload = async (response) => {
let canvas = document.getElementById('canvas');
let dataURL = canvas.toDataURL('image/jpeg', 1.0);
let blob = dataURItoBlob(dataURL);
let formData = new FormData();
formData.append('access_token', response.authResponse.accessToken);
formData.append('source', blob);
let responseFB = await fetch(`https://graph.facebook.com/me/photos`, {
body: formData,
method: 'post'
});
responseFB = await responseFB.json();
console.log(responseFB);
};
document.getElementById('upload').addEventListener('click', () => {
FB.login((response) => {
//TODO check if user is logged in and authorized publish_actions
upload(response);
}, {scope: 'publish_actions'})
})
Source: http://www.devils-heaven.com/facebook-javascript-sdk-photo-upload-from-canvas/

Categories