Backend service for ionic push - ionic-framework

I have implemented ionic push notifications using pushwoosh. But there I use the dashboard which has provided by pushwoosh to send push notifications. I wanted to send push notifications using a back end which has created by my self. How do I do that?

i am working on ionic-framework and also using push notification to sent notification via REST API using node-gcm its working fine.
sample code
(function() {
function execute(rqst, q, fwk) {
var gcm = require('node-gcm');
var message = new gcm.Message();
message.timeToLive = 3000;
message.addData({
title: 'Push Notification Sample',
body: 'Abnormal data access',
icon: 'ic_launcher',
message: '"\u270C Peace, Love \u2764 and PhoneGap \u2706!'
});
message.addNotification({
title: 'Push Notification Sample',
body: 'Abnormal data access',
icon: 'ic_launcher',
message: 'hey , how are you?'
});
/* message.addData('message', "\u270C Peace, Love \u2764 and PhoneGap \u2706!");
message.addData('title', 'Push Notification Sample');
message.addData('msgcnt', '3');*/
// Duration in seconds to hold in GCM and retry before timing out. Default 4 weeks (2,419,200 seconds) if not specified.
// Set up the sender with you API key
var sender = new gcm.Sender('xxxxxxxxxxxxxxxxx-hK5wE');
// Add the registration IDs of the devices you want to send to
var registrationIds = [];
registrationIds.push('APA91bEWB6-xcrfrfrffr-LqyMohLP4T-XuydQgt44Q6Acw5kmVDWvAaOsm1CriASm02SyBceZ2NBWF4FIES7grcPeY5v4fLQme2UqhRteeWRdD_Ma25QMGESOGAyw_Uhgg_EjkTl-');
// Send the message
// ... trying only once sendNoRetry
sender.send(message, {
registrationIds: registrationIds
}, function(err, result) {
if (err) {
console.error(err);
q.resolve({
status: 200,
data: {
data: err,
code: 1
}
});
} else {
console.log(result);
q.resolve({
status: 200,
data: result
});
}
});
}
return exports.execute = execute;
})();

Related

how to send post data with inappbrowser ionic 4

I need to know how you can send data by post via inappbrowser to an external url that is a payment gateway
I am dealing with the property of ionic execute Script however I have not managed to pass the post data, I would like to see if there is another way but I need to use inappbrowser
let options: InAppBrowserOptions={
zoom:'no',clearcache:'yes',hidden:'yes',hidenavigationbuttons:'yes',hideurlbar:'yes'
};
let customheader= 'foo:123,bar:456';
const browser= this.iab.create('https://url_anyway','_blank',options);
browser.on('loadstop').subscribe( (ev: InAppBrowserEvent) => {
browser.executeScript({code: "(function() {const data = new FormData(document.getElementById('mp_account'));fetch('https://url_anyway', { method: 'POST', body: data}).then(function(response) { if(response.ok) { return response.text() } else { throw 'Error en la llamada Ajax';}}).then(function(texto) { console.log(texto);}).catch(function(err) { console.log(err);}); })()"}).then( function(){
setTimeout(function(){
browser.show();
;}, 1500);
});
});
when opening the url does not show anything by post method

Sending voip push notification from one signal triggered firebase cloud functions

