Facebook graph api Friend Invitations - php

I have managed to send and retrieve data from facebook for invitatin using
FB.ui({
method: 'apprequests',
to: sendto,
message: 'Win Mega Prizes!',
title: 'Enter in this contest!'
},
function (response) {
if (response && response.request_ids) {
var requests = response.request_ids.join(',');
alert(requests);
window.location.href = "http://www.rmyserver/index.php?invitations="+requests+"&contest_id="+c_id+"&page_id="+page_id+"&user="+from+"&g_id="+g_id+"&sendto="+sendto+"&single=1";
} else {
alert('canceled');
}
PHP
foreach($requests as $request_id) {
// Get the request details using Graph API
echo $request_content = json_decode(file_get_contents("https://graph.facebook.com/$request_id?$app_token"), TRUE);
But i want to use single user app request , as per docs i need to use TO: filed but this doesnt work, request is sent as well i get invitation id but php code used above returns false.
Am i missing something

you can try direct url example given here https://developers.facebook.com/docs/reference/dialogs/requests/#frictionless_requests
that should work fine from php

This works for me:
FB.ui({
method:'apprequests',
message:'I want you to open up your heart a little.',
to:123456798,
// filters:['app_non_users'], // commented: let users send notifications to app users too, probably a good idea to make them revisit?
data:'' // send data what you would like to track, FB will send that back in the URL for us
// #todo send google campaign parameters
});
Moreover you are doing it wrong on PHP side, you would need to redirect the user to a URL where the invitation friend selector would be displayed. There is no way in my knowledge to directly send an invitation to users using PHP.

Related

How to retrieve device registration ID by using PHP (web) to avoid MismatchSenderId?

This is my code on the app on phonegap to obtain the registration ID. The registration ID is always obtained successfully.
const push = PushNotification.init({
android: {
},
browser: {
pushServiceURL: 'http://push.api.phonegap.com/v1/push'
},
ios: {
alert: "true",
badge: "true",
sound: "true"
},
windows: {}
});
push.on('registration', function ( data ) {
recordRegistrationID( data.registrationId ); //Pseudo
});
push.on('notification', function ( data ) {
// data.message,
// data.title,
// data.count,
// data.sound,
// data.image,
// data.additionalData
});
push.on('error', (e) => {
// e.message
});
Then I try to send a push notification to that device with the stored registration ID from my PHP server (example.com) by cURLing it to Firebase Cloud Messaging API, it always returns MismatchSenderId.
{"multicast_id":6660509895358893455,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]}
I already tried to compile the .APK and run it on my mobile device. I always successfully get the token, but the message can never be sent to that registration ID retrieved by the PhoneGap app.
Doing more research, it seems like that because PhoneGap actually retrieves the registration ID but it ties to PhoneGap itself as a sender, so other senders won't work.
Am I correct to assume this? If this is the case, how can I obtain the registration ID using PHP instead of PhoneGap, for Firebase Cloud Messaging?
Thank you.
Doing more research, it seems like that because PhoneGap actually retrieves the registration ID but it ties to PhoneGap itself as a sender, so other senders won't work.
This seems like an odd behavior. The token generated is tied to an app instance and the Firebase project. Can you provide the link where this is mentioned? It doesn't make sense for the token associated to change to a different sender at all.
With that said, there is currently no way to get the registration token from your backend. As I mentioned above, the token is tied to the app instance, so it can only be generated on the client app side.

FB Messenger Bot: Webhook updates not being delivered

i am working with Facebook Checkbox Plugin everything is working fine except facebook is not sending request to my webhook url when Confirming Opt-in.
in facebook docs it is mentioned that
After the opt-in event, we will post a webhook event to your server if the checkbox state was checked. This callback has the same format as the opt-in callback, but instead of a sender field, it has an optin object with a user_ref field.
But it is not sending any data. here is my webhook code
if (!empty($_REQUEST['hub_mode']) && $_REQUEST['hub_mode'] == 'subscribe' && $_REQUEST['hub_verify_token'] == 'verificationtoken') {
echo $_REQUEST['hub_challenge'];
}
$data = file_get_contents("php://input");
$fp = file_put_contents( PROTECH_FBB_DIR.'/data.log', $data);
i have also tried hitting my webhook manually and see if it responds. and it does work perfectly normal, so it means facebook is not posting data or maybe i am doing something wrong?
Any help would be highly appreciated. thanks
I am not php developer but have implemented the same logic in javascript, node.js. I would like to share the steps in detail and also the javascript code and hope you can figure out what you can do with it to make your life better :P
As you said, you are receiving the user_ref from the api call. That's correct. Read the documentation once again they have mentioned the user_ref will be received when user check the checkbox plugin. This user_ref is set by you and every-time the page loads this user_ref must be unique then only the checkbox plugin will render, if it is not unique the plugin wont render. And here is the complete logic behind it. You generate the user_ref, when user check the checkbox, you receive this unqiue user_ref, using this user_ref you send message to the user(you can send message to user using user_ref as many time as you want but I will suggest you rather use senderId). When you send the message to user using user_ref, the webhook api will give you a response containing senderId of the user which is actually psid we normally use in our app. This is what you need to save in your db.
Now I will put my code here how I did it.
Receiving the user_ref and sending message to user:
My payload:
function sendTextMessageRef(user_ref, messageText,md) {
var messageData = {
recipient: {
user_ref: user_ref
},
message: {
text: messageText,
metadata: md
}
};
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("Successfully sent message with id %s to recipient %s",
messageId, recipientId);
} else {
console.log("Successfully called Send API for recipient %s",
recipientId);
}
} else {
console.error("Failed calling Send API", response.statusCode, response.statusMessage, body.error);
}
});
}
Now, after sending the message, I receive a response in this json format which will include the sender id of the user:
{"sender":{"id":"xxxxxxx"},"recipient":{"id":"xxxxxWhat you are looking for is this*******"},"timestamp":1504698781373,"message":{"is_echo":true,"app_id":xxxxxxxxxxxxxxx,"metadata":"INVITATION__REPLY__qwe__2017-09-05T02xo20__xxxxxxxx__063__yes","mid":"mid.$cAAGcxxxxxxxxVxuAtJ","seq":120162,"text":":)"}}
In above received json data, the recipient.id is what you are looking for.
Here To make you understand what I did in my chat bot is first user select the checkbox plugin, I receive the call on my server, if check if it contains user_ref, if yes then I send a text message to user with a custom metadata using user_ref. When user receives the message, the webhook send me a json data in the above given format. To identify for which user_ref I have received this response, I set custom metadata which is combination of some string+user_ref. Using this I identify the sender.id of the user for which I previously sent message using user_ref. The sender.id is my pageid and recipient.id the the user id which you are trying to get and using which we generally send message to the user and is also know as psid.
Hope this helps, if you still get some issue using the above mentioned solution, then do update about it :)

