📜 ⬆️ ⬇️

Pushover push notification service for Android and iOS in conjunction with PHP


In short, push notifications are small in size important messages from a program or service that are displayed by the operating system when you are not directly working with the specified application or service. The advantage of such notifications is that there is no need to keep the program in memory forever, wasting processor power and memory on it.
I will not write here the whole technology of remote notification delivery, because it has already been done before me . It looks like this: periodically the daemon polls the server and in case of a message, shows it to us.
For iOS, APNS was invented, for Android, C2DM-GCM , but I want to tell you about the cross-platform (loud) Pushover service and its bundle with a php site.

Example task


Suppose that once a day we want to know something about the number of orders on the site per day and their cost.
The site is spinning on some CMS in PHP and mySQL, the host country has stylish iPhone and Android phones.
Urgency of message delivery is not a vital indicator.
It is necessary to find a conditionally non-hemorrhoid solution.

Pushover


Pushover is a modest notification service , as well as applications for iOS and Android , and crafts are planned for BlackBerry and OS X Mountain Lion. The service has its own API , allows you to send up to 7.5 thousand messages per month for free.


The message, in addition to the main text of the message with a length of 512 characters, may contain a large header, URL (then the message length is increased to 500) and its title (everything is displayed in separate formed blocks, therefore such a distinction). The message can be delivered under some selected specified priority. The user can specify "quiet" hours when it is not worth it to wake notifications, as well as connect and disconnect devices to which notifications will come.
Notification can be delivered to users who have provided their code, to all devices of this user or by choice. To receive a message, the user must be registered with the service and have at least one working device.
')
Add user


After registration , each user enters his office, where he immediately sees his hash token. This is a unique user identifier to which notifications are sent later.
The user who wants to receive messages, you must put on your phone / tablet / anyhow that the application from the corresponding store.

Add service

Adding a service is just as easy. From the personal account, go to the application creation page , where it is proposed to describe the product:

After filling in the appropriate fields, we become aware of the application token. In principle, this is all that is needed to send a message.
On the application page in the future there will be a beautiful schedule of successfully sent messages.

Linking applications and recipients

... not done in any way. Any application can send any user a notification if they know its token. Reception of tokens from the population remains on the conscience of the application. As well as unsubscribing from mailings.

API

Small , capacious and clear. To send a message in a POST request to api.pushover.net/1/messages.json or api.pushover.net/1/messages.xml you need to specify the minimum:

In addition, you can add:


Server response

The server response will be presented in json or xml format (depending on the extension of the called script).
If everything went well, the object will be given with the content of the status field equal to 1.
Otherwise, the status field will contain something else, and the errors field will contain an array of error descriptions. Here are examples of successful and unsuccessful responses in XML format:
<?xml version="1.0" encoding="UTF-8"?> <hash> <status type="integer">1</status> </hash> 
and
 <?xml version="1.0" encoding="UTF-8"?> <hash> <token>invalid</token> <errors type="array"> <error>application token is invalid</error> </errors> <status type="integer">0</status> </hash> 


Php


On the main page and in the FAQ in the sections “see how easy it is!” The codes of the simplest script in different languages ​​are given for sending and there is a link to the 3rd-party php-class from Chris Schalenborgh.
Everywhere it is used with CURL, which, of course, is understandable.

Zafigarim your class

Where now without bicycles?
In fact, I didn’t like it too much that the success of sending a notification is defined as either true / false, or the entire server response sheet is displayed at once. Yes, in general, there is no error handling. I believe that if a site visitor is not required, then the developer needs to know why this or that message was not sent.
In general, we essentially change everything, classes left for GitHub .
class PushoverException
 class PushoverException extends Exception { /** * Messages array * @var array */ private $fMessages; /** * Exception constructor * @param array $aMessages An array of messages */ public function __construct(array $aMessages) { parent::__construct('PushoverException exception'); $this->fMessages = $aMessages; } /** * Get messages array * @return array */ public function getMessages() { return empty($this->fMessages) ? array() : $this->fMessages; } } 

