Problems with facebook app's web-hook [duplicate] - facebook

I am trying to install a webhook for leadgen event for my page via a facebook app. So I have:
Facebook Page where leads come from
Facebook App
Webserver where I want to save leads
App and webserver are connected well I believe. Webhook is shown at app page etc. But when I am trying to create a test lead with this tool https://developers.facebook.com/tools/lead-ads-testing I am getting a POST request with no data in it.
I was suspecting permissions problems, but I am able to check a lead from page (via leadgen_id) directly with PHP SDK and the POST request is sent from Facebook just by URL, so they don't know about tokens yet.
UPD Plain POST request to the same url (curl -d "param=value" https://..url..) works as expected.

Facebook sends webhook data as Content-Type: application/json, not as …: application/x-www-form-urlencoded (as a normal form with method=post would.)
Therefor, PHP does not populate $_POST – you need to read the raw input stream instead. That can be done using file_get_contents('php://input') – and then just apply json_decode on that data, and you’ll have a proper data structure to work with.

Facebook sends the leads data in the request body. If you are using a framework, please check if you have access to the request body.
Try using a third party intermediate service like Runscope to see the full request, it is very usef

This code works for me...
if (!empty($_REQUEST['hub_mode']) && $_REQUEST['hub_mode'] == 'subscribe' && $_REQUEST['hub_verify_token'] == "<mytoken>") {
echo $_REQUEST['hub_challenge'];
} else {
$data = json_decode(file_get_contents("php://input"), true);
file_put_contents('logFB.txt', print_r($data, true));
}
First part is for verifying webhook, second for getting data from facebook webhook.
Hope this will help...

In case you are using the django framework, you should request.body, as post data will remain empty.
def webhook_response(request):
# it will print the contents from facebook webhook response
print(request.body)
# something like the following object will print up if you are using leadgen
{"object": "page", "entry": [{"id": "0", "time": 111111111, "changes": [{"field": "leadgen", "value": {"ad_id": "444444444", "form_id": "444444444444", "leadgen_id": "444444444444", "created_time": 11111111, "page_id": "444444444444", "adgroup_id": "44444444444"}}]}]}

Related

What is https://i.instagram.com/api/v1

I am digging into Instagram APIs and find out a URL https://i.instagram.com/api/v1 which used by many git repos(some are recently updated) but when I go to Instagram there is no such url available there. Can anyone guide me what is the use of this url and how I can use it because when I hit
https://i.instagram.com/api/v1/accounts/login/
by POSTMAN i got below message
{
"message": "Your version of Instagram is out of date. Please upgrade your app to log in to Instagram.",
"status": "fail",
"error_type": "needs_upgrade"
}
One more thing. I am with my friend who work in android he has done reverse engineering on a app which use for increase followers and that app is also using same endpoints and working on that app.
It's November 2021, and somehow the API https://i.instagram.com/api/v1 still works, but I believe they have changed the way you use it.
NOTE: The given information is just for educational purposes
Let's take the user/{user_id}/info endpoint of this API, which returns basic information about the user_id.
The URL with this endpoint would be
https://i.instagram.com/api/v1/users/176702683/info/
If you paste this link into your browser you'll get the following message
{"message":"useragent mismatch","status":"fail"}
This means that API must be called via mobile user-agent. read more about user-agent here
We can solve this problem by providing a mobile user-agent string.
Using python requests library
!pip install requests
import requests
URL = https://i.instagram.com/api/v1/users/176702683/info/
headers = {'User-Agent':'Instagram 76.0.0.15.395 Android (24/7.0; 640dpi; 1440x2560; samsung; SM-G930F; herolte; samsungexynos8890; en_US; 138226743)'}
# samsung mobile user-agent
response = requests.get(url, headers=headers)
print(response.json())
Output:
{
"user": {
"username": "marcelotwelve",
"pk": 176702683,
"profile_pic_url": "https://instagram.fzrh3-1.fna.fbcdn.net/v/t51.2885-19/233796637_544571223333074_8761964745157634211_n.jpg?stp=dst-jpg_s150x150\\u0026_nc_ht=instagram.fzrh3-1.fna.fbcdn.net\\u0026_nc_cat=1\\u0026_nc_ohc=Cfk2kHCxgbIAX_vgNjn\\u0026edm=AEF8tYYBAAAA\\u0026ccb=7-5\\u0026oh=00_AT-tuXbAbsIkvmJqm_akQS__UPDtEXZxZChx2lO-9Wb0FQ\\u0026oe=62A8115E\\u0026_nc_sid=a9513d"
},
"status": "ok"
}
NOTE: Please be aware of how you use it
It is actually an API, that you can only use from your phone application, thats why it say it needs upgrade. you can download an addon for chrome / firefox to switch user agents, and after that you will be able to see the content.
It's worth checking there is lots of info about any user on insa
this response is a default error caused by having no cookie set
inspect instagram, you can see a redirect first (this way they fill initial cookies set for you). copy paste it to postman and try again

Facebook Messenger webhook setup, but not triggered

So I'm trying to setup a bot for the new Facebook Messenger API.
I'm following the quickstart.
I setup the webhook ok, and see it in my webhooks,
I called this:
https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=%3Ctoken%3E
and it did not throw any errors,
But when I go to the Page that I generated the access token on, and send a message, it does not call my webhook.
I check the httpaccess, and it does not call it.
Any way to debug this or any ideas?
Also, one thing I'm still puzzled over is how to support managing multiple pages from one Facebook app? Anyone know the answer to this, or do you need to create anew app and get permission for every page?
I have recently worked with the new chat bot API and there's a lot that can go wrong. So, here are some Ideas.
Make sure you've verified your webhook under the product settings tab.
subscribe your app to the page using your page access token. It returns {"success" : "true"} if everything goes right.
Important
Make sure the Facebook user from which you're sending the message is listed as the Admin or Developer or Tester in your app roles (https://developers.facebook.com/apps/YOUR_APP_ID/roles/). Messages from other users won't work unless your app is approved and publicly released.
Have you received any call back from the facebook api ? or is it just the messages? Take a look at the logs of your web server and check if you're getting any hits on the webhook. Also check the error logs.
Try hitting your webhook manually and see if it responds. You can use
curl to generate a manual request. This is what the request from
Facebook looks like:
Command:
curl -i -X POST -H 'Content-Type: application/json' -d '{"object":"page","entry":[{"id":43674671559,"time":1460620433256,"messaging":[{"sender":{"id":123456789},"recipient":{"id":987654321},"timestamp":1460620433123,"message":{"mid":"mid.1460620432888:f8e3412003d2d1cd93","seq":12604,"text":"Testing Chat Bot .."}}]}]}' https://www.YOUR_WEBHOOK_URL_HERE
So my issue was I was calling GET when trying to subscribe instead of POST
https://graph.facebook.com/v2.6/:pageid/subscribed_apps?access_token=:token
GET will return the current subscriptions (empty {[]}), POST returns {"success" : "true"}
Some other gotchas I hit were,
the examples use https://graph.facebook.com/v2.6/me/.. but I seemed to need to use, https://graph.facebook.com/v2.6/:pageid
the access token is the messenger access token, not your API access token
if your webhook throws a error, Facebook will stop sending you messages for a while
One thing I'm still puzzled over is how to support managing multiple pages from one Facebook app? Anyone know the answer to this, or do you need to create anew app and get permission for every page?
Another thing which can prevent some responses from being sent to your webhook is when a message type gets blocked in a queue.
If a particular message type is delivered to your webhook but doesn't receive it's 200 response within 20 seconds it will keep trying to send you that message again for hours.
What's more facebook messenger will stop sending you any more of that message type until the first one has been acknowledged. It essentially puts them into a queue.
In the meantime, other message types will continue to send fine.
This happened to me when I accidentally introduced an undeclared variable inside my code which handled standard messages. It meant that postback messages all worked fine, but quick replies and normal messages would never get sent to my webhook. As soon as you fix the error, they all come piling through at once.
As mentioned by others, using a service such as POSTMAN to send messages to your webhook is a great way to find this kind of errors, otherwise, messenger just fails silently.
Exluding of your bot rout from CSRF verification can help if you use framework. This helps for me (Laravel 5.4, app/Http/Middleware/VerifyCsrfToken.php):
protected $except = [
'/your_bot_route'
];
I too had the same issue when I was working on a bot couple of days ago. Followed this gist and modified the code as below, and everything is working fine.
public function index()
{
$challenge = $_REQUEST['hub_challenge'];
$verify_token = $_REQUEST['hub_verify_token'];
// Set this Verify Token Value on your Facebook App
if ($verify_token === 'MyVerifyToken!') {
echo $challenge;
}
$input = json_decode(file_get_contents('php://input'), true);
// Get the Senders Graph ID
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
// Get the returned message
$message = $input['entry'][0]['messaging'][0]['message']['text'];
//$senderName = $input['entry'][0]['messaging'][0]['sender']['name'];
$reply="Sorry, I don't understand you";
switch($message)
{
case 'hello':
$reply = "Hello, Greetings from MyApp.";
break;
case 'pricing':
$reply = "Sample reply for pricing";
break;
case 'contact':
$reply = "Sample reply for contact query";
break;
case 'webinar':
$reply = "Sample reply for webinar";
break;
case 'support':
$reply = "sample reply for support";
break;
default:
$reply="Sorry, I don't understand you";
}
//API Url and Access Token, generate this token value on your Facebook App Page
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token=MYACCESSTOKEN';
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = '{
"recipient":{
"id":"' . $sender . '"
},
"message":{
"text":"'.$reply.'"
}
}';
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request but first check if the message is not empty.
if (!empty($input['entry'][0]['messaging'][0]['message'])) {
$result = curl_exec($ch);
}
}
Note : Ensure the user roles within the application page to get the responses from the web hook. I have set Administrator, and Tester user. Only there were able to get the responses. Other users will get once this is published. Also, change verify token, and page token accordingly.
There is an option that is asked while publishing the app about the number of business this bot going to be used by. But I have no idea how to use it. Still searching that though.
If you still can not solve your problem, try to check and update your Privacy policy link.
I updated worry link to Privacy policy, and Facebook show 404 error even the webhoob is verified...
You can link multiple pages to your app, under Add or Remove Pages tab in your Messenger Settings

