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

    In short, push notifications are small 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 in the absence of the need to keep the program forever in memory, spending on it processor power and memory.
    I will not describe here the entire technology for delivering remote notifications, for this has already been done before me . It looks something like this: from time to time the daemon polls the server and, if a message appears, shows it to us. They
    came up with APNS for iOS , C2DM-GCM for Android, but I want to talk about the cross-platform (loud) Pushover service and linking it to a php site.

    Task example

    Suppose once a day we want to know something about the number of orders on a site per day and their value.
    The site spins on some CMS in PHP and mySQL, the host has stylish iPhone and Android phones.
    The urgency of message delivery does not apply to vital indicators.
    It is necessary to find a conditionally hemorrhoidal solution.


    Pushover is a modest notification service , as well as applications for iOS and Android , planned crafts for both BlackBerry and OS X Mountain Lion. The service has its own API ; it allows sending 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, can contain a large header, URL (then the message length increases to 500) and its title (everything is displayed in separate formed blocks, because of this distinction). A message can be delivered under a selected selected priority. The user can specify the "quiet" hours when it is not worth it to wake up notifications, as well as connect and disconnect devices to which notifications will come.
    The notification can be delivered to the users who provided their code to all devices of this user or by choice. To receive a message, the user must be registered in the service and have at least one working device.

    Add user

    After completing the registration , each user gets into his account, where he immediately sees his hash token. This is the unique identifier of the user, to which notifications are sent later.
    A user who wants to receive messages must put the application from the corresponding store on his phone / tablet / anyhow.

    Adding a Service

    Adding a service is no more complicated. From your personal account you need to 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. Basically, this is all that is needed to send a message.
    The application page will subsequently have a beautiful schedule of successfully sent messages.

    Linking applications and recipients

    ... not done in any way. Any application can send a notification to any user if it knows its token. Acceptance of tokens from the population remains on the conscience of the application. As well as unsubscribing from newsletters.


    Small , capacious and understandable. To send a message in a POST request to api.pushover.net/1/messages.json or api.pushover.net/1/messages.xml, you must specify the minimum:
    • token - the hash token of your application or service.
    • user - the hash token of the user to whom you are sending a notification.
    • message - the text part of the message.

    In addition to this, you can add:
    • device - the identifier of the user's device, so as not to send notifications immediately to all its devices
    • title - the title of the message, if not specified, the name of the service will be displayed
    • url - link to a web page, if necessary
    • url_title - title to the link
    • priority - priority of the message, set to 1 for high priority, bypassing all "quiet" hours and -1 for silent notification.
    • timestamp - UNIX timestamp when this notification was created. Service delivery timetables are not provided.

    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, an object will be given with the contents 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 sample responses for successful and unsuccessful XML submissions:
    invalidapplication token is invalid0


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

    Zafigarim your class

    Where now without bicycles?
    In fact, I didn’t really like that the success of sending a notification is either defined as true / false, or the entire sheet of the server’s response is displayed immediately. Yes, generally there is no error handling. I believe that if a site visitor is not necessary, then the developer needs to know why this or that message was not sent.
    In general, we are essentially changing everything; the classes have left on 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)
    			$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()
    	 * 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()
    			$this->throwMessage('Application token is empty');
    			$this->throwMessage('User token is empty');
    			$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)
    		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['status']) || intval($lResponse['status']) != 1)
    			$this->throwMessage('Unknown notification send error');

    The minimum message is now quite simple to send, errors can be resolved:
    $lPushover = new Pushover('Токен приложения');
    $lPushover->userToken = 'Токен пользователя';
    $lPushover->notificationMessage = 'Текст сообщения';
    	echo 'Message sent', PHP_EOL;
    catch (PushoverException $aException)
    	echo 'Error sending messages
    ', PHP_EOL; echo '
      ', PHP_EOL; foreach($aException->getMessages() as $lMessage) echo '
    • ', $lMessage, '
    • ', PHP_EOL; echo '
    ', PHP_EOL; }

    The user has already accepted the message.


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

    Also popular now: