Pushnotification Server side Implementation

2019-01-09 16:42发布

问题:

Recently i have integreted the FCM in my app recent version but my previous version of app was using GCM. Any ideas about whether we need to segregate the write the background cron for GCM and FCM?.

My Previous version MY App 4.0 and used GCM and Current version My App 4.1 and integrated the FCM. I wants to send the pushnotification for both version and users. So whether we need to write the server side program for GCM and FCM right?. Any ideas about this integration.

FCM Server Side API : https://fcm.googleapis.com/fcm/send GCM Server Side API : https://android.googleapis.com/gcm/send

Any other possiblies can we send the notification via FCM Server side program? or seperately need to write the program for GCM and FCM?.

Sample Code for FCM in PHP

<?php

function sendFCM($mess,$id) {
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array (
        'to' => $id,
        'notification' => array (
                "body" => $mess,
                "title" => "Title",
                "icon" => "myicon"
        )
);
$fields = json_encode ( $fields );
$headers = array (
        'Authorization: key=' . "AIzaSyA9vpL9OuX6moOYw-4n3YTSXpoSGQVGnyM",
        'Content-Type: application/json'
);

$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );

$result = curl_exec ( $ch );
curl_close ( $ch );
}

?>

回答1:

FCM is still compatible with GCM, seeing as it is it's core. So switching to the FCM endpoint (https://fcm.googleapis.com/fcm/send) when sending your notification should still work for your app versions that have GCM. No need to write separate programs.



回答2:

I have working code in my project, you can try it using Firebase of google: Firebase Tutorial

                $notification_send ="Message to be sent";

                $server_key = '****************************';//Authorization Key
                $client = new Client();
                $client->setApiKey($server_key);
                $client->injectGuzzleHttpClient(new \GuzzleHttp\Client());
                $message = new Message();
                $message->setPriority('high');
                $message->addRecipient(new Topic('test'));
                $message
                    ->setNotification(new Notification('Reislivsmessen', $notification_send ))
                    ->setData(['key' => 'value']);

                $response = $client->send($message);

You have to create topic, here it's "test".

I hope it works for you too.