Error when using Facebook's PHP SDK to send notification - php

I'm sending a Facebook notification using PHP but I've run into a problem I can't seem to solve with Facebook's docs.
The notification informs a person that their friend has beaten them in a game, This is the PHP code that sends the message:
<?php
require_once __DIR__ . '/facebook-sdk-v5/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => '{123456789}',
'app_secret' => '{1a2b3c4d5f6g7h8i9j}',
'default_graph_version' => 'v2.3',
]);
//This is an array of ID numbers received from an Ajax post
$data = json_decode(stripslashes($_POST['data']));
//This the ID number of the sender of the notifications
$senderid = $_POST['senderid'];
echo $senderid;
foreach($data as $d){
$request = $fb->post('/'.$d.'/notifications', array( 'template' => '#['.$senderid.'] just beat you!'), '123456789|1a2b3c4d5f6g7h8i9j');
}
?>
This code is taking an array of ID numbers ($data) and sending the notification to each one. The senderid is the ID of the sender, and according to the docs here: https://developers.facebook.com/docs/games/services/appnotifications typing something like #[12625234523] just beat you! should automatically put the name of the person who owns that ID in place, so the notification should read something like "John Doe just beat you".
But this isn't working for me. I'm certain that the sender's ID is successfully being posted to the PHP file because it's appears in the console when I echo $senderid. And when I type in the sender's ID manually into the 'template' part of the request I'm getting the same error in the console. The error is:
Fatal error: Uncaught exception 'Facebook\Exceptions\FacebookServerException' with message 'An unknown error has occurred.' in /home/mywebsite/public_html/Games/Barre/facebook-sdk-v5/Exceptions/FacebookResponseException.php:105
Stack trace:
0 /home/mywebsite/public_html/Games/Barre/facebook-sdk-v5/FacebookResponse.php(210): Facebook\Exceptions\FacebookResponseException::create(Object(Facebook\FacebookResponse))
1 /home/mywebsite/public_html/Games/Barre/facebook-sdk-v5/FacebookResponse.php(255): Facebook\FacebookResponse->makeException()
2 /home/mywebsite/public_html/Games/Barre/facebook-sdk-v5/FacebookResponse.php(82): Facebook\FacebookResponse->decodeBody()
3 /home/mywebsite/public_html/Games/Barre/facebook-sdk-v5/FacebookClient.php(225): Facebook\FacebookResponse->__construct(Object(Facebook\FacebookRequest), '{"error":{"mess...', 500, Array)
4 /home/mywebsite/public_html/Games/Barre/facebook-sdk-v5/Facebook.php(504): Facebook\FacebookClient->sendRequest(Object(Facebook\FacebookRequest))
5 /home/mywebsite/public_ht in /home/mywebsite/public_html/Games/Barre/facebook-sdk-v5/Exceptions/FacebookResponseException.php on line 105
I'm sure that the array of IDs is working correctly, as everything works perfectly when I remove the $senderid from the message template. This isn't ideal though as I would like to tell the player who has beaten them, instead of giving them a message like "You've just been beaten." I would like to include the name of the sender in the message/template but the method given in the Facebook document above isn't working, maybe it's only possible to use the #[12425232] method when typing into Facebook's Graph API Explorer?
I'd really appreciate any help anyone could give me with this problem.
Thank you in advance!

Please use GET or REQUEST instead of POST for data and senderid

Related

How can I pass a variable into a Mailchimp function as a parameter?

