1. Code
  2. PHP

Generate Notifications From Your Web App With the Pushover API

Scroll to top
5 min read
Final product imageFinal product imageFinal product image
What You'll Be Creating

Pushover is one of my favorite services over the past few years; it makes it easy and inexpensive for developers to send push notifications to iOS and Android devices without having to develop their own application. 

It also recently added desktop browser notifications as well. The service is largely free for low level usage and the apps only require a $4.99 fee after a five-day free trial; there is no monthly fee. Working with its API is straightforward and there are libraries available for a handful of different languages.

While a number of front-end app developers integrate with Pushover, e.g. IT, I find it most useful as a developer for receiving notifications related to my own applications and web servers. For example, I've integrated Pushover into my Simple Monitoring application to alert me to website failures as well as sending twice daily heartbeat notifications when nothing is wrong. If MySQL fails or my DNS goes down, I'll receive a speedy alert to my iPhone. 

Similarly, I integrated Pushover into SimplifyEmail to send notifications when emails with specific keywords arrive such as "urgent" or from specific senders such as "Tom McFarlin" (Envato's Code editor).

Here's what Pushover alerts look like on your phone:

Sample heartbeat and failure alerts from Simple Monitor using PushoverSample heartbeat and failure alerts from Simple Monitor using PushoverSample heartbeat and failure alerts from Simple Monitor using Pushover

Pushover offers a variety of sounds to customize notifications and it also supports user-configurable quiet hours, so you don't have to be woken up in the middle of the night unless you want to be:

Configure Quiet Hours within PushoverConfigure Quiet Hours within PushoverConfigure Quiet Hours within Pushover

Just remember, real SysAdmins don't sleep!

Getting Started With Pushover

To get started with Pushover, visit the website and sign up:

Sign Up for PushoverSign Up for PushoverSign Up for Pushover

Then, install either mobile application or the desktop browser notification support. Each offers five days of free usage before you'll be required to purchase each for $4.99. For the iOS and Android apps, you can just download them from the app stores.

Install Pushover for iOSInstall Pushover for iOSInstall Pushover for iOS

When you install the mobile app, it will ask you to log in and specify a device name of your choosing, e.g. iPhone.

Setting up the desktop browser-based notifications is a bit different. Visit the Pushover for Desktop page and choose a simple name for your Pushover browser notifications:

Choose Your Desktop Notification Device NameChoose Your Desktop Notification Device NameChoose Your Desktop Notification Device Name

Instruct your browser to allow notifications:

Then, you'll see the Pushover desktop in-browser app:

The Pushover Browser-based AppThe Pushover Browser-based AppThe Pushover Browser-based App

Ultimately, desktop notifications from Pushover will look like this:

Example of a Pushover Web NotificationExample of a Pushover Web NotificationExample of a Pushover Web Notification

Once you have installed Pushover on your device and web browsers, you can begin sending test notifications from the Pushover website:

Send Send Send

But the fun is just beginning—let's get started using the Pushover API.

Developing With the Pushover API

Pushover requires that you register each application. Just visit your apps page:

The Pushover Apps PageThe Pushover Apps PageThe Pushover Apps Page

 And register a new application:

Create a New Pushover ApplicationCreate a New Pushover ApplicationCreate a New Pushover Application

You'll be given an API token to use to send notifications from your application:

An API Token for Pushover AppsAn API Token for Pushover AppsAn API Token for Pushover Apps

The Pushover home page offers some simple examples of sending notifications with curl:

1
curl_setopt_array($ch = curl_init(), array(
2
  CURLOPT_URL => "https://api.pushover.net/1/messages.json",
3
  CURLOPT_POSTFIELDS => array(
4
    "token" => "your-api-token",
5
    "user" => "your-user-id",
6
    "message" => "hello world",
7
  ),
8
  CURLOPT_SAFE_UPLOAD => true,
9
));
10
curl_exec($ch);
11
curl_close($ch);

But, for Simple Monitor and Simplify Email, I use Chris Schalenborgh's PHP Pushover library. For example, in SimpleMonitor, I use a background CronController that runs all of the tests the end user configures through the web user interface: 

1
class CronController extends Controller
2
{
3
  
4
  public function actionIndex()
5
    {
6
      $result = Content::model()->testAll();
7
		$this->render('index',array(
8
			'result'=>$result,
9
		));
10
	}

Here's an example of Simple Monitor's list of my checks which trigger different Pushover notification sounds:

Using Pushover Sounds with Simple MonitorUsing Pushover Sounds with Simple MonitorUsing Pushover Sounds with Simple Monitor

My TestAll method, called by cron, processes each of the user-configured tests. If there is a failure, it notifies each registered device. If there is no failure, it determines whether it's time to resend a heartbeat notification, letting me know the monitor is still up and running:

1
public function testAll() {
2
      $str = '';
3
        $errors = false;	  
4
  	  // monitor all content items

5
      $checks = Content::model()->findAll();
6
      foreach ($checks as $item) {
7
        // perform the test

8
        $str.='<p>Checking '.$item['name'].'...';
9
        $result = Content::model()->test($item['id']);
10
        // if there is an error send notification to the device

11
        if (!$result->status) {
12
          if ($item['type']==self::TYPE_CHANGES)
13
            $temp_result_string = 'Page Changed';
14
          else
15
            $temp_result_string = 'Failed';
16
          $str.=$temp_result_string.'<br />'; 
17
          $str.='Please check <a href="'.$item['url'].'">'.$item['url'].'</a><br />';
18
           if ($item['device_id']==0) {
19
             //  send to all devices

20
             $devices = Device::model()->findAll();
21
             foreach ($devices as $device) {
22
               Content::model()->notify($device,$item['name'].' '.$temp_result_string,'Please check into...',$item['url'],'this page',1,$item['sound']);                            
23
               $str.='Notifying '.$device['name'].'<br />';
24
             }
25
           } else {
26
             $device = Device::model()->findByPk($item['device_id']);
27
             Content::model()->notify($device,$item['name'].' '.$temp_result_string,'Please check into...',$item['url'],'this page',1,$item['sound']) ;               
28
             $str.='Notifying '.$device['name'].'<br />';
29
           }
30
           $str.='</p>';
31
          $errors = true;
32
        } else {
33
          $str.='success</p>';
34
        }      
35
      } 
36
      // check for sending heartbeart

37
      if (!$errors) {
38
        // only notify me with heartbeat every heartbeat_interval hours

39
        // note: cron must run every ten minutes or change 10 below to fit your interval

40
        // the point of date('i')<10 is to send heartbeat only in first part of any hour

41
        $setting = Setting::model()->getSettings();
42
        if ((date('G')% $setting['pushover_heartbeat_interval']) == 0 and date('i')<10) {
43
          $this->sendHeartbeat();
44
          $str.='<p>Heartbeat sent.</p>';
45
        } else {
46
          $str.='<p>Skipped heartbeat for now.</p>';        
47
        }
48
  	  }
49
  	  return $str;    
50
    }

My Notify method is what actually calls the Pushover PHP library to send the notifications. This is what you might use in your own application:

1
  // send notification to admin mobile device via pushover

2
  public function notify($device,$title='',$message='',$url='',$urlTitle='',$priority=1,$sound='gamelan',$debug=false) {
3
    if ($device['send_email']<>Device::SEND_EMAIL) {
4
      // load pushover key from Settings

5
      $setting = Setting::model()->getSettings();
6
      $po = new Pushover();
7
      $po->setToken($setting['pushover_app_api_token']);
8
      $po->setUser($device['pushover_user_key']);
9
      $po->setDevice($device['pushover_device']);
10
      $po->setSound($sound);
11
      $po->setTitle($title);
12
      $po->setMessage($message);
13
      if ($url<>'') {
14
        $po->setUrl($url);      
15
      }
16
      if ($urlTitle<>'') {
17
        $po->setUrlTitle($urlTitle);
18
      }
19
      $po->setPriority($priority);
20
      $po->setTimestamp(time());
21
      $po->setDebug(true);
22
      $go = $po->send();
23
      if ($debug) {
24
        echo '<pre>';
25
        print_r($go);
26
        echo '</pre>';      
27
      }      
28
    }

As a developer, I've found Pushover to be tremendously useful for delivering notifications in the absence of a dedicated mobile application. To me, Pushover's mobile app is like a SysAdmin dashboard that I didn't have to build. But it's also great for sending notifications for important emails or other server events. It's also fun to prank your friends if you can get hold of their user tokens and device names; but I would never do that.

Conclusion

I hope you enjoy using Pushover as much as I have. If you'd like to explore alternative services to Pushover, check out Boxcar and Panacea. I'd love to hear your thoughts. 

Please post any comments, corrections, or additional ideas below. You can browse my other Tuts+ tutorials on my author page or follow me on Twitter @reifman.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.