Daksh Agrawal
Daksh Agrawal

Reputation: 923

Application to Application Notifications

I am creating a Taxi App in which I have a driver application and a user application. When a user posts a request for a ride, ALL drivers must be notified that a request is available (Push Notifications). How can my native code know when to send notification?m

I don't want the Application to be Battery and Data Hungry, so I can't run a check over my MySQL database every minute. I looked for a solution with Firebase, but found out that they provide service for web to android notifications. I haven't written any code related to that yet.

Please suggest a way to achieve this. Googling it didn't help. If possible, attach code.

Thanks in Advance

Upvotes: 0

Views: 41

Answers (1)

Abdul Kawee
Abdul Kawee

Reputation: 2727

So firebase is not that difficult to use, here is the code for your PHP Api

// function makes curl request to firebase servers
private function sendPushNotification($fields) {

    require_once __DIR__ . '/config.php';

    // Set POST variables
    $url = 'https://fcm.googleapis.com/fcm/send';

    $headers = array(
        'Authorization: key=' . FIREBASE_API_KEY,
        'Content-Type: application/json'
    );
    // Open connection
    $ch = curl_init();

    // Set the url, number of POST vars, POST data
    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    // Disabling SSL Certificate support temporarly
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

    // Execute post
    $result = curl_exec($ch);
    if ($result === FALSE) {
        die('Curl failed: ' . curl_error($ch));
    }

    // Close connection
    curl_close($ch);

    return $result;
}

And now what config.php has is

<?php

// Firebase API Key
define('FIREBASE_API_KEY', '///lGrYwgBC8iz5reyx4qPUB7ByXX8MwC7Vcs8u...');
     ?>

You can get this key from Firebase Console under Project Settings -> Cloud Messaging -> Server Key

and now one simple function to send push notification

public function send($to, $message) {
    $fields = array(
        'to' => $to,
        'data' => $message,
    );
    return $this->sendPushNotification($fields);
}

Here in $to will come the Notification Id of the person you want to send notification. Here is the link.

Hope this helps you

Upvotes: 1

Related Questions