PHP Backend Sample


Send push notifications to your users with this PHP code sample.

The following code will send a push notification to devices with {message: "Hello World!"} as the payload.

// Require Pushy API Class
require('pushy.php');

// Payload data you want to send to devices
$data = array('message' => 'Hello World!');

// The recipient device tokens
$to = array('cdd92f4ce847efa5c7f');

// Optionally, send to a publish/subscribe topic instead
// $to = '/topics/news';

// Optional push notification options (such as iOS notification fields)
$options = array(
    'notification' => array(
        'badge' => 1,
        'sound' => 'ping.aiff',
        'title' => 'Test Notification',
        'body'  => "Hello World \xE2\x9C\x8C"
    )
);

// Send it with Pushy
PushyAPI::sendPushNotification($data, $to, $options);

Create a file named pushy.php and paste the following code inside it:

class PushyAPI {
    static public function sendPushNotification($data, $to, $options) {
        // Insert your Secret API Key here
        $apiKey = 'SECRET_API_KEY';

        // Default post data to provided options or empty array
        $post = $options ?: array();

        // Set notification payload and recipients
        $post['to'] = $to;
        $post['data'] = $data;

        // Set Content-Type header since we're sending JSON
        $headers = array(
            'Content-Type: application/json'
        );

        // Initialize curl handle
        $ch = curl_init();

        // Set URL to Pushy endpoint
        curl_setopt($ch, CURLOPT_URL, 'https://api.pushy.me/push?api_key=' . $apiKey);

        // Set request method to POST
        curl_setopt($ch, CURLOPT_POST, true);

        // Set our custom headers
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        // Get the response back as string instead of printing it
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Set post data as JSON
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post, JSON_UNESCAPED_UNICODE));

        // Actually send the push
        $result = curl_exec($ch);

        // Display errors
        if (curl_errno($ch)) {
            echo curl_error($ch);
        }

        // Close curl handle
        curl_close($ch);

        // Attempt to parse JSON response
        $response = @json_decode($result);

        // Throw if JSON error returned
        if (isset($response) && isset($response->error)) {
            throw new Exception('Pushy API returned an error: ' . $response->error);
        }
    }
}

Note: Make sure to replace SECRET_API_KEY with your app's Secret API Key, available in the Pushy Dashboard (Click your app -> API Authentication tab). This is a backend API endpoint. Never expose your application's Secret API Key in your client code.