Getting user's birthday through Facebook API

I'm having some troubles with the Facebook API, I am requesting permission for some information of the user by Javascript:
FB.login(function (response) {
if (response.authResponse) {
// authorized
} else {
// canceled
}
}, {scope: 'email,user_birthday,user_location'});
Now I want to get the user's information (when he is authorized) by PHP:
$facebookUser = json_decode(file_get_contents('https://graph.facebook.com/' . $this->data['userid'] . '?access_token=' . $this->oathtoken . '&fields=id,name,location,gender,email,picture,birthday,link'));
All working great, except that the API is not giving the user's birthday back. Even when I set my birthday privacy settings on public it won't show up.
So:
echo $facebookUser['birthday']; // Gives an error, since this key does not exists
Does somebody have an idea how to fix this?
You are logged in on the client side but php is executed on the server side so you receive only the basic information of an user object.
If you logged in on the server side and have the permissions so you can get the birthday simply with:
echo $facebookUser['birthday'];
Most probably you didn't receive approval to request user_birthday from FB.
You can't get user_birthday unless FB reviews your FB app.
Only the following permissions may be requested without review: public_profile, user_friends and email
(See: https://developers.facebook.com/docs/facebook-login/review/what-is-login-review)
Without review you can request only age_range, but not user_birthday
FB.login(function (response) {
var user_birthday = response.user_birthday;
console.log(user_birthday);
if (response.authResponse) {
} else {
// canceled
}
}, {scope: 'email,user_birthday,user_location'});
why don't you use serverside auth if you would like get FB info in server side?
if you are ok with clientside authentication, above should work.

facebook request dialog how to get the request_ids

Say,i've an facebook application.I use facebook request dialog javascript sdk to send invite to my friend.
At my friend account,he get;s notification and clicks the invite and he give's permission for the app .here how do i get the request id.
I'm using the code that was present in fb docs but it is giving request id only in the second invite but not at first time.
Request id's are delivered as a comma delimetered array.
You must use code like this to get them:
$r = $_REQUEST['request_ids'];
$rids = explode(',',$r);
$rids will now contain an array of your request ID's.
EDIT / UPDATE:
An example of what to do on your callback:
function sendRequestToManyRecipients() {
FB.ui({method: 'apprequests',
message: 'Request'
}, requestCallback);
}
function requestCallback(response) {
top.location.href="REDIRECT_URL?req="+response.request_ids;
}
In the PHP script that it redirects to you can now request the ID's that the user has invited to your app using $_REQUEST['req']

Facebook deauthorize my app

Can I use Facebook PHP SDK to deauthorize my app for a particular user, basically I like to have a toggle so the user can link or unlink their facebook account to my site, I have the link part working, now just need the unlink part.
Thanks
Now Graph API has a way to do this: https://developers.facebook.com/docs/reference/api/user/#permissions
Delete
You can de-authorize an application entirely, or just revoke a specific permission on behalf of a user by issuing an HTTP DELETE to USER_ID/permissions or USER_ID/permissions/PERMISSION_NAME
respectively. This request must be made with a valid user access_token or an app access token for the current app.
Using the graph API, this works fine:
$ret = $this->Facebook->api('/me/permissions', 'DELETE');
Not using the currently supported Graph API: as currently setup there is no interface in the Graph API (or even the legacy APIs) to deauthorize an application. The user has to explicitly choose to do it themselves through the Facebook settings pages.
However...
The legacy REST api has http://developers.facebook.com/docs/reference/rest/auth.revokeAuthorization/, which SOUNDS like it does what you want.
Let me know if that works for you: I'm curious.
Please note Facebook in the process of deprecating the REST API, and have adding equivalent support to the Graph API User object for "auth.revokeAuthorization" method.
For delinking or deauthorization the user by making app call:
$user_id = $this->facebook->getUser();
$access_token=$this->facebook->getAccessToken();
$result = $this->facebook->api(array(
'method' => 'auth.revokeAuthorization',
'uid' =>$user_id,
'access_token'=>$access_token
));
Using the JS API an app can be deauthorized like this:
FB.api('/me/permissions', 'DELETE', function(res){
if(res === true){
console.log('app deauthorized');
}else if(res.error){
console.error(res.error.type + ': ' + res.error.message);
}else{
console.log(res);
}
});
Or delete a specific permission:
FB.api('/me/permissions/user_birthday', 'DELETE', function(res){
if(res === true){
console.log('permission removed');
}else if(res.error){
console.error(res.error.type + ': ' + res.error.message);
}else{
console.log(res);
}
});
If you go to Facebook Developer, then select your application, then under the "Advanced" menu there is a field called "Deauthorize Callback". Set this as a URL on your domain which is pinged when a user deauthorizes themselves, there is some documentation on the format of the data it requests here.

Categories