Issue with Facebook messenger bot (welcome message and button message) - facebook

I'm facing 2 issues when developing a Facebook messenger bot, and I'm a newbie to programming.
I followed FB's tutorial to add the code - welcome message and deployed it in heroku, but my bot didn't pop up the said message.
app.post('/webhook/', function (req, res) {
let messaging_events = req.body.entry[0].messaging
for (let i = 0; i < messaging_events.length; i++) {
let event = req.body.entry[0].messaging[i]
let sender = event.sender.id
if (event.message && event.message.text) {
let text = event.message.text
if (text === 'Generic') {
sendGenericMessage(sender)
continue
}
if (text === 'button') {
sendbuttonmessage(sender)
continue
}
welcomemessage(sender)
//sendbuttonmessage(sender)
}
if (event.postback) {
let text = JSON.stringify(event.postback)
sendTextMessage(sender, "Postback received: "+text.substring(0, 200), token)
continue
}
}
res.sendStatus(200) })
function welcomemessage (sender) { let messageData = {
"setting_type":"call_to_actions", "thread_state":"new_thread", "call_to_actions":[
{
"message":{
"text":"Welcome to My Company!"
}
} ] } request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
recipient: {id:sender},
message: messageData,
} }, function(error, response, body) {
if (error) {
console.log('Error sending messages: ', error)
} else if (response.body.error) {
console.log('Error: ', response.body.error)
} }) }
How do I pop up another button when ppl clicked them? For example:
send function sendbuttonmessage(sender) after they click the web url of the button.
function sendbuttonmessage (sender) {
let messageData = {
"attachment": {
"type":"template",
"payload":{
"template_type":"button",
"text":"Welcome to Taikoo Place. How can we help?",
"buttons":[
{
"type":"web_url",
"url":"https://peterapparel.parseapp.com",
"title":"Show Website"
},
{
"type":"postback",
"title":"Service Lift Booking",
"payload":"what"
//"payload":"USER_DEFINED_PAYLOAD"
},
]
}
}
}

For the first question, you should set the welcome message buy a independent POST request as https://developers.facebook.com/docs/messenger-platform/send-api-reference#welcome_message_configuration shown because it uses different API and it should only be executed ONCE.
curl -X POST -H "Content-Type: application/json" -d '{
"setting_type":"call_to_actions",
"thread_state":"new_thread",
"call_to_actions":[
{
"message":{
"text":"Welcome to My Company!"
}
}
]
}' "https://graph.facebook.com/v2.6/<PAGE_ID>/thread_settings?access_token=<PAGE_ACCESS_TOKEN>"
For the second question, you cannot not detect when user clicks the web url of the button, because it will go to the link externally. However, you can set the message with the postback settings first, them you can process the postback when receiving the message, see how to handle postback here https://developers.facebook.com/docs/messenger-platform/quickstart
BTW also remember to set the messaging_postbacks under Subscription Fields.

Related

Payrexx integration in flutter webview

As described here https://developers.payrexx.com/docs/mobile-apps-javascript
I would like to interact with the javascript events of an iframe I want to create in the webview_flutter plugin.
The following example code is given in the official documentation
window.addEventListener('message', handleMessage(this), false);
and
function handleMessage(e) {
if (typeof e.data === 'string') {
try {
var data = JSON.parse(e.data);
} catch (e) {}
if (data && data.payrexx) {
jQuery.each(data.payrexx, function(name, value) {
switch (name) {
case 'transaction':
if (typeof value === 'object') {
if (value.status === 'confirmed') {
//handling success
} else {
//handling failure
}
}
break;
}
});
}
}
}
Do you know a way to do this? I have implemented an iframe in which there is the address of my gateway, but it is impossible to check if the payment has taken place.
Sounds good. The Payrexx iFrame sends a post message with the transaction details (including transaction status) to the parent window (e.g. your Flutter webview) after the payment (on the Payrexx result page). So you only need to add an event listener for type "message" in your webview as in the example:
window.addEventListener('message', handleMessage(this), false);
Please make sure you also send a post message into the Payrexx iFrame as soon as the iFrame is loaded (onload event):
let iFrame = document.getElementById('IFRAME-ID');
if (iFrame) {
iFrame.contentWindow.postMessage(
JSON.stringify({
origin: window.location.origin,
}),
iFrame.src,
);
}
Now you are ready to receive and handle the messages from the Payrexx iFrame:
private handleMessage(e): void {
try {
let message = JSON.parse(e.data);
if (typeof message !== 'object' ||
!message.payrexx ||
!message.payrexx.transaction) {
return;
}
let transaction = message.payrexx.transaction;
console.log(transaction);
} catch (e) {
}
};
Last but not least:
Make sure you also check the transaction status via transaction webhook (server-to-server notification):
https://docs.payrexx.com/developer/guides/webhook

