Categories
Developers Software Development Tools Web

Send Push Messages to Firebase Cloud Messaging (Google) via PHP

Firebase Cloud Messaging (FCM) is a cross-platform (Android, IOS and Web) messaging solution by Google that lets you send messages at no cost… FCM was previously known as Google Cloud Messaging. (view the docs)

Achitecture overview – Firebase Cloud Messaging ( source: Google )

Using FCM you can notify a client app (Android or even an IOS application) that new email or other data is available to sync.
You can send notification messages to drive user re-engagement and retention (very important in Sales & Marketing).

Customer engagement is important. You’ll want to keep your customers informed about related products they might want to buy or if you offer a new service you want the to know. Push notifications are a quick and easy way to contact people directly.

Click here to go to the PHP script. Or if you prefer a solution writting in Go, capable sending push messages to both IOS and Android directly go down go GoRush.

For use-cases such as instant messaging (a message can transfer a payload of up to 4KB to a client app).

4KB is 1024 ~ 4096 letters. To give you an example scroll past the following text, assuming one byte per letter gives you this amount of text to send: click here to skip directly to the features

// 4096 characters

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc, quis gravida magna mi a libero. Fusce vulputate eleifend sapien. Vestibulum purus quam, scelerisque ut, mollis sed, nonummy id, metus. Nullam accumsan lorem in dui. Cras ultricies mi eu turpis hendrerit fringilla. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; In ac dui quis mi consectetuer lacinia. Nam pretium turpis et arcu. Duis arcu tortor, suscipit eget, imperdiet nec, imperdiet iaculis, ipsum. Sed aliquam ultrices mauris. Integer ante arcu, accumsan a, consectetuer eget, posuere ut, mauris. Praesent adipiscing. Phasellus ullamcorper ipsum rutrum nunc. Nunc nonummy metus. Vestibulum volutpat pretium libero. Cras id dui. Aenean ut eros et nisl sagittis vestibulum. Nullam nulla eros, ultricies sit amet, nonummy id, imperdiet feugiat, pede. Sed lectus. Donec mollis hendrerit risus. Phasellus nec sem in justo pellentesque facilisis. Etiam imperdiet imperdiet orci. Nunc nec neque. Phasellus leo dolor, tempus non, auctor et, hendrerit quis, nisi. Curabitur ligula sapien, tincidunt non, euismod vitae, posuere imperdiet, leo. Maecenas malesuada. Praesent congue erat at massa. Sed cursus turpis vitae tortor. Donec posuere vulputate arcu. Phasellus accumsan cursus velit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed aliquam, nisi quis porttitor congue, elit erat euismod orci, ac placerat dolor lectus quis orci. Phasellus consectetuer vestibulum elit. Aenean tellus metus, bibendum sed, posuere ac, mattis non, nunc. Vestibulum fringilla pede sit amet augue. In turpis. Pellentesque posuere. Praesent turpis. Aenean posuere, tortor sed cursus feugiat, nunc augue blandit nunc, eu sollicitudin urna dolor sagittis lacus. Donec elit libero, sodales nec, volutpat a, suscipit non, turpis. Nullam sagittis. Suspendisse pulvinar, augue ac venenatis condimentum, sem libero volutpat nibh, nec pellentesque velit pede quis nunc. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Fusce id purus. Ut varius tincidunt libero. Phasellus dolor. Maecenas vestibulum mollis diam. Pellentesque ut neque. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. In dui magna, posuere eget, vestibulum et, tempor auctor, justo. In ac felis quis tortor malesuada pretium. Pellentesque auctor neque nec urna. Proin sapien ipsum, porta a, auctor quis, euismod ut, mi. Aenean viverra rhoncus pede. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Ut non enim eleifend felis pretium feugiat. Vivamus quis mi. Phasellus a est. Phasellus magna. In hac habitasse platea dictumst. Curabitur at lacus ac velit ornare lobortis. Cura

That's 4096 characters of text.... a lot eh?

Features

Firebase Cloud Messaging is the Google version of
Apple‘s counterpart Apple Push Notification Service. (Read more about APNs in a previous blogpost)

