Posting video to facebook from the browser using the graph API - javascript

I am trying to post a video from the browser to an edge sing the below code
var url = "https://graph.facebook.com/v2.5/" + this.uid + "/videos" + "?access_token=" + token;
var formData = new FormData();
formData.append("source", file);
formData.append("access_token", token);
return $.ajax({
url: url,
contentType: false,
processData: false,
type : "POST",
data: formData
})
But it gives a 400 bad request error.The response is
{
"error": {
"message": "Bad signature",
"type": "OAuthException",
"code": 1,
"fbtrace_id": "FYc5192NtSs"
}
}
Can you please tell me what am I doing wrong ?

I made the following utility function
var makeApiRequest: function(accessToken, config, successCallback, errorCallback) {
var baseUrl = 'https://graph.facebook.com/v2.5/';
// parse config and defaults
var config = config || {},
url = config.url || 'me',
data = config.data || {},
method = config.method || 'GET';
config.url = baseUrl + url + '&access_token=' + accessToken;
// make the api request
$.ajax(config)
.done(function(data) {
if (!!successCallback) {
successCallback(data);
} else {
console.log(data);
}
}
).error(function(xhr) {
errorCallback(xhr);
});
}
Which can be called like this for a video.
makeApiRequest(
'<token>',
{
url: 'me/videos',
data: {file_url:'http://example.com/path/to/file.mp4', description: 'title'},
method: 'POST'
}, successCb, errorCb);
Please ensure you use a token which was acquired using v2.5 of the API. You need publish_actions, publish_pages (for pages) permission to post
Debug your access token here

Related

Jquery REST API POST call, I'm getting 415 error?

I'm trying to translate one of my powershell scripts which makes an API call, into javascript or jquery for a chrome extension. I'm not very versed in Jquery, so I'm getting an error 415 when making a call with the below code, unsupported media type. I think I have to tell it I'm using "Content-Type","application/json"... but I'm not doing this in my powershell script untile subsequent calls after I've already gotten my token, so I'm a little confused. Why am I getting a 415 error and how do I fix it?
var token
var userName = "userID";
var passWord = "PaSSwOrD";
var tokenURL = "https://55.55.55.55/api/v1/token";
var xhr = new XMLHttpRequest();
var data =
'&grant_type=password';
'&server_host=55.55.55.55' +
'&username=' + userName +
'&password=' + passWord;
var dataFinal = encodeURI(data);
xhr.open('POST', tokenURL, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
//do something
}
}
xhr.send(data);
alert(xhr.responseText);
Try this (if we talk about jQuery):
var obj = null
$.ajax({
url: "https://55.55.55.55/api/v1/token",
method: 'POST',
async: false,
data: {
grant_type: 'password',
server_host: '55.55.55.55',
username: 'userID',
password: 'PaSSwOrD'
},
headers: {
'Content-type': 'application/x-www-form-urlencoded',
Accept:'application/json'
},
success: function(data){
obj = data // here the result
}
})
console.log(obj) // here the result because of "async: false"

Unable to call a Rest API that requires Crypto Authentication from my Client side JavaScript?

I am trying to call a Rest API (Logic Monitor API), that requires Token Authentication from the client side. But the authentication requires a signature, that is made up of Access ID, a base64 encoded HMAC signature based on the API Token access key and a Timestamp.
Ref: https://www.logicmonitor.com/support/rest-api-developers-guide/overview/using-logicmonitors-rest-api
The only example I found was in Node JS which imports modules like Crypto and request. Since I am trying to do it from the client-end, I will not be able to use Node JS. I tried using javaScript libraries like Crypto-JS CDN: https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.js", but it didn't work.
Below is my Javascript code:
var accessId = '12312312312';
var accessKey = '12324566767';
var company = 'api'
// Request Details
var httpVerb = "GET";
var epoch = (new Date).getTime();
var resourcePath = "/device/groups";
// Construct signature
var requestVars = httpVerb + epoch + resourcePath;
var hash = CryptoJS.HmacSHA256(requestVars, accessKey);
var signature = btoa(hash);
var auth = "LMv1 " + accessId + ":" + signature + ":" + epoch;
console.log(auth);
$.ajax({
url: 'https://' + company + '.logicmonitor.com/santaba/rest' + resourcePath,
headers: {
'Content-Type': 'application/json',
'Authorization': auth
},
type: "GET",
dataType: "json",
data: {},
success: function(result) {
console.log(result);
},
error: function(error) {
console.log(error);
}
});
Update 1: The Node JS example has the header set as below:
var options =
{
"method" : httpVerb,
"uri" : "https://" + company + ".logicmonitor.com/santaba/rest" + resourcePath,
"headers": {
'ContentType' : 'application/json',
'Authorization': auth //formed by the crypto authentication
}
};
// Make request
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Print out the response body
console.log(body)
}
});
But since the request package provided by node forms the API request, I am unable to figure out how can I frame the request from my client-end javascript. Note:- The access credentials can be on the client-side as this will be an inhouse application.

