[Huawei Developers] Freemind R:
More information like this, you can visit HUAWEI Developer Forum

[IMG="https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/647/156/2640091000001647156.20200814113632.25287550245158889197801330057635:50510826022009:2800:B9CDCAA965BBF29E28907A14E1D8728E0328C76E2BBF38A46237214F183377CF.png"]https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/647/156/2640091000001647156.20200814113632.25287550245158889197801330057635:50510826022009:2800:B9CDCAA965BBF29E28907A14E1D8728E0328C76E2BBF38A46237214F183377CF.png[/IMG]​

This article is the continuity of my previous article. To get a better picture or knowledge, refer my previous article first. Below is the link:

https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0202326236067510002&fid=0101187876626530001

Why you are having own server?

Using our own server to communicate with our app is generally the best option for sending push notification directly to our application. Because, our app will recognize and trust our own server which will allow us to control all transactions between our server and user devices.

Also if we need to send notification using Huawei AGC console, we need to copy and paste our users push token every time, which is a tedious job. Having our own server will allow us to store our users token and can send notification easily by fetching the entire list of token from database. That is what we are going to learn today.

Setting up the server

If you are not familiar with setting up your own local server and connecting the server with the device, refer my previous article “Build your own server from scratch to send push notification“. My previous article will help you setting up local server from scratch also, it is healthy to learn something new every day as our brain can store more information than a computer.

Prerequisite

1) We must have latest version of Node installed.

2) We must have latest version of Visual Studio Code installed.

3) We must have latest version of MongoDB database installed.

4) Laptop/desktop and Huawei mobile device must share same Wi-Fi connection.

5) We must have a working app integrate with HMS Push Kit.

We will divide this article into two parts

1) Server Side: The server side contains Node, Express, Request and JavaScript.

2) Client Side: The client side contains Android Native, Java, Retrofit and HMS Push Kit.

Demo

Send notification from server

[IMG="https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/647/156/2640091000001647156.20200814113902.80144588518814573861128422030551:50510826022009:2800:C0B2919B82C98962DBD483D16387EFD73358CE0DD269DD20514477455CAFD9C2.png"]https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/647/156/2640091000001647156.20200814113902.80144588518814573861128422030551:50510826022009:2800:C0B2919B82C98962DBD483D16387EFD73358CE0DD269DD20514477455CAFD9C2.png[/IMG]

[IMG="https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/647/156/2640091000001647156.20200814113912.03895910127423708006418684234449:50510826022009:2800:E7E549B8AE4724564A33F3C65ABB1E38911EDAD99903E2BAF524171093F16D3A.png"]https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/647/156/2640091000001647156.20200814113912.03895910127423708006418684234449:50510826022009:2800:E7E549B8AE4724564A33F3C65ABB1E38911EDAD99903E2BAF524171093F16D3A.png[/IMG]

Notification on device side

[IMG="https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/647/156/2640091000001647156.20200814114018.61053633353792838351478924613335:50510826022009:2800:E1197177A5FF14B55D26765B4F0B499CAB77B1215DBE1BB7441EC112397AABF3.gif"]https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/647/156/2640091000001647156.20200814114018.61053633353792838351478924613335:50510826022009:2800:E1197177A5FF14B55D26765B4F0B499CAB77B1215DBE1BB7441EC112397AABF3.gif[/IMG]

Goal

Our goal here is to subscribe, unsubscribe and send notification using topic-based message sending, also when user will tap the notification it will take user to a specific page. All this will be done using our local server side.

Server Side

Obtaining app-level access token API

The request header uses AccessToken for authentication, which is obtained using the service API provided by the open platform. The service API provides two modes to obtain AccessToken: authorization code mode and client password mode. This API uses the client password mode.

Do not apply for a new app-level access token each time before the server API is called. Frequent application requests may trigger rejection, leading to application failure within a specified period. Each access token has a validity period.

Within the validity period, it can be used repeatedly. You are advised to apply for an access token again, only when the server API is accessed and HTTP result code 401 is return

var request = require("request");

const getAppToken = (callBack) => {

var options = {

method: 'POST',

url: 'https://oauth-login.cloud.huawei.com/oauth2/v3/token',

headers:

{

'content-type': 'application/x-www-form-urlencoded',

host: 'Login.cloud.huawei.com',

post: '/oauth2/v2/token HTTP/1.1'

},

form:

{

grant_type: "client_credentials",

client_secret: 'Put Your Client Secret Here...',

client_id: 'Put Your APP ID Here ...'

}

};

request(options, function (error, response, body) {

if (error) throw new Error(error);

var tokenValue = JSON.parse(body);

callBack(tokenValue.access_token);

});

}

exports.getAppToken = getAppToken;

Subscribe to a topic API

The API is used to subscribe to a topic for one or more users. A maximum of 1,000 tokens are allowed in each call request. Currently, this API only supports Android apps.

URL: https://push-api.cloud.huawei.com/v1/[appid]/topic:subscribe

API

subscribeToTopic.js

var request = require("request");

const subscribeToTopicNotify = (appLevelToken, tokenVal, topicSubscribeVal, callBack) => {

var options = {

method: 'POST',

url: 'https://push-api.cloud.huawei.com/v1/[appid]/topic:subscribe',

headers:

{

authorization: 'Bearer ' + appLevelToken,

host: 'oauth-login.cloud.huawei.com',

post: '/oauth2/v2/token HTTP/1.1',

'content-type': 'application/json'

},

body:

{

topic: topicSubscribeVal,

tokenArray: tokenVal

},

json: true

};

request(options, function (error, response, body) {

if (error) throw new Error(error);

// console.log(body);

var notify = JSON.parse(JSON.stringify(body));

// console.log(">>>"+notify.msg);

callBack(notify.msg);

});

}