I`m trying to send Voip push notification from one signal triggered by firebase cloud functions. So far it being able to send normal message push notifications from one signal to IOS devices using firebase cloud functions with below code.
var sendNotification = function(data) {
var headers = {
"Content-Type": "application/json; charset=utf-8"
};
var options = {
host: "onesignal.com",
port: 443,
path: "/api/v1/notifications",
method: "POST",
headers: headers
};
var https = require('https');
var req = https.request(options, function(res) {
res.on('data', function(data) {
console.log("Response:");
console.log(JSON.parse(data));
});
});
req.on('error', function(e) {
console.log("ERROR:");
console.log(e);
});
req.write(JSON.stringify(data));
req.end();
};
var message = {
app_id: "*********************",
contents: {"en": "English Message"},
include_player_ids: ["******************7b0bdc38"]
};
sendNotification(message);
Does anyone know how to send Voip push notifications from one signal using firebase cloud functions??
(If the above code is required to change some part of it, it would be very thankful telling me where it is.)
As per one signal documentation (https://documentation.onesignal.com/docs/voip-notifications) you are missing the DEVICE_VOIP_TOKEN that you should have received from the iOS application.
Please try adding that and let me know, think of adding the exact error message if any.

403 on Google Action push notification request

I'm trying to perform a push notification for Google Actions Intent.
Thus far, I've followed the instructions here: https://developers.google.com/actions/assistant/updates/notifications#send_notifications
This is my resulting code:
const {google} = require('googleapis');
var request = require('request');
const key = require('./bot.json');
module.exports = async function (context, myQueueItem) {
context.log('JavaScript queue trigger function processed work item', myQueueItem);
let jwtClient = new google.auth.JWT(
key.client_email, null, key.private_key,
['https://www.googleapis.com/auth/actions.fulfillment.conversation'],
null
);
jwtClient.authorize((err, tokens) => {
// code to retrieve target userId and intent
let notif = {
userNotification: {
title: [message],
},
target: {
userId:[obtained from permission request],
intent: [name of intent],
// Expects a IETF BCP-47 language code (i.e. en-US)
locale: 'en-US'
},
};
request.post('https://actions.googleapis.com/v2/conversations:send', {
'auth': {
'bearer': tokens.access_token,
},
'json': true,
'body': {'customPushMessage': notif},
}, (err, httpResponse, body) => {
console.log(body);
console.log(httpResponse.statusCode + ': ' + httpResponse.statusMessage);
});
});
};
//module.exports(console, "Test");
This results in a 403 from the notification service. Is this because of the user id, intent name or jwtoken that was generated?
Following are the steps we need to check before sending the push notification
Check your Google permission settings
In order to test the Action, you need to enable the necessary permissions.
Go to the ‘Activity Controls' page (https://myaccount.google.com/activitycontrols).
Sign in with your Google account, if you have not already done so.
Ensure that the following permissions are enabled:
a.Web & App Activity
b.Device Information
c.Voice & Audio Activity
2.Target intent name should be added into the Implicit invocation field.
with enabled push notification.
3.use the same email id in your google assistant which you had used for login in GCP.

How we do Exception handling in protractor-cucumber and do a email notification

I am using Protractor-Cucumber framework with protractor 5.2.2 and cucumber 3.2. I have a requirement of posting in no.of locations. So I have written a script in a loop for it. But it randomly fails before completing the loop. So when the script ends abnormally, is there like an exception handling section that gets control before exiting.The script can be fail due to any of the reasons like web driver issue,NoSuchElementError,ElementIsNotIntractable,ElementIsNotVisible etc.So whatever be the issue I have to handle that, and if it fails, I have to do an email notification. I have tried try catch, as given below, but it does not work for me.
When(/^I login$/, function () {
try{
element(by.css(".signin")).click();
var count=post_details.length ;
for (var i=0; i<count; i++){
post();
}
}
catch(e){
console.log("failed");
}
});
How we can do this in protractor-cucumber.Thanks in advance
For the exception problem you can try this. ignoreUncaughtException
For the email part create a hooks.js file. Here you can setup the After() function, to check your scenario fails or not. Cucumber Docs.
Example:
After(function (scenario) {
if (scenario.result.status === Status.FAILED)
{
failed = true;
const attach = this.attach;
//creates a screenshot for the report
return browser.takeScreenshot().then(function(png) {
return attach(new Buffer(png, "base64"), "image/png");
});
}
});
Then you can use nodemailer to send messages. Nodemailer
In your AfterAll() function you can handle the send part.
Example:
AfterAll(function(callback){
console.log("AfterAll");
if (failed)
{
var transporter = nodemailer.createTransport(
{
host: 'host.com',
port: xx,
secure: false,
//proxy: 'http://10.10.10.6:1098',
auth: {
user: userMail,
pass: pw
}
});
var mailOptions = {
from: 'xx', // sender address (who sends)
to: xxxxxx#mail.com',
subject: 'your subject', // Subject line
text: 'Your test failed....', // plaintext body
/*attachments: [
{
filename: 'report.html',
path: htmlReport,
}]*/
};
transporter.sendMail(mailOptions, function(error, info)
{
if(error)
{
return console.log(error);
}
console.log('Email sent: ' + info.response);
console.log(info);
});
} else {
//do your stuff
}
setTimeout(callback, 2000);
});

How to use botkit with facebook and wit.ai

I am a novice in chatbot development and I would like some help.
While it seems quite simple to connect botkit with facebook messenger and wit.ai in orger to use NLP. I haven't managed to do so. My initial goal is to have a simple conversation like hello-hello but using wit.ai as middleware.
Below I attach the code. What it should do is receive a "hello" message, pass it to wit.ai and then respond "I heard hello!" as a reply (without using wit at this stage). Instead I just receive
debug: RECEIVED MESSAGE
debug: CUSTOM FIND CONVO XXXXXXXXXXXXXX XXXXXXXXXXXXXX
debug: No handler for message_received
after every message I send to facebook messenger bot. In wit it seems like I am getting the messages since I receive messages in my inbox to update the intents.
If there is any code much simpler than the one below I would be very happy to have it so that I can start with something much simpler :).
Thanks
<pre><code>
if (!process.env.page_token) {
console.log('Error: Specify page_token in environment');
process.exit(1);
}
if (!process.env.page_token) {
console.log('Error: Specify page_token in environment');
process.exit(1);
}
if (!process.env.verify_token) {
console.log('Error: Specify verify_token in environment');
process.exit(1);
}
if (!process.env.app_secret) {
console.log('Error: Specify app_secret in environment');
process.exit(1);
}
var Botkit = require('./lib/Botkit.js');
var wit = require('./node_modules/botkit-middleware-witai')({
token: process.env.wit,
minConfidence: 0.6,
logLevel: 'debug'
});
var os = require('os');
var commandLineArgs = require('command-line-args');
var localtunnel = require('localtunnel');
const ops = commandLineArgs([
{name: 'lt', alias: 'l', args: 1, description: 'Use localtunnel.me to make your bot available on the web.',
type: Boolean, defaultValue: false},
{name: 'ltsubdomain', alias: 's', args: 1,
description: 'Custom subdomain for the localtunnel.me URL. This option can only be used together with --lt.',
type: String, defaultValue: null},
]);
if(ops.lt === false && ops.ltsubdomain !== null) {
console.log("error: --ltsubdomain can only be used together with --lt.");
process.exit();
}
var controller = Botkit.facebookbot({
debug: true,
log: true,
access_token: process.env.page_token,
verify_token: process.env.verify_token,
app_secret: process.env.app_secret,
validate_requests: true, // Refuse any requests that don't come from FB on your receive webhook, must provide FB_APP_SECRET in environment variables
});
var bot = controller.spawn({
});
controller.setupWebserver(process.env.port || 3000, function(err, webserver) {
controller.createWebhookEndpoints(webserver, bot, function() {
console.log('ONLINE!');
if(ops.lt) {
var tunnel = localtunnel(process.env.port || 3000, {subdomain: ops.ltsubdomain}, function(err, tunnel) {
if (err) {
console.log(err);
process.exit();
}
console.log("Your bot is available on the web at the following URL: " + tunnel.url + '/facebook/receive');
});
tunnel.on('close', function() {
console.log("Your bot is no longer available on the web at the localtunnnel.me URL.");
process.exit();
});
}
});
});
controller.middleware.receive.use(wit.receive);
controller.hears(['hello'], 'direct_message', wit.hears, function(bot, message) {
bot.reply(message, 'I heard hello!');
});
function formatUptime(uptime) {
var unit = 'second';
if (uptime > 60) {
uptime = uptime / 60;
unit = 'minute';
}
if (uptime > 60) {
uptime = uptime / 60;
unit = 'hour';
}
if (uptime != 1) {
unit = unit + 's';
}
uptime = uptime + ' ' + unit;
return uptime;
}
Make sure you have a few conversations in Wit.ai beforehand so for example hello there and highlight the hello in that statement as something like, greetings.
Now i'm not sure what your intents are called in wit.ai but in your statement controller.hears(['hello'] you're actually listening to the wit.ai intents. So in the example i mentioned above, we'd be using hears(['greetings']) since that's the intent in wit.ai.
Also, instead of using direct_message use message_received this is what it should look like:
controller.hears(['hello'], 'message_received', wit.hears, function(bot, message) {
bot.reply(message, 'I heard hello!');
});
If you're struggling tracking down the problem you can stick a console statement in your controller so something like console.log("Wit.ai detected entities", message.entities); and see what you get back from that.
Let me know if you're still having any issues :)