Facebook messenger bot Get Started Button - javascript

I'm building my first messenger bot in js and already can receive and reply to messages and send cards with options, but I've already tried everything to setup a get started button but with no success... Here is what I have done for that:
I don't know what i'm doing wrong or where do i have to call the facebookthreadAPI function. Need advice.
Excerpt from index.js:
function facebookThreadAPI(jsonFile, cmd){
// Start the request
request({
url: 'https://graph.facebook.com/v2.6/me/thread_settings?access_token='+process.env.token,
method: 'POST',
headers: {'Content-Type': 'application/json'},
form: require(jsonFile)
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
// Print out the response body
console.log(cmd+": Updated.");
console.log(body);
} else {
// TODO: Handle errors
console.log(cmd+": Failed. Need to handle errors.");
console.log(body);
}
});}
Excerpt from fb-get-started-button.json:
{
"setting_type":"call_to_actions",
"thread_state":"new_thread",
"call_to_actions":[
{
"payload":"action?POSTBACKHERE"
}
]
}

Facebook now offers a new API for setting up the Get started button with many other features such as the greeting text and persistent menu so instead of using the old thread_setting API use the messenger profile API. For example, using curl
curl -X POST -H "Content-Type: application/json" -d '{
"get_started":{
"payload":"GET_STARTED_PAYLOAD"
}
}' "https://graph.facebook.com/v2.6/me/messenger_profile?access_token=PAGE_ACCESS_TOKEN"
Replace PAGE_ACCESS_TOKEN with your page access token and GET_STARTED_PAYLOAD with any payload you want.
See the complete tutorial here

I have the same problem. Here you can find the documentation.
I have tried to execute the example with no results.
curl -X POST -H "Content-Type: application/json" -d '{
"setting_type":"call_to_actions",
"thread_state":"new_thread",
"call_to_actions":[
{
"payload":"USER_DEFINED_PAYLOAD"
}
]
}' "https://graph.facebook.com/v2.6/me/thread_settings?access_token=PAGE_ACCESS_TOKEN"
My error is:
Requires pages_messaging permission to manage the object
But my page is not public.
Edit: You can find the solution Here. It doesn't work with the page admin

Now, with that new API, I'm trying to set GetStarted button with that request: curl -X POST -H "Content-Type: application/json" -d '{ "get_started":{
"payload":"start"}
}' "https://graph.facebook.com/v2.6/me/messenger_profile?access_token=My_Token"
and getting {"result":"success"}. But that button still doesn't appear in chat. So, I still dont understand, what's the problem here...

Related

how to put --data in GET method ? since GET not recieving body parameter

i've given the api endpoint with GET method but i think it needs a body, when i test it on postman it works fine but in react native when i try to fetch it it shows error [TypeError: Body not allowed for GET or HEAD requests]
my backend partner send this curl, how to use the --data since GET are not recieving any body
curl --request GET \
--url http://base_url/api/v2/order/all \
--header 'Content-Type: application/json' \
--cookie 'token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwaG9uZU51bWJlciI6IjA4ODc3NzA5MjIxIiwidXNlcm5hbWUiOiJGbG8iLCJpYXQiOjE2NTEwMzIxNTYsImV4cCI6MTY1MTA3NTM1Nn0.JkwTPvjig7bd8Q27MvZ7DsUCz68Qyzh3EctFTRh-m0E; connect.sid=s%253AgtaL-l_60sBGAdEhTiHspbzX3rBBiEFg.O5z0JBi7Oqo1UXSZOxQckm2FNhG3A%252BWZod951CC5Cys' \
--data '{
"userId":"79025884",
"limit":10,
"page":1
}'
this is my function
function GetActivity() {
const url = APIConfig.SERVER.ORDER + "/all";
fetch(url, {
method: "GET",
headers: { "content-type": "application/JSON" },
body: JSON.stringify({
userId: "79025884",
limit: 10,
page: 1,
}),
})
.then((response) => response.json())
.then((data) => {
console.log("GetActivity Order:", data);
setOrderList(data.data);
})
.catch((error) => {
console.error("Error:", error);
});
}
For a GET request, any parameters you want to pass to the API end point will need to be sent as part of the url I believe.
E.g. http://example.com/id/1 (where 1 is the dynamic value for the ID parameter)
I think the error you are seeing is because your trying to set a "body" value for a get request, which would be used with a POST request instead for example.
The same problem I faced several days ago, and I made some research about it. I can say that even though it is possible to use get method with body in postman you can't use get method with body with fetch or axios, because body is not allowed. And I think you should allow post method in your backend if your want to send data. You can read in depth about it here.
You need to add it to the URI or the HTTP request headers depending on the data. Usually URI path for hierarchical resource identification data and URI query for non-hierarchical. There are standard HTTP headers for many things including pagination. https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests They are for byte ranges, but you can use custom units like pages. Another way is doing pagination with URI.
GET https://example.com/api/v1/orders/by-user-id/79025884/?page=1&limit=10
GET https://example.com/api/v1/orders/by-user-id/79025884/ "Range: items=1-10"

