Using Facebook's Mobile Hosting API with Parse Cloud Code for App Links - javascript

I am having trouble getting App Links working with Parse.
Since my App is mobile only i wanted to use Facebook's Mobile Hosting API.
And since you need to send your Facebook App Secret with the request i wanted to do it with Parse Cloud Code.
All i coud find on the Facebook documentation was how to do it with cURL:
curl https://graph.facebook.com/app/app_link_hosts \
-F access_token="APP_ACCESS_TOKEN" \
-F name="iOS App Link Object Example" \
-F ios=' [
{
"url" : "sharesample://story/1234",
"app_store_id" : 12345,
"app_name" : "ShareSample",
}, ]' \
-F web=' {
"should_fallback" : false, }'
so this is what i came up with in cloud code
Parse.Cloud.httpRequest({
method: 'POST',
url: 'https://graph.facebook.com/app/app_link_hosts',
headers: {
'Content-Type': 'multipart/form-data'
},
body: {
access_token : "APP_ACCESS_TOKEN",
name : "iOS App Link Object Example",
ios : '[{"url" : "sharesample://story/1234","app_store_id" : 12345,"app_name" : "ShareSample",},]',
web : '{"should_fallback" : false,}'
}
the response i get is: Request failed with response code 400
now i just read that multipart/form-data is not supported withParse.Cloud.httpRequest
so is there another way to do this?
update: just found out that you can send multipart data with a Buffer,
so this is my code now
var Buffer = require('buffer').Buffer;
var access_token = new Buffer('APP_ACCESS_TOKEN','utf8');
var name = new Buffer('iOS App Link Object Example','utf8');
var ios = new Buffer('[{"url" : "sharesample://story/1234","app_store_id" : 12345,"app_name" : "ShareSample",},]','utf8');
var web = new Buffer('{"should_fallback" : false,}','utf8');
var contentBuffer = Buffer.concat([access_token, name, ios, web]);
Parse.Cloud.httpRequest({
url: 'https://graph.facebook.com/app/app_link_hosts',
method: 'POST',
headers: {
'Content-Type': 'text/html; charset=utf-8'
},
body: contentBuffer
}
however i am still getting the same result :(
update2: got it working with content type application/x-www-form-urlencoded and normal body. But i think the error was somewhere in my parameters since i tested it with curl and got the same response

It took me a few hours, but I finally got it working:
// Returns the canonical url, like https://fb.me/....
Parse.Cloud.define("createAppLink", function(request, response) {
// see https://developers.facebook.com/docs/graph-api/reference/v2.5/app/app_link_hosts
var storyId = request.params.storyId + ''; // param identifying a single "post"
var appId = 'APP_ID';
var appSec = 'APP_SECRET';
var appToken = appId + '|' + appSec; // your app token
Parse.Cloud.httpRequest({
url: 'https://graph.facebook.com/app/app_link_hosts',
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ // you need to stringify it
access_token: appToken,
name: 'LINK TO ' + storyId, // it is needed but not public
android: [{
url: 'app://story/' + storyId, // deep link url
package: 'com.package', // your package name
app_name: 'APP' // your app name
}],
web: { should_fallback: 'false' }
})
}).then(function(httpResponse) {
// We get an id, by which we can fetch
// the canonical url with a get request
var data = JSON.parse(httpResponse.text);
var id = data.id;
return Parse.Cloud.httpRequest({
url: 'https://graph.facebook.com/' + id,
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
params: {
access_token: appToken,
fields: 'canonical_url',
pretty: 'true'
}
});
}).then(function(httpResponse) {
var data = JSON.parse(httpResponse.text);
var canonicalUrl = data.canonical_url;
response.success(canonicalUrl);
}, function(error) {
response.error(error);
})
});

Related

Sending media parameter is not working while sending it to kaleyra api through code

https://developers.kaleyra.io/docs/send-a-media-template-message-through-whatsapp
I am trying to send a media to kalerays api through my code. But it is not working when I pass from code. But When I hit the API from postman then it works fine.
async whatsappAPIWithAttachment(requestBody) {
let api_key = "";
if (requestBody.campaign) {
api_key = "x";
} else {
api_key = "Y";
}
var data = qs.stringify({
from: "xyz",
to: "xyz",
type: "mediatemplate",
channel: "whatsapp",
template_name: "xyz",
params: '"name","vendor"',
lang_code: "en",
media_url: "http://www.africau.edu/images/default/sample.pdf",
});
var config: AxiosRequestConfig = {
method: "post",
url: "https://api.kaleyra.io/v1/HXIN1707222213IN/messages",
headers: {
"api-key": api_key,
"content-type": "multipart/form-data",
},
data: data,
};
let response = await axios(config);
return response.data;
}
}
It gives me an enter image description hereerror request failed with status code 400. Here I have replaced X, Y, and XYZ with actual parameters. So Inputs are correct but still get an error saying 'E413', message: 'Invalid/incorrect inputs.
As per sample request in kaleyra documentation, they have used
--header 'Content-Type: application/json'
while you are passing
"content-type": "multipart/form-data",
pls correct it and try.
how about using double quote strings for param value
params: "\"name\",\"vendor\""

Rename video with Vimeo API

I'm looking to rename my videos with the Vimeo Api and Google Apps Script. I succesfully have the API moving videos into folders (using pretty much identical syntax to below) but can't for the life of me get the renaming working. It's extremely frustrating.
Here is the reference and below is my code - it just returns the video info as if I'm not trying to change anything, even though I'm clearly using a 'PATCH' call, not a 'GET'.
Where am I meant to put the 'name' parameter??
function renameVideo(){
var newName = 'thisismynewname';
var url = 'https://api.vimeo.com/videos/_________?name=' + newName;
var options = {
'method': 'PATCH',
'muteHttpExceptions': true,
'contentType': 'application/json',
'headers': {
'Accept':'application/vnd.vimeo.*+json;version=3.4',
'Authorization': "Bearer " + token,
},
//Note that I've also tried 'name' : 'thisismynewname' here too
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(JSON.parse(response).name); //it just returns the *current* name not the new one, and doesn't change it
}
When I saw the official document of Edit a video, it seems that name is included in the request body. So how about this modification?
Modified script:
function renameVideo(){
var newName = 'thisismynewname';
var url = 'https://api.vimeo.com/videos/_________'; // Modified
var options = {
'method': 'PATCH',
'muteHttpExceptions': true,
'contentType': 'application/json',
'headers': {
'Accept':'application/vnd.vimeo.*+json;version=3.4',
'Authorization': "Bearer " + token,
},
'payload': JSON.stringify({name: newName}) // Added
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(JSON.parse(response).name);
}
The content type is application/json.
Reference:
Edit a video

How can I make a post request to wordpress from nodejs

This is what I have and it doesn't work. I need to update an acf-field at wordpres from a nodejs application:
var username = 'username';
var password = '****';
var auth = 'Basic ' + Buffer.from(username + ':' +
password).toString('base64');
var clientServerOptions = {
uri: 'http://localhost/wp-admin/admin-ajax.php',
body: JSON.stringify({action:'microserviceOnline', update : '1', field : 'wschannel_status', micro: '138'}),
method: 'POST',
headers: {
'Content-Type': 'application/json',
'accept': 'application/json',
'Authorization': auth
}
}
request(clientServerOptions, function (error, response) {
console.log(response);
});
This is what I have in my functions.php in theme folder:
function microserviceOnline() {
global $post;
// Update the field
update_field($_POST['field'], $_POST['update'], $_POST['micro']);
die(':)');
}
add_action( 'wp_ajax_nopriv_microserviceOnline', 'microserviceOnline' );
add_action( 'wp_ajax_microserviceOnline','microserviceOnline' );
You're sending JSON, but then trying to access it as though you'd sent a URI-encoded form ($_POST['field'] and such, see here). That's a bit like speaking English to a vending machine expecting you to press a button to choose your item.
Either send URI-encoded form data, or process what you receive on the server as JSON.

make folder shared google drive api v3?

I can make a folder using this code
var request = gapi.client.request({
'path': '/drive/v3/files/',
'method': 'POST',
'headers': {
'Content-Type': 'application/json'
//'Authorization': 'Bearer ' + token
},
'body':{
"name" : "copy",
"mimeType" : "application/vnd.google-apps.folder",
}
});
request.execute(function(resp) {
console.log(resp);
//document.getElementById("info").innerHTML = "Created folder: " + resp.title;
});
but I cant figure out for the life of me how to make the folder shared to all, I seen in the documentation to put type:anyone but I cant figure out how to do it in the code, thank you for your time
You create a permission for a file or folder with this REST function:
POST https://www.googleapis.com/drive/v3/files/fileId/permissions
So you can do:
var fileId = File Id;
var request = gapi.client.request({
'path': '/drive/v3/files/' + fileId + '/permissions',
'method': 'POST',
'headers': {
'Content-Type': 'application/json'
//'Authorization': 'Bearer ' + token
},
'body':{
'role': 'reader', // owner, writer, commenter
'type': 'anyone'
}
});
If it's successful, it'll give you a Permissions resource as a result:
{
kind: "drive#permission",
id: Unique identifier,
type: string,
emailAddress: string,
domain: string,
role: string,
allowFileDiscovery: boolean,
displayName: string,
photoLink: string
}
I give you links to the reference, but I haven't found any example there:
Share file/folder
Create permission
Permission resource

Angular File Upload with Parameters

I'm using Angular-file-upload to upload files to an API by doing this:
var upload = function (file) {
return $upload.upload({
url: '/api/place/logo',
data: {place_id: 1, token: <some_token>},
file: file
});
};
All the parameters seem to be correctly set. The API expects the token to be present for authentication. For some reason, the API never receives the token or the place_id posted by the client and always responds with a BadRequest.
What is the issue here?
Try this.
At angular controller:
.controller('uploadCtrl', function ($scope, FileUploader) {
$scope.uploader = new FileUploader({
url: "./api/file/upload",
formData: [
{ "data1": "value1" },
{ "data2": "value2" }
]
});
});
At server side(In FileController, method: upload):
var provider = GetMultipartProvider();
var result = await Request.Content.ReadAsMultipartAsync(provider);
var data1 = result.FormData.Get("data1");
var data2 = result.FormData.Get("data2");
Are you using Bearer token? I'm using the https://github.com/nervgh/angular-file-upload and ran into a similar problem, turns out the file post was occurring using AJAX and not the $http, so the authorisation interceptor service (which is supposed to inject the token into all outgoing traffic from my angular website) wasn't working.
Depending on how your library works, you might be running into a similar issue. If so, you have to specify the token as the 'Authorization' header, something along the lines of (where I am retrieving authData from localStorage after having been authorized previously by the token provider):
tokenHeader = 'Bearer ' + authData.token;
var uploader = $scope.uploader = new FileUploader({
headers: { "Authorization": tokenHeader },
url: _uploadUrl,
withCredentials: true
});
I do like this:
var tokenHeader = $http.defaults.headers.common.Authorization;
var uploader = $scope.uploader = new FileUploader({
url: '/api/WS_Books/PostBooks',
autoUpload: true,
headers: { "Authorization": tokenHeader },
withCredentials: true
});
you can use onBeforeUploadItem method to inject jwt token
uploader.onBeforeUploadItem = function (item) {
item.headers = {
'Authorization': 'Bearer ' + localStorage.getItem('token_name')
};
};
This here worked for me. I'm using PHP
You can send values ​​to PHP using the formData property
app.controller ('FileUploadCtrl', ['$ scope', 'FileUploader',
function ($ scope, FileUploader) {
var uploader = $ scope.uploader = new FileUploader ({
url: '.myapi / mycontrollers / myuploadfile.php',
formData: [{
data1: 'value1',
data2: 'value2',
dataN: 'valueN'
}]
});
In PHP you use $ _REQUEST to capture the information available in formData
$myValue1 = $_REQUEST ['data1'];
$myValue2 = $_REQUEST ['data2'];
$myValue3 = $_REQUEST ['dataN'];

Categories

Resources