Create a food ordering app in React Native - Part 3: Adding push notifications
You will need Node 11.10+, Yarn 1.17+, React Native CLI 2+ and React Native 0.61+ installed on your machine.
This is the final part of a three-part series on creating a food ordering app in React Native. In the first part we created a very simple food ordering app, and in the second part we created a driver app with chat functionality. In this part, we’re going to add push notifications to inform both the customer and the driver of various events throughout the ordering process.
IMPORTANT:
ChatKit has been retired from the Pusher product stack as of April, 2020. This tutorial will no longer be functional in its current version. Explore our other Pusher tutorials to find out how Channels and Beams can help you build.
Prerequisites
This part has the same prerequisites as the first and second part.
You’ll need a Firebase account and a Beams account for implementing push notifications.
Feature overview
We will be adding push notifications for the following events:
- Driver accepted the order.
- Driver picked the order from the restaurant.
- Driver delivered the order to the customer.
- Driver sent a message to the customer.
- Customer confirmed to let the driver handle the order.
- Customer sent a message to the driver.
Here are a couple of screenshots. The first one is when the driver has accepted an order, and the second one is when the customer confirmed:
You can find the code on this GitHub repo. The completed code for this part is on the push-notifications
branch.
Setting up a Firebase project
Beams depends on Firebase Cloud Messaging (FCM) to send push notifications in Android so we need to set up a Firebase project.
The official documentation on how to create a Firebase project is available here. You can also follow the visual walkthrough in the Beams documentation site.
Create a separate Firebase project for each of the apps that we created because each one uses a different package name.
Once the project is created, click on the Cloud Messaging menu on the sidebar and you’ll see this screen. Click on the Android icon to view the form wizard for setting up Firebase on an Android app:
On the screen that follows, enter the package name. Note that you have to do this twice (one for each Firebase project). The first one is the driver app (com.rnfooddeliverydriver
), and the second one is for the ordering app (com.rnfooddelivery
):
Once you clicked on the Register app, it will ask you to download the config file. Download it and copy it over to the android/app
directory for the corresponding app.
Remember to repeat the same process for the ordering app.
Setting up Beams
On your Beams account, you also need to create two app instances. Each corresponds to the Firebase projects you just created.
On your Beams dashboard, click on the + CREATE button and enter the name of the app:
Once the instance created, it walks you through the quickstart. Select ANDROID:
Next, it will ask you to enter the FCM server key. Documentation on how to get it is available here:
Once that’s done, it will give you instructions on how to add Beams on your app. Some of these apply to React Native, but I’ll just walk you through how to set it up in the Setting up the ordering and driver app section so just skip this one:
Remember to repeat the same process for the ordering app and add the FCM server key from the corresponding Firebase project.
Setting up Chatkit webhooks
IMPORTANT:
ChatKit has been retired from the Pusher product stack as of April, 2020. This tutorial will no longer be functional in its current version. Explore our other Pusher tutorials to find out how Channels and Beams can help you build.
Configure Chatkit webhooks. This allows us to get notified when new messages are sent by any of the users of the app. That’s where we’ll add push notification code to notify the receiving user that somebody has sent them a message. This is especially useful in cases where the receiver is not yet in the chat screen when the message is sent.
You can choose to do this now or later when you run the app. Just know that you can actually execute ngrok at this point and add the target URL using this format: https://YOUR_NGROK_URL/notify
. Add a webhook secret as well. Just take note of it because we’re going to add it to the server/.env
file:
Setting up the ordering and driver app
The next step is to install and configure the React Native package for implementing push notifications. There’s no official React Native package for Beams yet so we’re using the React Native Push Notifications package. But because this package is already outdated, we’re using a fork instead.
The following instructions should be applied to both the ordering and driver app.
Update your package.json
file to add the push notifications package:
"dependencies": {
// ...
"react-native-pusher-push-notifications": "git+http://git@github.com/ZeptInc/react-native-pusher-push-notifications#v.2.4.0-zept-master",
}
After that, install the package:
yarn install
Next, update the android/settings.gradle
file, android/build.gradle
, and android/app/build.gradle
files to include the necessary configuration:
// android/settings.gradle
rootProject.name = 'RNFoodDelivery'
include ':app'
// add these:
include ':react-native-pusher-push-notifications'
project(':react-native-pusher-push-notifications').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-pusher-push-notifications/android')
// android/build.gradle
buildscript {
ext {
// ...
}
repositories {
// ...
}
dependencies {
classpath("com.android.tools.build:gradle:3.4.2")
classpath 'com.google.gms:google-services:4.2.0' // add this
}
}
allprojects {
repositories {
mavenLocal()
maven {
// ..
}
maven {
// ..
}
google()
jcenter()
}
}
// android/app/build.gradle
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "com.facebook.react:react-native:+"
// add these:
compile project(':react-native-pusher-push-notifications')
implementation 'com.github.ZeptInc:push-notifications-android:1.5.0-alpha'
}
// ...
apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
apply plugin: 'com.google.gms.google-services' // add this
Lastly, update your .env
file for the ordering app to include the Beams instance ID for the ordering app:
BEAMS_INSTANCE_ID="YOUR BEAMS INSTANCE ID FOR THE ORDERING APP"
Do the same for the driver app:
BEAMS_INSTANCE_ID="YOUR BEAMS INSTANCE ID FOR THE DRIVER APP"
Setting up the server
Since the push notifications will be triggered from the server, we need to install the Beams Server SDK for Node.js. Add the following to your server’s package.json
file:
"dependencies": {
// ...
"@pusher/push-notifications-server": "^1.2.0",
}
After that, execute the following:
yarn install
Lastly, update your server/.env
file with your Chatkit webhook secret and the instance and secret key for both Beams app instances:
CHATKIT_WEBHOOK_SECRET="YOUR CHATKIT WEBHOOK SECRET"
BEAMS_INSTANCE_ID_DRIVER="YOUR BEAMS INSTANCE ID FOR THE DRIVER APP"
BEAMS_SECRET_KEY_DRIVER="YOUR BEAMS SECRET KEY FOR THE DRIVER APP"
BEAMS_INSTANCE_ID_CUSTOMER="YOUR BEAMS INSTANCE ID FOR THE ORDERING APP"
BEAMS_SECRET_KEY_CUSTOMER="YOUR BEAMS SECRET KEY FOR THE ORDERING APP"
Updating the ordering app
At this point, we’re now ready to start updating the apps. First we’ll start with the ordering app.
GlobalContext
Open the GlobalContext.js
file and add a user_type
. This allows us to specify which type of user triggered the push notification. Which in turn allows us to determine which Beams app instance to use for sending the push notification. If it’s the customer who triggered it then it means the receiver is the driver so we use the Beams app instance for the driver app. Otherwise, we use the Beams app instance for the ordering app. You’ll see this in action in the server code later on:
export class AppContextProvider extends React.Component {
state = {
cart_items: [],
user_id: 'wernancheta',
user_name: 'Wern Ancheta',
user_type: 'customer', // add this
room_id: '',
room_name: '',
};
// ...
}
OrderSummary
Next we update the Chatkit login code so it uses the user_type
that we just added:
// src/screens/OrderSummary.js
placeOrder = async () => {
// ...
const {
address: restaurant_address,
location: restaurant_location,
} = this.context.cart_items[0].restaurant;
try {
await axios.post(`${BASE_URL}/login`, {
user_id: this.context.user_id,
user_name: this.context.user_name,
user_type: this.context.user_type, // add this
});
} catch (err) {
// ...
}
// ...
}
TrackOrder screen
The TrackOrder screen is where we put the code for implementing push notifications. Start by importing the react-native-pusher-push-notifications
package:
// src/screens/TrackOrder.js
import RNPusherPushNotifications from 'react-native-pusher-push-notifications';
Next, set the Beams app instance and create the function for subscribing to a specific device interest. In this case, we’re using the name subscribeToRoom()
because we’re using the room ID as the device interest name:
RNPusherPushNotifications.setInstanceId(Config.BEAMS_INSTANCE_ID);
const subscribeToRoom = room_id => {
RNPusherPushNotifications.subscribe(
room_id,
(statusCode, response) => {
console.error(statusCode, response);
},
() => {
console.log('Success');
},
);
};
We’re using the concept of device interests in order to subscribe users to a specific push notification channel. Later on in the server, we publish to the same device interest so that the devices which are subscribed to it can receive the notification.
Next, in your componentDidMount()
, add the code for triggering a push notification to be sent to the driver. This is sent when the customer confirms that the driver can proceed with processing the order after the driver has accepted their request. The way this works is that we add a specific route to the server later on to handle the triggering of push notifications. All we have to do from the frontend is supply the room_id
, push_type
, and data
and it will deliver the push notification to the recipient:
componentDidMount() {
// ...
this.user_ride_channel.bind('client-driver-response', data => {
const {hasDriver} = this.state;
this.user_ride_channel.trigger('client-driver-response', {
response: hasDriver ? 'no' : 'yes',
room_id: hasDriver ? '0' : this.context.room_id,
room_name: hasDriver ? '' : this.context.room_name,
});
// add this
if (!hasDriver) {
setTimeout(async () => {
const res = await axios.post(
`${BASE_URL}/push/${this.context.room_id}`,
{
push_type: 'customer_confirmed',
data: this.context.user_name,
},
);
}, 5000);
}
});
}
Still inside componentDidMount()
, right before the function’s closing curly brace, add the code to subscribe to the room and listen for notifications. In this case, we simply alert the user. This is only triggered when the app is in the foreground. If the app is in the background then the default behavior is to add a new item in the notification panel:
this.user_ride_channel.bind('client-order-update', data => {
this.setState({
orderStatusText: orderSteps[data.step],
});
});
// add these:
subscribeToRoom(this.context.room_id); // subscribe to device interest
RNPusherPushNotifications.on('notification', noty => { // listen for notifications
Alert.alert(noty.title, noty.body);
});
Updating the driver app
We now proceed to the driver app. What we need to do is pretty much the same thing we did in the ordering app. Only this time, we’re triggering a lot more notifications.
OrderMap screen
First, update the OrderMap screen:
// src/screens/OrderMap.js
import axios from 'axios';
import RNPusherPushNotifications from 'react-native-pusher-push-notifications'; // add this
// ..
const GOOGLE_API_KEY = Config.GOOGLE_API_KEY;
// add these
RNPusherPushNotifications.setInstanceId(Config.BEAMS_INSTANCE_ID);
const subscribeToRoom = room_id => {
RNPusherPushNotifications.subscribe(
room_id,
(statusCode, response) => {
console.error(statusCode, response);
},
() => {
console.log('Success');
},
);
};
// next: add triggerNotification()
Because we now have to trigger multiple notifications, we also need to add a function to encapsulate the functionality so we don’t repeat ourselves. You’ll see how the arguments we’re passing here will be utilized in the server later on. For now, know that the push_type
is the key that decides which user type the notification will be sent to as well as the title and body of the notification:
triggerNotification = async (room_id, push_type, data) => {
try {
await axios.post(`${BASE_URL}/push/${room_id}`, {
push_type,
data,
});
} catch (err) {
console.log('error triggering notification: ', err);
}
}
Next, in the constructor()
, add the user_type
:
constructor(props) {
super(props);
this.user_id = 'johndoe';
this.user_name = 'John Doe';
this.user_type = 'driver'; // add this
// ...
}
Update componentDidMount()
to add the code for listening to notifications. Also, update the Chatkit login code to include the user_type
:
componentDidMount() {
// ...
this.setState({
locationPermission: location_permission,
});
RNPusherPushNotifications.on('notification', noty => {
Alert.alert(noty.title, noty.body);
});
try {
await axios.post(`${BASE_URL}/login`, {
user_id: this.user_id,
user_name: this.user_name,
user_type: this.user_type, // add this
});
} catch (err) {
console.log('error creating user: ', err);
}
}
When the driver accepts an order, we want to notify the customer that somebody has accepted their order. Before triggering the notification though, we subscribe to the room first so that the driver will also receive notifications that are triggered by the customer:
_acceptOrder = () => {
// ...
this.ride_channel.bind('pusher:subscription_succeeded', () => {
// ..
this.ride_channel.bind(
'client-driver-response',
async customer_response => {
if (customer_response.response == 'yes') {
// ..
this.room_id = room_id;
this.room_name = room_name;
// add these
subscribeToRoom(room_id);
await triggerNotification(
room_id,
'driver_accepted_order',
this.username,
);
// ..
}
}
);
});
}
When an order is picked, trigger a notification:
_pickedOrder = async () => {
// ...
await triggerNotification(
this.room_id,
'driver_picked_order',
this.username,
);
}
And lastly, when an order is delivered:
_deliveredOrder = async () => {
// ...
await triggerNotification(
this.room_id,
'driver_delivered_order',
this.user_name,
);
}
Updating the server
The final step is to update the server code to send out those push notifications.
First, include the additional packages that we need:
// server/index.js
const PushNotifications = require('@pusher/push-notifications-server');
const crypto = require('crypto');
crypto
is a built-in module in Node.js so all we have to do is import it. We’re using it to calculate the signature to verify if the requests are indeed coming from Chatkit’s servers.
Next, add the Chatkit webhook secret and initialize the Beams client for each app:
const CHATKIT_WEBHOOK_SECRET = process.env.CHATKIT_WEBHOOK_SECRET;
// for sending notifications for the driver app
const beamsClientDriver = new PushNotifications({
instanceId: process.env.BEAMS_INSTANCE_ID_DRIVER,
secretKey: process.env.BEAMS_SECRET_KEY_DRIVER,
});
// for sending notifications for the ordering app
const beamsClientCustomer = new PushNotifications({
instanceId: process.env.BEAMS_INSTANCE_ID_CUSTOMER,
secretKey: process.env.BEAMS_SECRET_KEY_CUSTOMER,
});
After that, add the push_types
. These are the notification types that the server will handle. As you can see, it’s just a map of the title
and body
to be used for each notification type. The [data]
is replaced with the data
supplied for each notification request:
const push_types = {
driver_accepted_order: {
title: 'Order accepted',
body: '[data] has accepted your order',
},
driver_picked_order: {
title: 'Picked up order',
body: '[data] has picked up your order from the restaurant',
},
driver_delivered_order: {
title: 'Order delivered',
body: '[data] has delivered your order',
},
driver_sent_message: {
title: 'New message',
body: '[data]',
},
customer_confirmed: {
title: 'Customer confirmed',
body: '[data] has confirmed',
},
customer_sent_message: {
title: 'New message',
body: '[data]',
},
};
Next, determine which body parser to use depending on the content type. Chatkit webhooks needs to be processed as plain text so we use bodyParser.text()
if the content-type
is application/json
. This is the content type used by Chatkit’s servers. For the rest of the requests, we’re not really specifying the content type so it’s basically application/text
. In those cases, we use the bodyParser.json()
:
// app.use(bodyParser.json()); // remove
app.use(
bodyParser.text({
type: req => {
const contype = req.headers['content-type'];
if (contype === 'application/json') {
return true;
}
return false;
},
}),
);
app.use(
bodyParser.json({
type: req => {
const contype = req.headers['content-type'];
if (contype !== 'application/json') {
return true;
}
return false;
},
}),
);
Next, add the function for verifying if the requests came from Chatkit:
const verifyRequest = req => {
const signature = crypto
.createHmac('sha1', CHATKIT_WEBHOOK_SECRET)
.update(req.body)
.digest('hex');
return signature === req.get('webhook-signature');
};
If you want to learn more about implementing Chatkit webhooks in a React Native app, check out this tutorial: Integrate Chatkit Webhooks in a React Native Chat App.
Next, add a function for getting a Chatkit user. We’re already using the same functionality in the /login
route. But since we’re also going to need it to get the data of the user who sent a message, we’re adding it as well so we can use it for both instances:
const getUser = async user_id => {
try {
const user = await chatkit.getUser({
id: user_id,
});
return user;
} catch (err) {
console.log('error getting user: ', err);
return false;
}
};
Next, add the function for sending push notifications. This determines which Beams app instance to use depending on the user_type
. If the driver is the one who sent it then the recipient is the customer, thus we use the beamsClientCustomer
. Otherwise, we use the beamsClientDriver
:
const publishNotification = async (user_type, order_id, title, body) => {
const beamsClient =
user_type == 'driver' ? beamsClientCustomer : beamsClientDriver;
try {
await beamsClient.publishToInterests([order_id], {
fcm: {
notification: {
title,
body,
},
},
});
} catch (err) {
console.log('error publishing push notification: ', err);
}
};
Next, add the function for handling Chatkit webhooks. This handles the “message created” event. This is where we use the custom user data user_type
to determine which push notification to send. The room_id
is the same as the device interest so we can simply use it as the value for the order_id
required by the publishNotification()
function:
const notifyUser = async ({payload}) => {
try {
const msg = payload.messages[0];
const sender_id = msg.user_id;
const sender = await getUser(sender_id);
const message = msg.parts[0].content.substr(0, 37) + '...';
const order_id = msg.room_id;
const user_type = sender.custom_data.user_type;
const push_data = push_types[`${user_type}_sent_message`];
const title = push_data.title;
const body = push_data.body.replace('[data]', message);
await publishNotification(user_type, order_id, title, body);
} catch (err) {
console.log('notify user err: ', err);
}
};
Before we proceed to the routes which triggers the notifications, let’s first update the /login
route to include the user_type
:
app.post('/login', async (req, res) => {
const {user_id, user_name, user_type} = req.body; // add user_type
const user = await getUser(user_id);
if (!user) {
await chatkit.createUser({
id: user_id,
name: user_name,
// add this
customData: {
user_type,
},
});
}
return res.send('ok');
});
Next, add the route that allows us to trigger push notifications from the app:
app.post('/room', async (req, res) => {
// ...
});
app.post('/push/:order_id', async (req, res) => {
const {data, push_type} = req.body;
const {order_id} = req.params;
const user_type = push_type.split('_')[0];
const push_data = push_types[push_type];
const title = push_data.title;
const body = push_data.body.replace('[data]', data);
await publishNotification(user_type, order_id, title, body);
return res.send('ok);
});
Lastly, add the route which handles the Chatkit webhook for new messages:
app.post('/notify', (req, res) => {
if (verifyRequest(req)) {
const data = JSON.parse(req.body);
const type = data.metadata.event_type;
if (type == 'v1.messages_created') {
notifyUser(data);
}
return res.sendStatus(200);
} else {
console.log('Unverified request');
return res.sendStatus(401); // unauthorized
}
});
Running the app
At this point, you’re now ready to run the app.
Replace the NGROK_HTTPS_URL
on the .env
file on both apps then run the app. You can use the same technique we used on part two to run two apps from the same machine.
Don’t forget to update your Chatkit webhook with the ngrok HTTPS URL and the same webhook secret that you added on your server/.env
file. Also, clear out all existing Chatkit users because they don’t have the user_type
custom data yet.
Conclusion and next steps
That’s it! In this series, we created a food ordering app with React Native, Channels, Chatkit, and Beams. Along the way, you learned how to use various React Native packages for implementing maps, realtime location tracking, chat, and push notifications.
As for the next steps, here are a few ideas for improving the app further:
- Add authentication - currently, the usernames are just hard coded. It would be good to have an authentication in place. You can check out this tutorial as a guide: Using Auth0 for authenticating users in a React Native chat app.
- Add a restaurant app - you might have noticed that there’s really no way for the restaurant to know that someone has ordered a meal from them. You can either create a separate React Native app or simply create a web interface which gets notified everytime an order is received from the app.
- Hande order declines - we’ve only handled the “happy path” in this tutorial. It would be good to handle instances wherein the driver declines an order.
- Notify only nearby drivers - it would be good for the drivers to have a location database which constantly gets updated so that when an order is made, the app will query from this database only the drivers within a certain radius from the customer.
- Improve security - currently, anyone can just have access to the Channels and push notifications route. It would be good to put those behind an authentication.
You can find the full source code on this GitHub repo.
IMPORTANT:
ChatKit has been retired from the Pusher product stack as of April, 2020. This tutorial will no longer be functional in its current version. Explore our other Pusher tutorials to find out how Channels and Beams can help you build.
23 October 2019
by Wern Ancheta