class Pushover
 class Pushover { /* * Pushover json api service url */ const C_API_URL = 'https://api.pushover.net/1/messages.json'; /** * Properties storage array * @var array */ private $fProperties; /** * cURL instance */ private $fCurl; //--------------------------------------------------------------------------// /** * Properties getter * @param string $aPropertyName Property name * @return mixed */ public function __get($aPropertyName) { if(array_key_exists($aPropertyName, $this->fProperties)) return $this->fProperties[$aPropertyName]; return null; } /** * Properties setter * @param string $aPropertyName Property name * @param mixed $aValue Property value */ public function __set($aPropertyName, $aValue) { $this->fProperties[$aPropertyName] = $aValue; } //--------------------------------------------------------------------------// /** * Class constructor * @param string $aApplicationToken Application token */ public function __construct($aApplicationToken = null) { if(!empty($aApplicationToken)) $this->applicationToken = $aApplicationToken; $this->fCurl = curl_init(); curl_setopt($this->fCurl, CURLOPT_URL, self::C_API_URL); curl_setopt($this->fCurl, CURLOPT_HEADER, false); curl_setopt($this->fCurl, CURLOPT_RETURNTRANSFER, true); curl_setopt($this->fCurl, CURLOPT_SSL_VERIFYPEER, false); } /** * Class destructor */ public function __destruct() { curl_close($this->fCurl); } //--------------------------------------------------------------------------// /** * Throws an exceprion with single message * @param mixed $aMessage * @throws PushoverException */ public function throwMessage($aMessage) { throw new PushoverException(array($aMessage)); } /** * Throws an exceprion with an array of messages * @param array $aMessages * @throws PushoverException */ public function throwMessages(array $aMessages) { throw new PushoverException($aMessages); } //--------------------------------------------------------------------------// /** * Send pushover notification */ public function send() { if(!strlen($this->applicationToken)) $this->throwMessage('Application token is empty'); if(!strlen($this->userToken)) $this->throwMessage('User token is empty'); if(!strlen($this->notificationMessage)) $this->throwMessage('Notification message is empty'); if(intval($this->notificationTimestamp) <= 0) $this->notificationTimestamp = time(); $lSendParams = array( 'token' => $this->applicationToken, 'user' => $this->userToken, 'device' => $this->userDevice, 'title' => $this->notificationTitle, 'message' => $this->notificationMessage, 'priority' => $this->notificationPriority, 'timestamp' => $this->notificationTimestamp, 'url' => $this->notificationUrl, 'url_title' => $this->notificationUrlTitle ); foreach($lSendParams as $lKey => $lParam) if(empty($lParam)) unset($lSendParams[$lKey]); curl_setopt($this->fCurl, CURLOPT_POSTFIELDS, $lSendParams); $lResponseJson = curl_exec($this->fCurl); if($lResponseJson === false) $this->throwMessage('API request error'); $lResponse = json_decode($lResponseJson, true); if(empty($lResponse) || !is_array($lResponse)) $this->throwMessage('Bad API response'); if(!empty($lResponse['errors'])) $this->throwMessages($lResponse['errors']); if(empty($lResponse['status']) || intval($lResponse['status']) != 1) $this->throwMessage('Unknown notification send error'); } } 



The minimum message is now quite simple to send, errors can be parsed:
 $lPushover = new Pushover(' '); $lPushover->userToken = ' '; $lPushover->notificationMessage = ' '; try { $lPushover->send(); echo '<font color="green">Message sent</font>', PHP_EOL; } catch (PushoverException $aException) { echo '<font color="red">Error sending messages</font><br>', PHP_EOL; echo '<ul>', PHP_EOL; foreach($aException->getMessages() as $lMessage) echo '<li>', $lMessage, '</li>', PHP_EOL; echo '</ul>', PHP_EOL; } 

The user has already accepted the message.

Total


We know about the convenient service of remote notifications, equally successfully transmitting messages to users of Android and iOS.
We have a working mechanism for sending notifications from the site to PHP.

Source: https://habr.com/ru/post/159649/


All Articles