The standard features are what you’d expect of a messaging service:

  1. Send notification messages or data messages
    Send notification messages that are displayed to your user. Or send data messages and determine completely what happens in your application code.

  2. Target the audience you want!
    Distribute messages to your client app in any of 3 ways—to single devices, to groups of devices, or to devices subscribed to topics.

  3. Send messages from client apps back to your API
    Send acknowledgments, chats, and other messages from devices back to your server over FCM. (Google claims this is very energy efficient)

As an added benefit you can also use FCM to send messages to IOS devices. (You can’t send a message to Android devices from Apple’s service)

The real power of FCM? Analytics!

The real power of FCM is analytics and data.
You’ll get a GREAT dashboard and tons of options to review how you’re app is doing as an added benefit. It integrates perfectly with all the other tools of Google (like search console and analytics) so you can see how your app is performing (over time / per version)

It’s something you don’t get with Apple’s APNS out of the box.

PHP Script to send message


You can use the following script to send a message to Android device(s) registered via your App:

<?php

// API access key from Google API's Console
$apiKey = "FILL_IN_KEY_HERE";

// Device id's from Android devices.
$deviceIds = [
   'cpTVnn56oE4:APA91dDay_example_only_deviceId1',
   'cpTVnn56oE4:APA91dDay_example_only_deviceId2',
   'cpTVnn56oE4:APA91dDay_example_only_deviceId3'
];

// Message payload
$payload = [
   'registration_ids' => $deviceIds,
   'notification' => [
       'title'   => 'SaMauto.nl Test Notification title',
       'body'    => 'Body of the notification...'
   ]
];

// headers
$headers = [
   "Authorization: key=$apiKey",
   "Content-Type: application/json"
];

$ch = curl_init();
// prod endpoint
curl_setopt($ch, CURLOPT_URL, "https://fcm.googleapis.com/fcm/send");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));

// execute the request.
$result = curl_exec($ch);

// close the connection
curl_close($ch);

GoRush: Push Notification Server that supports IOS and Android

  ________                              .__
 /  _____/   ____ _______  __ __  ______|  |__
/   \  ___  /  _ \\_  __ \|  |  \/  ___/|  |  \
\    \_\  \(  <_> )|  | \/|  |  /\___ \ |   Y  \
 \______  / \____/ |__|   |____//____  >|___|  /
        \/                           \/      \/

Usage: gorush [options]

As I mentioned in the previous post about a PHP script for push messages to mobile (IOS) devices, you can also use this great tool from appleboy written in Go. It’s called GoRush. You’ll get way way more performance, and features like an out-of-the-box Web API, Monitoring, Memory Usage, CLI, Retry/Resend and it also supports Push notification to Apple’s Push Notification Service.


Categories
Developers Software Development Tools Web

Step-by-Step PHP script to connect to Apple Push Notification Service – IOS

HTTP/2 is the new standard (soon in November 2020 the only way to connect to the APNS) in this article i’ll explain how to use PHP to connect to APNS using JWT tokens. You can also use certificates, but they expire and are a pain in the *ss if you manage multiple apps.

I18N: Deze blog is ook het Nederlands beschikbaar.

Pssst… Don’t like PHP? Scroll down to the other options at the bottom.

Apple’s service to send push notifications to iPhones, iPads and even to Apple’s watches is called APNS: Apple Push Notification Service) .

In order to send Push Notifications you’ll need an IOS app and a server to send the message from. In this article I will provide information on how to send the messages via PHP using a library to make it easier to generate the required JWT token.

What do you need in order to send Push Notifications via APNS?

The delivery of remote notifications involves several key components. We’ll be needing a receiver (iPad, iPhone, ect) and a server to send the message from (provider server)

We’ll be creating a provider server (left). To send a message to a IOS device (right)
  • Your company’s/personal server (known as the provider server)
    • We’ll be using PHP on our provider server
  • Apple Push Notification service (APNs)
    • Private key (or certificate) from Apple (.p8 file)
  • The user’s (apple) device (iPad, iPhone, ect.)
  • IOS application (Your app running on the user’s device)
    • for example: nl.samauto.ios-application

Getting the private key from Apple