I feel this is a very basic question so I do apologise in advance, I have spent some hours before deciding to ask this.
In short, I am using the MailChimp API to archive/delete a user.
public function archiveClient(Request $request){
$client_email = md5(strtolower($request->client_email));
$mailchimp = new \MailchimpMarketing\ApiClient();
$mailchimp->setConfig([
'apiKey' => config('services.mailchimp.key'),
'server' => 'us14'
]);
$mailchimp->lists->deleteListMember("list_id", "<?php $client_email ?>");
}
List_id works just fine, I have used it in other functions to add subscribers. I changed it back to list_id for privacy. However the subscriber_hash parameter requires an MD5 hash of the user's email in lowercase and this is where the problem comes in. I've tried various ways but I still come to the same error:
GuzzleHttp\Exception\ClientException
Client error: DELETE
https://us14.api.mailchimp.com/3.0/lists/list_id/members/%3C%3Fphp%20d076a26e78f7e9935a3af1a8f5124b98%20%3F%3E
resulted in a 404 Not Found response:
{"type":"https://mailchimp.com/developer/marketing/docs/errors/","title":"Resource
Not Found","status":404,"detail":"The (truncated...)
The targeted email address is there on Mailchimp and comes through correctly as a string in the $request->client_email, the issue is with the hash somehow. Any help would be appreciated! Thank you!
The above suggestions by Paul T and Greg Schmidt are correct!
Parameters should be set to ("list_id", $client_email)
After this fix I received a 405 error which was truncated. I therefore used the following to find the precise error:
try {
$mailchimp->lists->deleteListMember("list_id", $client_email);
} catch (\GuzzleHttp\Exception\RequestException $ex) {
return $ex->getResponse()->getBody()->getContents();
}
The cause was that I used a contact that was 'cleaned'. After testing on a 'subscribed' member it worked just fine.

Push notification overrides previous notifications

I'm using codeigniter-gcm library on top of codeigniter to send messages to Google Cloud Messaging service. It sends the message and the message is received at the mobile device, but if I send multiple messages, only the latest message appears on the device (as if it is overriding the previous messages).
I'm seeing that I might need to create a unique notification ID, but I'm not seeing how it's done anywhere on the codeigniter-gcm documentation or Google's documentation for downstream messages.
Any idea how this should be done?
Here's my code in the codeigniter controller. It is worth mentioning that Google's response contains a different message_id for each time I send a push...
public function index() {
$this->load->library("gcm");
$this->gcm->setMessage("Test message sent on " . date("d.m.Y H:i:s"));
$this->gcm->addRecepient("*****************");
$this->gcm->setData(array(
'title' => 'my title',
'some_key' => 'some_val'
));
$this->gcm->setTtl(false);
$this->gcm->setGroup(false);
if ($this->gcm->send())
echo 'Success for all messages';
else
echo 'Some messages have errors';
print_r($this->gcm->status);
print_r($this->gcm->messagesStatuses);
}
After three exhausting days I found the solution. I'm posting it here in hope of saving someone else's time...
I had to add a parameter to the data object inside the greater JSON object, named "notId" with a unique integer value (which I chose to use a random integer from a wide range). Now why Google didn't include this in their docs? Beats me...
Here's how my JSON looks now, when it creates separate notifications instead of overriding:
{
"data": {
"some_key":"some_val",
"title":"test title",
"message":"Test message from 30.09.2015 12:57:44",
"notId":14243
},
"registration_ids":["*******"]
}
Edit:
I'm now thinking that the notId parameter is not really determined by Google, but by a plugin I use on the mobile app side.
To extend further on my environment, my mobile app is developed using Phonegap, so to get push notification I use phonegap-plugin-push which I now see in its docs that parameter name.
I'm kinda' lost now as far as explaining the situation - but happy it is no longer a problem for me :-)
You need to pass a unique ID to each notification. Once you have clicked on the notification you use that ID to remove it.
...
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotificationManager.cancel(SIMPLE_NOTFICATION_ID_A);
...
But I'm sure you shouldn't have so much of notifications for user at once. You should show a single notification that consolidates info about group of events like for example Gmail client does. Use Notification.Builder for that purpose.
NotificationCompat.Builder b = new NotificationCompat.Builder(c);
b.setNumber(g_push.Counter)
.setLargeIcon(BitmapFactory.decodeResource(c.getResources(), R.drawable.list_avatar))
.setSmallIcon(R.drawable.ic_stat_example)
.setAutoCancel(true)
.setContentTitle(pushCount > 1 ? c.getString(R.string.stat_messages_title) + pushCount : title)
.setContentText(pushCount > 1 ? push.ProfileID : mess)
.setWhen(g_push.Timestamp)
.setContentIntent(PendingIntent.getActivity(c, 0, it, PendingIntent.FLAG_UPDATE_CURRENT))
.setDeleteIntent(PendingIntent.getBroadcast(c, 0, new Intent(ACTION_CLEAR_NOTIFICATION), PendingIntent.FLAG_CANCEL_CURRENT))
.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)
.setSound(Uri.parse(prefs.getString(
SharedPreferencesID.PREFERENCE_ID_PUSH_SOUND_URI,
"android.resource://ru.mail.mailapp/raw/new_message_bells")));

Twilio Callback URL not Called - PHP & Wordpress