How to call login API and get output on command prompt in nodeJS?

In this code i am calling login API. and also using JSON to parse the data.when i am running this code on command prompt no output is there.what is wrong thing i am doing in my code and what is the right way to do that please help me.
--I supposed to see my output on command prompt--
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
var querystring = require('querystring');
var https = require('https');
var host = 'https://blahabc.com/api/login.json';
var username = 'xxxxx';
var password = '******';
var apiKey = '*****';
var sessionId = '1234567890';
function performRequest(endpoint, method, data, success) {
console.log("hello");
var dataString = JSON.stringify(data);
var headers = {};
if (method == 'POST') {
endpoint += '?' + querystring.stringify(data);
}
else {
headers = {
'Content-Type': 'application/json',
'Content-Length': dataString.length
};
}
var options = {
host: 'blahabc.com',
path: '/api/login',
method: 'POST',
// headers: headers
};
}
console.log("bye");
function login() {
performRequest('/api/login', 'POST', {
username: 'xxxxx',
password: '******',
api_key_id: '******'
},
function(data) {
console.log(data);
sessionId = data.result.id;
console.log('Logged in:', sessionId);
console.log("tring");
getCards();
});
console.log("hello");
}
function getCards() {
console.log("hello");
performRequest('/api/post_login' + deckId + '/cards', 'POST', {
session_id: '1234567890',
"_items_per_page": 100
}, function(data) {
console.log('Fetched ' + data.result.paging.total_items + ' cards');
});
}
login();
You aren't calling anything to make a request in your performRequest() function. You need to make a call to XMLHttpRequest to post the request to the server.

Want to set and get data with localstorage after google auth login

