$usersStmt = self::$db->query("SELECT `token` FROM `tokens`");
$users = $usersStmt->fetchAll(PDO::FETCH_COLUMN);
foreach ($users AS $userToken) {
$apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $userToken)) . chr(0) . chr(strlen($payload)) . $payload;
$result = fwrite($fp, $apnsMessage);
}
I have a table with 10 push notification tokens inside of it. Using PHP, I fetch these tokens and send a notification for each token to APNS.
The problem is, only half are actually getting the notifications. I have a feeling that this is because one of the tokens is invalid (or something along those lines) and it is stopping it from sending the rest of the tokens.
I have checked the value of $result and each one returns true. This means that all notifications are being successfully sent to APNS but not delivered to all devices.
Is it possible that an invalid token could disrupt the rest of the notifications from reaching devices? I'm not sure what's going on here but I know all the notifications are sent successfully to APNS but not reaching the devices.
Any ideas?
Invalid tokens will not disrupt the rest of the notifications from reaching devices.
I have the same issue before, the problem was with messages sent itself.
Check your messages length, the notification payload is 256 bytes ).
Check your messages encoding, use the escape sequence for none ASCII messages.
If you send to same device multiple times, Apple will send the last notification only.
Make sure your tokens is for the same working environment, sandbox tokens will not work with production server.
Check Apple technical notes for more info:
https://developer.apple.com/library/mac/technotes/tn2265/_index.html#//apple_ref/doc/uid/DTS40010376-CH1-TNTAG23
As stated in the Apple Documentation:
"Remember that delivery of notifications is “best effort” and is not guaranteed."
(Linked relevant question with the same answer - thanks to Joe)
Are APNS now guaranteed delivery given that passbook passes are guaranteed
The current adoption rate of iOS 7 to iOS 8 is 50/50. Have you made sure your apps register separately for each OS in your didFinishLaunching call in the AppDelegate? Does the data suggest it's working for one OS and not the other? example code in App Delegate:
if(iOS8){
[self.application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[self.application registerForRemoteNotifications];
NSLog(#"Register for iOS 8 Notifications %#", application);
}else{
// iOS 7 Notifications
[self.application registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound)];
NSLog(#"Register for iOS 7 Notifications %#", application);
}
Related
I was looking for a way to send notifications directly to the customer phone number using the Whatsapp API
I found an article on a site that explains in detail how to activate and use the Whatsapp API.
Add the phone number +34 644 76 66 43 into your Phone Contacts. (Name it it as you wish)
Send this message "I allow callmebot to send me messages" to the new Contact created (using WhatsApp of course)
Wait until you receive the message "API Activated for your phone number. Your APIKEY is 123123" from the bot.
Note: If you don't receive the ApiKey in 2 minutes, please try again after 24hs.
The WhatsApp message from the bot will contain the apikey needed to send messages using the API.
You can send text messages using the API after receiving the confirmation.
Perfect receipt apikey
How to send WhatsApp Messages from PHP using CURL Library
It is very simple to send WhatsApp messages from PHP using the cURL Library. I would recommend to create a function and then call to the function every time that you want to send a message.
First, create the function "send_whatsapp" in your php code as follow:
function send_whatsapp($message="Test"){
$phone="NUMBER"; // Enter your phone number here
$apikey="YOUR_API_KEY"; // Enter your personal apikey received in step 3 above
$url='https://api.callmebot.com/whatsapp.php?source=php&phone='.$phone.'&text='.urlencode($message).'&apikey='.$apikey;
if($ch = curl_init($url))
{
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
$html = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// echo "Output:".$html; // you can print the output for troubleshooting
curl_close($ch);
return (int) $status;
}
else
{
return false;
}
}
Just update the $phone and $apikey variable with the ones that you obtained during the step 3 above.
And then call to the function from any place in your code.
send_whatsapp("this is a test from PHP"); //Text message that your would like to send
You can call to the send_whatsapp function from different places in your code.
QUESTION
Perfect this will send me a message every time to the number I specified to activate the notification system.
But what if I want to send it not to my number but to the customer number?
I believe you're missing two concepts here. If you want to send messages from your personal phone number, you need to host & run your own solution (I don't think you'd like to allow anybody else out there to get all your stuff).
If you are asking for a service provider to set up a number for you and offer you a gateway service for that purpose, there are several alternatives out there. Google them. You'll find two options; Facebook/Whatsapp API connected providers and 'free riders' that will set that up for you at a cost.
The solution you mention is called call me bot and it is just to send self notifications and not for sending out messages to third parties. I am hosting a similar solution (https://github.com/inUtil-info/whin-use-cases) but is the same situation. To prevent span, you are not allowed to send messages to anyone but you.
We have an application built in PHP that sends out push notifications to both Android and iOS. Our problem is there are some device ids for iOS that seem to completely halt the sending of the all other iOS push notifications in our script, they even say that they have been sent without errors but it stops all notifications in the loop afterwards.
If we then remove the offending device id from our database the sending script works for all devices after the offending device. It is very strange and cant seem to figure out why.
Does anyone have any experience with this? Is it to do with sending to a device ID that doesnt exist anymore will stop apple from completing our script on that specific connection?
Here is our sending script in PHP (this works for all devices apart from the odd rogue device id):
$tHost = 'gateway.push.apple.com';
$tPort = 2195;
$tCert = "path_to_our_cert.pem";
$tPassphrase = 'passphrase';
$tAlert = $this->title; //assign a title
$tBadge = 8;
$tSound = 'default';
$tPayload = $this->body_plain; //assign a body
// Create the message content that is to be sent to the device.
$tBody['aps'] = array ('alert' => $tAlert,'badge' => $tBadge,'sound' => $tSound,);
$tBody ['payload'] = $tPayload;
$tBody = json_encode ($tBody);
$tContext = stream_context_create ();
stream_context_set_option ($tContext, 'ssl', 'local_cert', $tCert);
stream_context_set_option ($tContext, 'ssl', 'passphrase', $tPassphrase);
$tSocket = stream_socket_client ('ssl://'.$tHost.':'.$tPort, $error, $errstr, 30, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $tContext);
if (!$tSocket) exit ("APNS Connection Failed: $error $errstr" . PHP_EOL);
//Loop through all devices to send
foreach($this->device->devices as $item){
if($item->os != "iOS") continue;
if(session::getAdministratorStaffSchoolID() != $item->school_id) continue;
$tToken = $item->device_id;//assign the device id
$tMsg = chr (0) . chr (0) . chr (32) . pack ('H*', $tToken) . pack ('n', strlen ($tBody)) . $tBody;
$tResult = fwrite ($tSocket, $tMsg, strlen ($tMsg));
}
fclose ($tSocket);
Does anyone have any ideas regarding this?
Many thanks
So, just a thought, but you're using the legacy format to send the notification:
$tMsg = chr (0) . chr (0) . chr (32) . pack ('H*', $tToken) . pack ('n', strlen ($tBody)) . $tBody;
And:
Error response. With the legacy format, if you send a notification
packet that is malformed in some way—for example, the payload exceeds
the stipulated limit—APNs responds by severing the connection. It
gives no indication why it rejected the notification. The enhanced
format lets a provider tag a notification with an arbitrary
identifier. If there is an error, APNs returns a packet that
associates an error code with the identifier. This response enables
the provider to locate and correct the malformed notification.
https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Appendixes/LegacyFormat.html
So maybe APNS is just dropping the connection on you? That's why all the remaining notifications actually don't get through. Take a closer look at those payloads. And might be a good time to move to the new format.
AFAIK APNs will close the connection as soon as any error occurs (invalid device token, malformed payload, etc.). Your code that sends out Push needs to be prepared to recover from this situation, reconnect and then restart the work.
Take a look at the 3rdParty libraries out there to execute this job for you. You'll rely on the community work.
I can referral Pushy which is written in Java. I have used it in 2 different projects and I can say it works fine and it's an very active project (a lot of discussions and updates there).
I don't know any of them using PHP, but probably there is one
I am trying to send push notification to a bunch of iPads and tested it first with the device I have. It worked just fine. Then I tried to expand it to include multiple devices, including my own, and it doesn't seem to work (checked with other relevant device holders just to make sure). The device token information appears to be just fine. What could be wrong? Maybe it's a throttling issue?
I tried to rewrite everything from the following tutorial and the issue is still the same:
http://learn-php-by-example.blogspot.co.il/2013/01/working-with-apple-push-notification.html
I get no error in the checkAppleErrorResponse function.
Here is the code that changes when changed from one device to many:
foreach ($device_tokens as $token)
{
$apple_identifier = '[censored]';
$payload = json_encode($body);
$msg = pack("C", 1) . pack("N", $apple_identifier) . pack("N", $apple_expiry) . pack("n", 32) . pack('H*', str_replace(' ', '', $token)) . pack("n", strlen($payload)) . $payload;
/* Actually sends the notification */
fwrite($fp, $msg);
$this->checkAppleErrorResponse($fp);
}
Update: I tried to manually copy some of the tokens and do random tests on when devices receive the notifications. Although I can't say the results are conclusive, it turns out that when all tokens are certainly valid (devices that exist in our company), the messages go through. However, when I add at least one device that I can't check personally (means it might be invalid, or the user refused notifications), none of the devices in the list get messages.
The question is, does this mean Apple requires the entire array of tokens to be valid devices whose owners authorized APNs? (Seems completely illogical, but it's the only explanation I can think of).
A big part of the app I am working on is chat with Push Notifications. The whole system is working great except that when a user sends a message with an emoji in it, the receiver of this message will see this in their push note:
When the receiver taps on the push notification, the emoji's from the message are rendered fine in the app, like so:
The messages are stored on my server in a MySQL db, and a php script packages up the push note JSON and sends it to APNS.
Here is the part of my PHP script that packages up the JSON to send to APNS (borrowed mostly from a Ray Wenderlich tutorial):
function makePayload($senderName, $text)
{
$nameJson = $this->jsonEncode($senderName);
$nameJson = truncateUtf8($nameJson, 20);
// Convert and truncate the message text
$textJson = $this->jsonEncode($text);
$textJson = truncateUtf8($textJson, self::MAX_MESSAGE_LENGTH);
$payload = '{"aps":{"alert":"' . $nameJson . ': ' . $textJson . '","sound":"default"} . '}';
return $payload;
}
I'm pretty stumped. I'm not sure why iOS isn't parsing the "alert:" portion of my push note JSON correctly. Any ideas are much appreciated.
We have an app on appstore, and with registered push notifications. They have successfully worked all the time, but we now tried to send a 'global' push, and something weird happened. This is what we have in our server-side .php file:
//Loop through tokens in tokenArray
$i = 0;
$t = 0;
foreach($tokenArray as $token)
{
$t++;
// Make notification
$msg = chr(0) . pack('n', 32) . pack('H*', $token) . pack('n', strlen($payload)) . $payload;
// Send
$result;
if($message != null)
{
$result = fwrite($fp, $msg, strlen($msg));
}
if ($result)
$i++;
}
// Close the connection to the server
fclose($fp);
if($i == 0)
{
echo 'The message was not delivered to anyone out of '.$t.'.';
}
else
{
echo 'The message was delivered to '.$i.' out of '.$t.'.';
}
The code before this has always worked, and it kind of still does. The tokenArray contains the table with tokens, as in SELECT Token FROM Tokens; from our SQL. This works.
During development, when only our own tokens were registered, it always said "The message was delivered to 4 out of 4", even though we had deleted our apps from our phones. Now we tried to send to all ≈1100 registered tokens with this code.
The message was sent, and the output was "The message was delivered to 588 out of 1194."
And we did not receive the notification ourselves!
What does that mean?
After about 5 minutes, I switched out the tokenArray with an array only containing my own tokens and sent a new push, and I received that one on my phone. I also know for a fact that the 'working' token exist in the previous 'tokenArray' which failed(I checked).
Is push notification a game of chance!? What does it mean when if($result) fails? And why did it fail over 500 times?
The certificates and .pem and .p12 etc are all working, the only thing I did different from push1 to push2 was to use another table which is a clone from the original table in my SQL-server. Table2 only have my tokens, and it worked. No other changes was made. Only SELECT Token FROM Tokens2, and later I proved that all the tokens in Tokens2 exist in Tokens
I have no idea if anyone got the push at all, or if the 'lucky' 588 of the 1200 that still has the app installed received it.
What causes this? We don't dare send another one in case half of them already received it.. Is there some limit to how fast I can send pushes at once? Or what are we doing wrong?!
Please help, thanks.
Well, I don't know php, so your code doesn't help me. However, based on your description it's likely some of the device tokens in your DB are invalid. When Apple's server gets a notification with an invalid device token it closes the socket. If you already wrote more messages after the one with the bad token, they won't reach Apple. Only after you detect that the socket was closed and open a new one your messages will reach Apple. If you don't use the enhanced notification format, it would be a good idea to start using it - this way you can get from Apple the id of the invalid message and clean your DB from invalid tokens. However, even using the enhanced format doesn't guarantee that you'll detect all the errors (unless you are willing to send the messages really slowly, and check for error responses from Apple after each message you send).
Your main loop does not take into account cases in which Apple will close socket connections. As mentioned by Eran, if you send an invalid token, Apple closes the connection at which point, any further writes using fwrite will fail. So if your 589th token is invalid, no other push will be sent to Apple.
Here's a simple fix for that that fits into your logic; this part replaces the if statement in the main loop:
if ($result) {
$i++;
} else {
fclose($fp);
// Add code here to re-open socket-connection with Apple.
}
Besides the enhanced notification format mentioned by Eran, you can also use the APNS Feedback API to query Apple for invalid tokens and purge them from your database. You can find more infomation on that here: http://bit.ly/14RPux4
There is no limit to how many push notifications you can send at once. I've sent thousands in a few seconds. The only real limitation is the connection between you and the APNS servers.