I'm trying to integrate Twilio onto my Wordpress site.
The idea is to allow users to type in their phone number to get a download link to our app. We've put up a simple form here - http://evntr.co/download - and upon submitting the form, the EvntrPHP.php code is run.
Using template code, we've easily been able to get the form to send a message to a verified number (the one currently in the To field) using a free Twilio number. However, when we add the StatusCallback parameter, it never calls our callback.php code. Both EvntrPHP.php and callback.php are in the root directory - evntr.co/.
<?php
require 'twiliophp/Services/Twilio.php';
$AccountSid = "--------";
$AuthToken = "---------";
$client = new Services_Twilio($AccountSid, $AuthToken);
$phonenum = $_POST["phonenum"];
$callbackURL = "https://evntr.co/callback.php";
$client->account->messages->create(array(
'To' => "XXXXXXXXXX",
'From' => "+XXXXXXXXXX",
'Body' => "Test Message",
'StatusCallback' => "https://evntr.co/callback.php",
));
?>
My understanding is that the flow should be like this:
user navigates to evntr.co/download
user submits the form with their number
form calls EvntrPHP.php and sends a text message to their number
Twilio POSTs to callback.php whenever the status of the message changes (Sent, Delivered, Canceled, etc).
However, every time I submit the form, the message is sent and the page just stays at evntr.co/EvntrPHP.php and never loads callback.php. Maybe this is a misunderstanding on my part with how Callback URLs work? Or maybe the StatusCallback parameter doesn't work with a free Twilio number?
Twilio developer evangelist here.
You are correct that the Twilio callbacks are not working as you expect. As McCann points out, the request is made asynchronously from Twilio to the URL you supply. You can use the callback to keep track of the progress of the message, but not affect the request the user has made.
So, in your example you either want to render something after you have sent the message:
<?php
require 'twiliophp/Services/Twilio.php';
// other stuff
$client->account->messages->create(array(
'To' => $phonenum,
'From' => "+14708655xxx",
'Body' => "Test Message",
'StatusCallback' => "https://evntr.co/callback.php",
));
?>
<h1>You should receive an SMS, click the link in the SMS to download the app on the platform of choice.</h1>
With some more style than a plain <h1> of course! Or, you could redirect to a page with a success message on. (PHP is not my strongest subject, but discussions of redirects are rife on this StackOverflow question)
Good luck with the app, and let me know if you have any more Twilio questions!
[edit]
As discussed in the comments, if you want to see if the API request was successful you'll want to do something like:
<?php
require 'twiliophp/Services/Twilio.php';
// other stuff
try {
$client->account->messages->create(array(
'To' => $phonenum,
'From' => "+14708655xxx",
'Body' => "Test Message",
'StatusCallback' => "https://evntr.co/callback.php",
));
// Success! Redirect to success page!
header("Location: http://evntr.co/success.php");
die();
} catch (Services_Twilio_RestException $e) {
// Something went wrong!
// Do something about it!
}
?>
So, wrapping the API call in a try/catch block and responding appropriately should catch most errors from incorrect phone numbers or other API errors. It won't guarantee that the SMS has been delivered (you'll get that from the callback webhook) but it will guarantee that you've done all you can to get the SMS sent.
The callback doesn't work like you think it does.
Call End Callback (StatusCallback) Requests
After receiving a call, requesting TwiML from your app, processing it, and finally ending the call, Twilio will make an asynchronous HTTP request to the StatusCallback URL configured for the called Twilio number (if there is one). By providing a StatusCallback URL for your Twilio number and capturing this request you can determine when a call ends and receive information about the call.
-- https://www.twilio.com/docs/api/twiml/twilio_request

can we send Facebook Notifications using app scoped user ids?

I am struggling with one problem.
I have to send notification to Facebook Users. According to >=2.0 version of Graph API, we get app scoped ids of user instead of original UIDs.
My question is: can we send notification to user using these new app scoped ids?
As i tried to send notification with app scoped ids, code failed. But When I tried same code with original user id, it worked.
Please let me know if there is any way to solve this problem.
Thanks in Advance.
Here is my code:
require_once "/facebook_api/facebook.php";
$facebook = new Facebook();
$app_id = '<app_id>';
$app_secret = '<secret_id>';
$app_access_token = $app_id . '|' . $app_secret;
$id = '<app-scoped-id>'
$response = $facebook->api( '/'. $id .'/notifications', 'POST', array(
'template' => 'You have received a new message.',
'href' => 'http://test.com',
'access_token' => $app_access_token
));
print_r($response);
die;
RESPONSE:
If is use app-scoped user id, response is:
PHP Warning: Missing argument 1 for Facebook::__construct(), called in /facebook/message.php on line 4 and defined in /facebook/facebook_api/facebook.php on line 47
PHP Notice: Undefined variable: config in /facebook_api/facebook.php on line 51
PHP Fatal error: Uncaught GraphMethodException: Unsupported post request. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api
thrown in /facebook/facebook_api/base_facebook.php on line 1283
if i use original user id, result is: Array(['success']=>1);
Currently you can use both the global ID and app scoped ID in your app. Facebook seems to have relaxed this restriction.
If your app scoped ID isn't working, file a bug.
I'm doing the same thing and it also works with real userID, but when I use app scoped id, I get this error :
(#803) Some of the aliases you requested do not exist: ...

Replying to a private message as a Facebook page

I created a tool for our support team that gets all private messages from our +/- 70 Facebook fan pages for easy processing and not having to manually click through all the pages to check if there are new or unanswered messages.
This tool worked perfectly for a couple of months but recently we've been getting the following error when trying to send a reply on a private message:
[error] => Array
(
[message] => (#504) Invalid reply thread id
[type] => OAuthException
[code] => 504
)
My code is as follows:
$fb->setAccessToken('%access_token%');
$edge = 't_id.' . $thread['id'] . '/messages';
$result = $fb->api($edge, 'POST', array('message' => $message));
I use extended access tokens but just to be sure I renewed them all. The value in $thread['id'] is the value from 'thread_id' from querying FQL 'message' table.
I searched in the Facebook docs but it looks like they removed everything concerning this subject, which could imply they removed the functionality entirely.
They say something about a new messages system which they are rolling out on the thread reference page, but I can't find anything else about this subject. https://developers.facebook.com/docs/reference/api/thread/
EDIT:
As you can see in the comments the documentation can be found here: https://developers.facebook.com/docs/graph-api/reference/page/conversations
I just made a new page for testing and I can't seem to get a valid access token in the graph api exlorer for accessing the edge /{page-id}/conversations. I remember this has happened before when I was developing my tool. The same access tokens didn't work for a week and then suddenly started working again...

Categories