Unable to get access token for linkedin using axios

I am trying to get access token following the steps described in Linkedin Oauth. I am trying to perform step 2 in the process to get an access token. I am using Axios for the POST request. Here is the code I am using (The client secret and id is not real for security reasons):
const axios = require('axios');
const qs = require('qs');
axios({
method: 'post',
url: 'https://www.linkedin.com/oauth/v2/accessToken',
data: qs.stringify({
grant_type: 'authorization_code',
code: 'AQSow7V6s2F2koWzIsnVKcQGt_cHtsM1F3FHZOrEV0UY1KIFkWiFJpi8dt1NtjuZMOO6-NStoCjTf58awk6GBcH2XQRctt7IBtel4Oeop5yVIBqiedk8qxlIlbkMxlfGg1gCVoupXL6xUc3-jegKYDPSe0rl4mygdpIzGdej2_hhJ827vJcojtvaMXCCGw',
redirect_uri: 'https%3A%2F%2Fwww.linkedin.com%2Fcompany%2Ftttrrr878',
client_id: '99blt2z20qlm3d',
client_secret: 'fGGgdqqcx5t3cRfw'
}),
headers: {
content-type: 'application/x-www-form-urlencoded;charset=utf-8'
}
}).then(result => {
console.log(result.data);
}).catch(error => {
console.log(error);
});
I get the following error when I run the code even after making sure that the code is not expired (before the 30 min expiration time):
data: {
error: 'invalid_redirect_uri',
error_description: 'Unable to retrieve access token: appid/redirect uri/code verifier does not match authorization code. Or authorization code expired. Or external member binding exists'
}
However when I do the same thing using curl in the command line as follows, I am able to get the access code:
curl -ik -X POST https://www.linkedin.com/oauth/v2/accessToken \
-d grant_type=authorization_code \
-d code=AQSow7V6s2F2koWzIsnVKcQGt_cHtsM1F3FHZOrEV0UY1KIFkWiFJpi8dt1NtjuZMOO6-NStoCjTf58awk6GBcH2XQRctt7IBtel4Oeop5yVIBqiedk8qxlIlbkMxlfGg1gCVoupXL6xUc3-jegKYDPSe0rl4mygdpIzGdej2_hhJ827vJcojtvaMXCCGw \
-d redirect_uri=https%3A%2F%2Fwww.linkedin.com%2Fcompany%2Ftttrrr878 \
-d client_id=99blt2z20qlm3d \
-d client_secret=fGGgdqqcx5t3cRfw
Any idea why this is happening? Is it somehow related to this
issue ?
Your code looks correct. The issue is because you are url encoding the redirect_uri parameter, remove that and it should work.
You only need to url encode the redirect_uri parameter when doing the initial request for the access code from the browser.

Need help converting cURL command to Javascipt

I am trying to get recipe nutritional information from Edamam API. In the API docs, the cURL command is:
curl -d #recipe.json -H "Content-Type: application/json" "https://api.edamam.com/api/nutrition-details?app_id=${YOUR_APP_ID}&app_key=${YOUR_APP_KEY}"
I am using Axios and Javascript to try to access the API with a Post command:
import axios from "axios";
var postData = './recipe.json'
let axiosConfig = {
headers: {
'Content-Type': 'application/json;charset=UTF-8',}
};
axios.post('https://api.edamam.com/api/nutrition-details?app_id=XXXXXXXX&app_key=XXXXXXXXXXXXXXXXXXXXX', postData, axiosConfig)
.then((res) => {
console.log("RESPONSE RECEIVED: ", res);
})
.catch((err) => {
console.log("AXIOS ERROR: ", err);
})
I receive a 400 error back. Any thoughts on what I need to do to make this work would be appreciated.
postData needs to be a string of JSON.
You appear to be passing it a string containing a filename.
You might want to read './recipe.json' with axios.get() to fetch the data from it.
In your cURL the option -d #recipe.json is sending the content of the file recipe.json
But, In your Code postData = './recipe.json', You are just passing the name instead of reading it.
First you need to read the data from recipe.json,Then you need to send it through request.