React-native Log in with Facebook App refreshes app

I am using react-native-fbsdk and am on IOS. When users log in with Facebook their are two buttons they can press. Log in with the Facebook App or Log in with Phone Number or Email Address. Logging in with the Phone Number or email address works perfectly, I get the user object and create a user account for them. But when users press Log in with the Facebook App I don't get sent a user object, and the whole app refreshes where they get pushed to the log in page and the Facebook button has turned to Log out. I am not too sure on how to approach this as when users log in with the Facebook App none of my console.logs or alerts are getting called and the whole app just refreshes. Any help would be very much appreciated.
<LoginButton
readPermissions={["email","public_profile"]}
onLoginFinished={
(error, result) => {
console.log("onLoginFinished: ", result);
if (error) {
console.log("login has error: ", result.error);
} else if (result.isCancelled) {
console.log("login is cancelled.");
} else {
AccessToken.getCurrentAccessToken().then(
(data) => {
let accessToken = data.accessToken
console.log("accessToken.toString(): ", accessToken.toString())
const responseInfoCallback = (error, result) => {
if (error) {
console.log('Error fetching data: ', error)
//lert('Error fetching data: ' + error.toString());
} else {
console.log("responseInfoCallback:", result)
this.state.fbobj = result;
this.sendAjax();
//alert('Success fetching data: ' + result.toString());
}
}
const infoRequest = new GraphRequest(
'/me',
{
accessToken: accessToken,
parameters: {
fields: {
string: 'email,name'
}
}
},
responseInfoCallback
);
// Start the graph request.
new GraphRequestManager().addRequest(infoRequest).start()
}
)
}
}
}
onLogoutFinished={() => console.log("Logout")}
In your button action, you will need something like this:
import { LoginManager, AccessToken } from 'react-native-fbsdk'
handlePressFacebookLogin = () => {
LoginManager.logInWithReadPermissions(['public_profile', 'email']).then(
(result) => {
if (!result.isCancelled) {
AccessToken.getCurrentAccessToken().then((data) => {
console.log(data)
})
}
}
)
}

Loopback remoteMethod with onesignal push notification

i still learn, and trying to be learn. im looking for trying hard remote method on loopback 3 for push notification to specific user with onesignal.
any wrong in my code ?
because always :
Error: [ 'All included players are not subscribed' ]
My Case :
im using ionic 3 framework
loopback 3 (or latest)
2 User, (Customer & Seller)
Customer buying product from thread's seller.
If success to order, the seller will receive the notification.
and This is My code :
Ajiorder.observe('after save', function (ctx, next) {
console.log('Order', ctx.instance);
let postingModel = app.models.AjiPosting;
let userAuth = app.models.AjiUserAuth;
postingModel.find({
where:
{ id: ctx.instance.id }
}, function (err, success) {
console.log(success, 'SUKSES');
if (ctx.instance) {
let dataFilter = [];
dataFilter.push({
'field': 'tag',
'key': 'id',
'relation': '=',
'value': success[0].id
});
console.log(success[0].idSeller, 'ID TOT')
console.log(dataFilter, 'dataFilter');
let data = {
idSeller: ctx.instance.idSeller
}
console.log(data, 'Data');
userAuth.find({
where:
{ id: ctx.instance.idCustomer }
}, function (err, result) {
console.log(result, 'Data Personal');
let content = result[0].namaLengkap + ' ' + 'Order your product';
console.log(content, 'Nama Order');
console.log(ctx.instance.idSeller, 'My Dream', success[0].id);
if (ctx.instance.id != success[0].id) {
console.log('Spirit');
sendMessage(dataFilter, content, data);
}
})
}
next();
});
});
var sendMessage = function (device, message, data) {
var restKey = 'XXXXXXXXXXXXXXXXXX';
var appID = 'XXXXXXXXXXXXXXXXX';
request(
{
method: 'POST',
uri: 'https://onesignal.com/api/v1/notifications',
headers: {
'authorization': 'Basic ' + restKey,
'content-type': 'application/json'
},
json: true,
body: {
'app_id': appID,
'filters': device,
'data': data,
'contents': { en: message }
}
},
function (error, response, body) {
try {
if (!body.errors) {
console.log(body);
} else {
console.error('Error:', body.errors);
}
} catch (err) {
console.log(err);
}
}
)
}
};
and i got this error :
Error: [ 'All included players are not subscribed' ]
Picture : Picture of Console Log Here
any one can help me ?
sorry for my english too bad.
Greetings
Solved !
I'm Forget to add some code from onesignal. thanks