Facebook Realtime Updates for Payments callback POST received but still having issues

I am using Facebook payments and Realtime Updates for Payments. Here is a typical payment callback from Facebook servers when someone buys/refunds something:
{
"object": "payments",
"entry": [
{
"id": "296989303750203",
"time": 1347996346,
"changed_fields": [
"actions"
]
}
]
}
I am using PHP to get this like this:
$updates = json_decode(file_get_contents("php://input"), true);
It works ok and I got the id stored in $myid. My problem is:
In the same PHP page I try to get details of this ID but it doesn't work:
$getDetails = json_decode(file_get_contents('https://graph.facebook.com/'.$myid.'?access_token='.$app_token));
The response is empty, nothing there. I even tried to get the user with this $user = $facebook->getUser(); in this PHP but it returned with zero. I suspect that since this PHP is run from the Facebook server (and not the client browser) Facebook does not know who the user is and that is why the Graph API does not work.
How can this PHP page knows who the user is? Cookies and sessions cannot be used since they will never communicate with the client browser. Help is needed. Thanks.

Error with Twitter link

Yesterday I started a new app on Facebook. Today I got the message that when people copy the link to Twitter they get an error. This is what you get:
{
"error": {
"message": "Unknown path components: /your_namespace:your_action",
"type": "OAuthException",
"code": 2500
}
}
What does this mean? What could be the problem?
Are you actually sending the POST action link to Twitter? Why?
I think you misunderstood how Open Graph works. Basically, you should be the one publishing actions when users take an action using your service. You can use a server-side or a client-side language to POST request (when you click a link, your browser actually makes a GET request, not a POST) to https://graph.facebook.com/me/namespace:action?access_token=ACCESS_TOKEN&OBJECT_PATH=OBJECT_URL
Note that you need to create an app, use it to authenticate users to get the access token and also set your custom actions / objects. These will need to be approved before you can actually use them.
You should start by taking a look at the sample apps to see how they work: https://developers.facebook.com/docs/samples/

