Push notifications are special messages that appear on smartphones without opening an app. The service transmits relevant events (e.g., error states of a server) to subscribed users in each case.
Numerous push notification providers exist on the market, such as Pushover. If one does not intend to use these, such as for privacy violation reasons, this requires a separate service. Nextcloud Talk allows to implement a fully independent push notification service.
The following example describes the implementation and sending of a push notification with PHP script and Nextcloud Talk from a server to a smartphone.
- The prerequisite is a functioning Nexcloud service with activated Nextcloud Talk app. In addition, it is necessary to install Nextcloud Talk on the smartphone and configure it to the Nextcloud service. This installation and configuration is not part of this article.
- installing curl on the system
sudo apt install curl
- Create a user for the automatic service in Nextcloud (e.g. “robotic”).
- Create an application password under “User/Security”.
- Create a Nextloud Talk channel with the user for the automatic service (e.g. robotic) and add users to whom the push messages should be sent.
- Open the channel and copy the channel id from the URL (https://<address_to_nextcloud_service>/index.php/call/<channel_id>).
- And now follows the magic PHP-code part, which has to be copied somewhere on the server.
<?php function NextcloudTalk_SendMessage($channel_id, $message) { $SERVER = "https://<address_to_nextcloud_service>"; $USER = "<nextcloud_robotic_user>"; $PASS = "<application_password>"; // notify hack $data = array( "token" => $channel_id, "message" => $message, "actorDisplayName" => "PYTHON-NOTIFICATION", "actorType" => "", "actorId" => "", "timestamp" => 0, "messageParameters" => array() ); $payload = json_encode($data); $ch = curl_init($SERVER . '/ocs/v2.php/apps/spreed/api/v1/chat/' . $channel_id); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLINFO_HEADER_OUT, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); curl_setopt($ch, CURLOPT_USERPWD, "$USER:$PASS"); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); // Set HTTP Header curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($payload), 'Accept: application/json', 'OCS-APIRequest: true') ); $result = curl_exec($ch); curl_close($ch); } $token = $argv[1]; $message = $argv[2]; NextcloudTalk_SendMessage($token, $message); ?>
- Test service from command line
php <path_to_file>/nextcloudmessage.php <channel_id> <message>