Apple Push Notification service (APNs) must know the address of a user’s device before it can send notifications to that device. The address takes the form of a device token unique to both the device and your app ( nl.samauto.ios-application ) . At launch time, your app communicates with APNs and receives its device token, which you then forward to your provider server (the one we are going to build with PHP). Our server will include that token with any notifications it sends to Apple.

Head over to developer.apple.com and login with your AppleId.
Go to “Certificates, Identifiers & Profiles > Keys“

Generate a new key for your application, make sure to enable the Push Notifications Capability.

Download the .p8 file and save it to a secure location.
IT CANNOT BE DOWNLOADED AGAIN (APPLE DELETES THE PRIVATE KEY)

Samauto PHP Push Server

We’ll be building our server with PHP.

To authenticate to APNS we are utilizing JWT (JSON Web Tokens – RFC 7519) to create a Token Based Authenticated connection to Apple’s servers.

We will use composer to add a package (jwt) developed by Luís Cobucci. View lcobucci/jwt on GitHub or at packagist.org)

To add the package (via composer) to the project use the following command:

composer require lcobucci/jwt

We’ll have something like this in our composer.json.
We can now use it (using a PSR autoloader) in our script

<?php
require __DIR__ . '/vendor/autoload.php'; // Step 0: PSR-0 Autoloader
// Step 1: Import the library
use Lcobucci\JWT\Signer\Key;
use Lcobucci\JWT\Signer\Ecdsa\Sha256;
use Lcobucci\JWT\Configuration;

// Step 2: declare config variables
$device_token = "device_token_here";
$apns_topic = 'nl.samauto.ios-application';
$p8file = "/home/dave/samauto/key_from_apple.p8";
$url = "https://api.sandbox.push.apple.com/3/device/$device_token"; // call either the sandbox or production API's


$config = $container->get(Configuration::class);
assert($config instanceof Configuration);

// Step 3: Generate a JWT Token.
$token = (string) $config->createBuilder()
->issuedBy("DEF123GHIJ") // (iss claim) // teamId
->issuedAt(time()) // time the token was issuedAt
->withHeader('kid', "ABC123DEFG")
->setKey('file://' . $p8file)
->setSigner(new Sha256()) // APNs only supports the ES256 algorithm
->getToken(); // get the generated token

// Step 4: Generate a payload (PushMessage) to send to the device
$payloadArray['aps'] = [
  'alert' => [
    'title' => "Dev.To Push Notification", // title of the notification
    'body' => "Visit SamAuto.nl for more awesome scripts", // content/body of the notification
  ],
  'sound' => 'default',
  'badge' => 1
];
// Step 4.1: Encode it as json.
$payloadJSON = json_encode($payloadArray);


// Step 5: create and send the cURL HTTP/2 request
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_POSTFIELDS, $payloadJSON);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer $token","apns-topic: $apns_topic"]);
$response = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

// On successful response you should get true in the response and a status code of 200
// A list of responses and status codes is available at
// https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/TheNotificationPayload.html#//apple_ref/doc/uid/TP40008194-CH107-SW1

var_dump($response);
var_dump($httpcode);
?>

What if you leak your Push Notification key to GitHub.com?

Immediately revoke the key or certificate!
(you can do this on the developer.apple.com site)

Then… add a .gitignore file to your repository in order to prevent this from happening again.

– Get a new key and install it on the provider server.

All the code is on our GitHub account!

Do you really want to get started right now?

just use the following composer command:

composer require edamov/pushok

This will download edamov/pushok which is a super nice library that basically does the same thing as the example, but better.

<?php

require __DIR__ . '/vendor/autoload.php';

use Pushok\AuthProvider;
use Pushok\Client;
use Pushok\Notification;
use Pushok\Payload;
use Pushok\Payload\Alert;

$options = [
    'key_id' => 'ABC123DEFG', // The Key ID obtained from Apple developer account
    'team_id' => 'DEF123GHIJ', // The Team ID obtained from Apple developer account
    'app_bundle_id' => 'com.app.Test', // The bundle ID for app obtained from Apple developer account
    'private_key_path' => __DIR__ . '/private_key.p8', // Path to private key
    'private_key_secret' => null // Private key secret
];

$authProvider = AuthProvider\Token::create($options);