exports.subscribeToTopicNotify = subscribeToTopicNotify;

app.js

app.post('/subscribeToTopic', (req, res, next) => {

// topicSubscribeVal = req.body.topic;

let topic = {

topic: req.body.topic,

};

console.log(topic.topic);

// Fetching Token from mongodb ...

dbase.collection('token').find().toArray((err, results) => {

if (results) {

//clear the token list ...

arrToken = [];

// adding token in the list ...

for (var i = 0; i < results.length; i++) {

console.log("Token " + i + " " + results[i].token);

arrToken.push(results[i].token);

}

// if error code 401 returned it means access token becomes invalid

// and we need to obtain a new token. Token Validity is 60 mins...

// fetchin app level access token here ...

appToken.getAppToken((callBack) => {

console.log("TOKEN >>>" + callBack);

appLevelAccesToken = callBack;

subscribeToTopic.subscribeToTopicNotify(appLevelAccesToken, arrToken, topic.topic,callBackMessage => {

notifySucesssMessage = callBackMessage;

console.log(notifySucesssMessage);

if(callBackMessage!=null){

res.send(callBackMessage);

}

});

});

}

});

});

Unsubscribe to a topic API

The API is used to unsubscribe to a topic for one or more users. A maximum of 1,000 tokens are allowed in each call request. Currently, this API only supports Android apps.

URL: https://push-api.cloud.huawei.com/v1/[appid]/topic:unsubscribe

API

unSubscribeToTopic.js

var request = require("request");

const unSubscribeToTopicNotify = (appLevelToken, tokenVal, topicSubscribeVal, callBack) => {

var options = {

method: 'POST',

url: 'https://push-api.cloud.huawei.com/v1/[appid]/topic:unsubscribe',

headers:

{

authorization: 'Bearer ' + appLevelToken,

host: 'oauth-login.cloud.huawei.com',

post: '/oauth2/v2/token HTTP/1.1',

'content-type': 'application/json'

},

body:

{

topic: topicSubscribeVal,

tokenArray: tokenVal

},

json: true

};

request(options, function (error, response, body) {

if (error) throw new Error(error);

// console.log(body);

var notify = JSON.parse(JSON.stringify(body));

// console.log(">>>"+notify.msg);

callBack(notify.msg);

});

}

exports.unSubscribeToTopicNotify = unSubscribeToTopicNotify;

app.js

// Push Kit unsubscribe to a topic ...

app.post('/unsubscribeToTopic', (req, res, next) => {

let topic = {

topic: req.body.topic,

};

// Fetching Token from mongodb ...

dbase.collection('token').find().toArray((err, results) => {

if (results) {

//clear the token list ...

arrToken = [];

// adding token in the list ...

for (var i = 0; i < results.length; i++) {

console.log("Token " + i + " " + results[i].token);

arrToken.push(results[i].token);

}

// if error code 401 returned it means access token becomes invalid

// and we need to obtain a new token. Token Validity is 60 mins...

// fetchin app level access token here ...

appToken.getAppToken((callBack) => {

console.log("TOKEN >>>" + callBack);

appLevelAccesToken = callBack;

unSubscribeToTopic.unSubscribeToTopicNotify(appLevelAccesToken, arrToken, topic.topic,callBackMessage => {

notifySucesssMessage = callBackMessage;

console.log(notifySucesssMessage);

if(callBackMessage!=null){

res.send(callBackMessage);

}

});

});

}

});

});

Querying the topic subscription list API

The API is used to query the topic subscription list of a token. Currently, this API only supports Android apps.

URL: https://push-api.cloud.huawei.com/v1/[appid]/topic:list

API

getTopicList.js

var request = require("request");

const getTopicList = (appLevelToken, tokenVal, callBack) => {

var options = {

method: 'POST',

url: 'https://push-api.cloud.huawei.com/v1/[appid]/topic:list',

headers:

{

authorization: 'Bearer ' + appLevelToken,

host: 'oauth-login.cloud.huawei.com',

post: '/oauth2/v2/token HTTP/1.1',

'content-type': 'application/json'

},

body:

{

token: tokenVal

},

json: true

};

request(options, function (error, response, body) {

if (error) throw new Error(error);

// console.log(body);

var notify = JSON.parse(JSON.stringify(body));

console.log(">>>"+notify);

callBack(notify.topics);

});

}

exports.getTopicList = getTopicList;

app.js

app.post('/getTopicList', (req, res, next) => {

console.log("CALLLLLING")

// Fetching Token from mongodb ...

dbase.collection('token').find().toArray((err, results) => {

if (results) {

//clear the token list ...

arrToken = [];

// adding token in the list ...

for (var i = 0; i < results.length; i++) {

console.log("Token " + i + " " + results[i].token);

arrToken.push(results[i].token);

}

var uniqueItems = Array.from(new Set(arrToken));

// if error code 401 returned it means access token becomes invalid

// and we need to obtain a new token. Token Validity is 60 mins...

// fetchin app level access token here ...

appToken.getAppToken((callBack) => {

console.log("TOKEN VA L >>>" + uniqueItems);

appLevelAccesToken = callBack;

getTopicList.getTopicList(appLevelAccesToken, uniqueItems[0],callBackMessage => {

notifySucesssMessage = callBackMessage;

console.log("MSG >>>>>>>>>"+notifySucesssMessage);

res.send(notifySucesssMessage);

});

});

}

});

});

Sending notification using topic subscription API

The API is used to send notification using topic subscription, also an intent to send user to specific page. In this case we are sending URL as a data in an intent which will make user to view the website in android WebActivity page on taping the notification.

URL: https://push-api.cloud.huawei.com/v1/[appid]/messages:send

This is not the end. For full content, you can visit https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201327882870070045&fid=0101187876626530001