I am able to do login but I don't know how to set and get data into my localstorage, data is showing in alert.I know how to get and get result data from ajax response but did'nt understand how to do same with this below code.
function getDataProfile() {
var term = null;
// alert("getting user data="+accessToken);
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=' + accessToken,
type: 'GET',
data: term,
dataType: 'json',
error: function (jqXHR, text_status, strError) {},
success: function (data) {
var item;
alert(JSON.stringify(data));
// Save the userprofile data in your localStorage.
localStorage.gmailLogin = "true";
localStorage.gmailID = data.id;
localStorage.gmailEmail = data.email;
localStorage.gmailFirstName = data.given_name;
localStorage.gmailLastName = data.family_name;
localStorage.gmailProfilePicture = data.picture;
localStorage.gmailGender = data.gender;
$('#loginStatus').html(data.given_name);
}
});
}
var googleapi = {
authorize: function (options) {
var deferred = $.Deferred();
//Build the OAuth consent page URL
var authUrl = 'https://accounts.google.com/o/oauth2/auth?' + $.param({
client_id: options.client_id,
redirect_uri: options.redirect_uri,
response_type: 'code',
scope: options.scope
});
//Open the OAuth consent page in the InAppBrowser
var authWindow = window.open(authUrl, '_blank', 'location=no,toolbar=no');
//The recommendation is to use the redirect_uri "urn:ietf:wg:oauth:2.0:oob"
//which sets the authorization code in the browser's title. However, we can't
//access the title of the InAppBrowser.
//
//Instead, we pass a bogus redirect_uri of "http://localhost", which means the
//authorization code will get set in the url. We can access the url in the
//loadstart and loadstop events. So if we bind the loadstart event, we can
//find the authorization code and close the InAppBrowser after the user
//has granted us access to their data.
$(authWindow).on('loadstart', function (e) {
var url = e.originalEvent.url;
var code = /\?code=(.+)$/.exec(url);
var error = /\?error=(.+)$/.exec(url);
if (code || error) {
//Always close the browser when match is found
authWindow.close();
}
if (code) {
//Exchange the authorization code for an access token
$.post('https://accounts.google.com/o/oauth2/token', {
code: code[1],
client_id: options.client_id,
client_secret: options.client_secret,
redirect_uri: options.redirect_uri,
grant_type: 'authorization_code'
}).done(function (data) {
deferred.resolve(data);
changepage('#adminhome');
}).fail(function (response) {
deferred.reject(response.responseJSON);
$("#errorStatus").html('error');
});
} else if (error) {
//The user denied access to the app
// $("#mainerrorStatus").html(error);
// alert(error);
deferred.reject({
error: error[1]
});
}
});
return deferred.promise();
}
};
var accessToken;
var UserData = null;
function callGoogle() {
// alert('starting');
googleapi.authorize({
client_id: 'myid',
client_secret: 'myid',
redirect_uri: 'http://localhost',
scope: 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email'
}).done(function (data) {
accessToken = data.access_token;
// alert(accessToken);
// $loginStatus.html('Access Token: ' + data.access_token);
console.log(data.access_token);
console.log(JSON.stringify(data));
getDataProfile();
$("#accesstokenget").html('access token get');
});
}
// This function gets data of user.
function getDataProfile() {
var term = null;
// alert("getting user data="+accessToken);
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=' + accessToken,
type: 'GET',
data: term,
dataType: 'json',
error: function (jqXHR, text_status, strError) {},
success: function (data) {
var item;
alert(JSON.stringify(data));
// Save the userprofile data in your localStorage.
localStorage.gmailLogin = "true";
localStorage.gmailID = data.id;
localStorage.gmailEmail = data.email;
localStorage.gmailFirstName = data.given_name;
localStorage.gmailLastName = data.family_name;
localStorage.gmailProfilePicture = data.picture;
localStorage.gmailGender = data.gender;
$('#loginStatus').html(data.given_name);
}
});
disconnectUser();
}
function disconnectUser() {
var revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token=' + accessToken;
// Perform an asynchronous GET request.
$.ajax({
type: 'GET',
url: revokeUrl,
async: false,
contentType: "application/json",
dataType: 'jsonp',
success: function (nullResponse) {
// Do something now that user is disconnected
// The response is always undefined.
accessToken = null;
// alert(JSON.stringify(nullResponse));
console.log("-----signed out..!!----" + accessToken);
},
error: function (e) {
// Handle the error
// console.log(e);
// You could point users to manually disconnect if unsuccessful
// https://plus.google.com/apps
// alert('user diconnected<br>could not be connected');
}
});
}
This is the way to use localStorage:
// Store
localStorage.setItem("gmailLogin", "true");
// Retrieve
var isGmailLogin = localStorage.getItem("gmailLogin");

Parse webrequest to Coinbase gives 401 not authorized

I'm trying to send bitcoin through Coinbase's API, and this is my code:
// create object to send as data
var transaction = {
to : correctusermail, // "my#email.com"
amount_string : amount, // "1.00"
amount_currency_iso : currency // "EUR"
};
// get correct auth key from user
var authq = new Parse.Query(Parse.User);
authq.get(objectid, {
success: function(userObject) {
correctauth = userObject.get("provider_access_token");
console.log(correctauth);
console.log(transaction);
// send post request
// make post request
Parse.Cloud.httpRequest({
method: 'POST',
url: 'https://coinbase.com/api/v1/transactions/send_money',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: {
access_token: correctauth,
transaction: transaction
},
success: function(httpResponse) {
response.success(120);
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
response.error(111);
}
});
},
error: function(userObject, error) {
response.error(150);
}
});
As you can see I'm making sure that my correctauth var is correct by logging it, which works just fine.
All the other variables are correct, I've checked them. So what am I missing? It's probably very small.
From my understanding of the Coinbase API documentation, the access_token should always be part of the URL, e.g.
Parse.Cloud.httpRequest({
method: 'POST',
url: 'https://coinbase.com/api/v1/transactions/send_money?access_token='
+ correctauth,
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: {
transaction: transaction
},
// ... etc ...

Categories