$alert = Alert::create()->setTitle('Hello!');
$alert = $alert->setBody('First push notification');

$payload = Payload::create()->setAlert($alert);

//set notification sound to default
$payload->setSound('default');

//add custom value to your notification, needs to be customized
$payload->setCustomValue('key', 'value');

$deviceTokens = ['<device_token_1>', '<device_token_2>', '<device_token_3>'];

$notifications = [];
foreach ($deviceTokens as $deviceToken) {
    $notifications[] = new Notification($payload,$deviceToken);
}

$client = new Client($authProvider, $production = false);
$client->addNotifications($notifications);



$responses = $client->push(); // returns an array of ApnsResponseInterface (one Response per Notification)

foreach ($responses as $response) {
    $response->getApnsId();
    $response->getStatusCode();
    $response->getReasonPhrase();
    $response->getErrorReason();
    $response->getErrorDescription();
}

All clean code and nice and easy to use. Happy coding!

GoRush: Push Notification Server written in Golang (supports IOS and Android)

It’s 2020… PHP has come a long way, but it cannot match the sheer performance of Golang…

  ________                              .__
 /  _____/   ____ _______  __ __  ______|  |__
/   \  ___  /  _ \\_  __ \|  |  \/  ___/|  |  \
\    \_\  \(  <_> )|  | \/|  |  /\___ \ |   Y  \
 \______  / \____/ |__|   |____//____  >|___|  /
        \/                           \/      \/

Usage: gorush [options]

I can recommend a very fast and versatile program written in Go. It’s called GoRush. You’ll get way way more performance, and features like an out-of-the-box Web API, Monitoring, Memory Usage, CLI, Retry/Resend and it also supports Push notification to Google/Android/FCM previously known as Google Cloud Messaging.

Give it a try and tell me what you think.

Categories
Developers Databases Software Development Tools

Metabase

Graph viz toolsset meets SQL/DB explorer tool. Metabase to the rescue! As a developer I really love love this tool…

I ❤️ Metabase .

You can provide users with report pages in your application… or you could give them access to a whole array of tools at their disposal. You’ll empower them to create awesome dashboards and data visualizations.

GitHub

Since MetaBase is Open Source you can download it for free!

GitHub Logo
Click the GitHub Logo to visit MetaBase on Github

GitHub: https://github.com/metabase/metabase

Website: https://www.metabase.com/

Docker

You can try out Metabase on Docker, put the following commands in your favorite command line:

docker run -d -p 3000:3000 --name metabase metabase/metabase

After running the command, visit http://localhost:3000/ to view Metabase on your local environment. After a quick setup you can pick a datasource:

Datasources that work with Metabase

  • MySQL
  • Postgres
  • Mongo
  • SQL Server (Microsoft)
  • AWS Redshift
  • Google BigQuery
  • Druid
  • H2
  • SQLite
  • Oracle
  • Crate
  • Google Analytics
  • Vertica
  • Spark
  • Presto
  • Snowflake

There is an example database included so you can checkout the graph capabilities of Metabase. So you don’t even need a dataset or database credentials in order to get a first impression of metabase.

Pie chart in MetaBase
Example Pie chart in MetaBase

Pie charts, Bar charts, Line charts you name it, select the data and the tool will graph it for you.

Graph in Metabase
Example bar graph in Metabase

Metabase Dark Mode

In order to use MetaBase in Dark mode: (just like SaMauto (Dark by default)

First enter fullscreen mode: just click the screen icon in the top right of the dashboard. Using fullscreen mode you can switch the dashboard into “Night mode” (Dark mode) for higher contrast (black on white)

Categories
Developers Software Development Tools

Docker

Docker is an awesome tool for developers. It makes it easy to share the exact same configuration with the world. If you pack an application in a Docker container, it’ll run on any system independent of the underlying OS.

Most of the tools listed on SamAuto run on Docker and we’ve made it easy to deploy the whole stack using Docker compose.

Visit https://docker.com for more information on Docker.

Categories
Developers Tools

HubSpot

HubSpot is what i currently use for forms (Contact form, Newsletter) on this website. My newsletter pop-up is an good example of how you can engage with the visitors of your website.

Website: https://hubspot.com/