data-Binary in request nodejs

I'm trying to upload a file to dropbox throug nodeJS.
This CURL request works.
curl -X POST https://content.dropboxapi.com/2/files/upload \
--header "Authorization: Bearer myToken" \
--header "Dropbox-API-Arg: {\"path\": \"/Homework/math/Matrices.txt\",\"mode\": \"add\",\"autorename\": true,\"mute\": false}" \
--header "Content-Type: application/octet-stream" \
--data-binary #fileName
I don't know how to translate it into javascript code.
Here's what I've accomplished so far:
var request = require('request')
var headers = {
"Authorization": "Bearer " + dropboxToken,
"Dropbox-API-Arg": {
"path": "/"+fileName, //nome sul drive
"mode": "add",
"autorename": true,
"mute": false
},
"Content-Type": "application/octet-stream"
}
var options = {
url: 'https://content.dropboxapi.com/2/files/upload',
method: 'POST',
headers: headers,
}
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}
});
How do I include the data-binary option in this request in order to select the file to upload?
Thanks.
you can create a readstream and then pipe it to request with your current headers and options like-
fs.createReadStream('/path/to/youfile').pipe(request.post(options).on('end', (done) => { console.log('success') }));
First, if you're trying to integrate with the Dropbox API in JavaScript, we recommend using the official Dropbox API v2 JavaScript SDK, as it will do most of the work for you:
https://github.com/dropbox/dropbox-sdk-js
Otherwise, if you don't want to use the SDK, you can make the requests yourself. In this case, the --data-binary parameter is the curl parameter for supplying the data for the request to curl. curl then takes that data and puts it in the request body, which is the correct way to supply file data for a Dropbox API v2 "content-upload" style endpoint, such as /2/files/upload.
So, you should check the documentation for the HTTP client you're using for information on how to set the request body. It looks like you're using the request node module, which appears to take a body option, where you can put the request data.

Using React and axios for curl

Is it possible to make a curl request by using axios?
the curl string is:
curl -v 'https://developer.api.autodesk.com/authentication/v1/authenticate' --data 'client_id=1234&client_secret=1234&grant_type=client_credentials&scope=bucket:create bucket:read data:write data:read viewables:read' --header 'Content-Type: application/x-www-form-urlencoded' -k | jq '.'
I tried to do this:
getToken() {
axios.get({
url: 'https://developer.api.autodesk.com/authentication/v1/authenticate',
data: {
client_id: '1234',
client_secret: '1234',
grant_type : 'client_credentials',
scope: 'data:read data:viewables'
},
beforeSend: function(xhr) {
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
}, success: function(data){
console.log(data)
}
})
}
But with no luck - e.g. nothing happens.
I previously used the cygwin-terminal to make the curl-request and I succesfully got the response
{
"token_type": "Bearer",
"expires_in": 1799,
"access_token": "eyJhbGciOiJIUzI1NiIsImtpZCI6Imp3dF9zeW1tZXRyaWNfa2V5X2RldiJ9.eyJjbGllbnRfaWQiOiJjWTFqcm1rQXhPSVptbnNsOVhYN0puVURtVEVETGNGeCIsImV4cCI6MTQ4NzU2NzgwMSwic2NvcGUiOlsiZGF0YTpyZWFkIl0sImF1ZCI6Imh0dHBzOi8vYXV0b2Rlc2suY29tL2F1ZC9qd3RleHAzMCIsImp0aSI6InJZcEZZTURyemtMOWZ1ZFdKSVVlVkxucGNWT29BTDg0dFpKbXlmZ29ORW1MakF0YVVtWktRWU1lYUR2UGlnNGsifQ.uzNexXCeu4efGPKGGhHdKxoJDXHAzLb28B2nSjrq_ys"
}
So, is this possible with React/axios?
In addition to the question, can I pass the received token to another curl request?
Well it's not really "a curl request". It's an HTTP request. Curl is just the tool you use to do HTTP (and other) actions via the command line.
In your HTTP request, I can see you're using axios.get(), however you're trying to do a post request (you've got a data object you're trying to send). So you should be using axios.post(). It'd be best to check out the axios page to see the syntax for HTTP posts, including how to include the data and header objects in the post.
In answer to your second question, yes you can. In the .then() section of your first axios post, you can do another axios post using the response, e.g.
axios.post(
...
).then(response => {
// do another post with response.token or whatever as the data
})
...

Categories

Resources