How to retrieve `custom_disclaimer_responses` in Facebook lead gen webhook data

I have set up a webhook that gets data submitted from a lead gen ad on Facebook.
In my response I have access to field_data and can see names and email address coming through but can't seem to find where the custom_disclaimer_responses is.
I am using the graph API explorer to send test submissions and getting a successful response
My webhook code is as follows:
exports.webhook = function (req, res, next) {
var lead = req.body.entry[0].changes[0].value;
var leadID = lead.leadgen_id;
var formID = lead.form_id;
var customDisclaimerResponses = lead.custom_disclaimer_responses
fs.readFile(config.token, 'utf8', function(err, data) {
if (err) {
console.log('err', err)
throw err;
}
var content = JSON.parse(data);
if(!content.access_token) {
console.log('Facebook Access Token is invalid.');
res.sendStatus(400);
} else {
FB.options({accessToken: content.access_token});
FB.api('/' + leadID, function (response) {
if(response && response.error) {
console.log('error', response.error);
res.sendStatus(400);
} else {
var fields = response.field_data;
// do stuff here with fields
// Response moved to outside of above function block since Facebook will
// stop sending updates if the webhook starts giving errors repeatedly.
res.sendStatus(200);
}
});
}
});
}
Example of response:
{ created_time: '2016-11-17T09:52:44+0000',
id: '<id>',
field_data:
[ { name: 'email', values: [Object] },
{ name: 'first_name', values: [Object] },
{ name: 'last_name', values: [Object] },
{ name: 'city', values: [Object] },
{ name: 'date_of_birth', values: [Object] }
]
}
I don't use webhooks, but I think this can help you:
You can add the parameter fields=custom_disclaimer_responses to get the data you need.
I re-join collected data (the ones in field_data got without parameter) by user id
This is my PHP code, for example:
$url = "https://graph.facebook.com/v2.9/$leadForm/leads?access_token=".$appToken;
$urlCustom = "https://graph.facebook.com/v2.9/$leadForm/leads?fields=custom_disclaimer_responses&access_token=".$appToken;

Facebook messenger api - Metadata on the message is not coming back in the response

I have following code to send text message with metadata. When user responds with text, metadata field on the message is empty. Is it a bug or Messenger api does not support this functionality?
function sendTextMessage(recipientId, messageText, metadata) {
var messageData = {
recipient: {
id: recipientId
},
message: {
text: messageText,
metadata: metadata,
}
};
callSendAPI(messageData);
}
function callSendAPI(messageData) {
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: { access_token: PAGE_ACCESS_TOKEN },
method: 'POST',
json: messageData
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
var recipientId = body.recipient_id;
var messageId = body.message_id;
if (messageId) {
console.log("FBHook Successfully sent message with id %s to recipient %s",
messageId, recipientId);
} else {
console.log("FBHook Successfully called Send API for recipient %s",
recipientId);
}
} else {
console.error(response.error);
}
});
}
This is not how it is expected to behave. The metadata field will be returned to webhook immediately if subscribed to the "message_echoes" field. This is meant for co-ordination between multiple apps linked to the page.
From the changelog - https://developers.facebook.com/docs/messenger-platform/changelog
"New field: metadata, passed from the Send API and sent to the message_echoes callback, to help interoperability betwen multiple bots."