Bad Request/Method not Implemented Error when Publishing Actions to the Timeline

I am working on a Joomla site and using myApi to handle most facebook integrations. The like button is working fine and picking up information from the og meta tags inserted by myApi.
On the website, the user can login using facebook - I have added the publish_actions permission to the myApi code, and I know this is being requested because when authorising the app, the oauth dialog says that actions like ordering from restaurants (the action i added to my fb app) will be posted to the timeline.
now, while ordering, I check whether the user has an entry in the myApi user table and if so, I provide a checkbox that lets the customer choose whether she wants the order action posted to her timeline. if ticked, I then use curl to try and post the order action to facebook. I have been using my account to test - I have authorised the app with all permissions requested. I use the myApi interface to get my user access token. I am adding the access_token and object url to the url as querystring parameters and then posting to it through curl.
The curl response I get is:
<HTML><HEAD>
<TITLE>400 Bad Request</TITLE>
</HEAD><BODY>
<H1>Method Not Implemented</H1>
Invalid method in request<P>
</BODY></HTML>
the response I get when going to the generated url in my browser is
{
"data": [
],
"paging":{
"next": "https://graph.facebook.com/me/og_collegekhana:order_from?restaurant=http\u00253A\u00252F\u00252Fwww.collegekhana.com\u00252Fstates\u00252Ftamil-nadu\u00252Fcampus-1\u00252Feat-1&access_token=[the token I got]&offset=25&limit=25"
}
}
I checked the object id of the url using
https://graph.facebook.com/?ids=http://www.collegekhana.com/states/tamil-nadu/campus-1/eat-1
I am not getting an object id. instead I get
{
"http://www.collegekhana.com/states/tamil-nadu/campus-1/eat-1": {
"id": "http://www.collegekhana.com/states/tamil-nadu/campus-1/eat-1"
}
}
I am completely lost and hope someone can tell me what I am doing wrong.
The problem was that instead of doing a cURL POST, one has to add the querystring parameter
method=post to the URL.