Implementation of Amazon SNS push notification to android device using aws-sdk package in NodeJS. I have few implementations mentioned below. Mobile device is displaying push notifications. I want to send data and notification object in payload.
let payload2 = JSON.stringify({
default: 'Naresh',
GCM: JSON.stringify({
notification : {
body : 'great match!',
title : 'Portugal vs. Denmark'
},
data:{
testdata: 'Check out these awesome deals!',
url: 'www.amazon.com'
}
})
});
It's not sending push notifications.
let payload1 = {
"GCM": "{
\"notification\": {
\"title\": \"this one last test in app\",
\"body\": \"mm hello tests\"
},
\"data\": {
\"turnclass\": \"efwfwe\",
\"flight\": \"truejet\"}
}"
};
It's sending push notifications.
sns.publish({ TargetArn: targetArn,
Message: payload1,
MessageStructure: 'json'
}, (error, data) => (error) ? reject(error) : resolve(data));
What is right format to send push notifications?
According to documentation:
When sending platform-specific payloads in messages using the Amazon
SNS console, the data must be key-value pair strings and formatted as
JSON with quotation marks escaped.
Example:
{
"GCM":"{
"data":{
"message":"Check out these awesome deals!",
"url":"www.amazon.com"
}
}"
}
What you are doing in the first payload produces the following output:
{"default":"Naresh","GCM":"{\"notification\":{\"body\":\"great match!\",\"title\":\"Portugal vs. Denmark\"},\"data\":{\"testdata\":\"Check out these awesome deals!\",\"url\":\"www.amazon.com\"}}"}
And that is not a valid format. That happens because you're double JSON.stringify a part of your object. So if you do:
let payload2 = JSON.stringify({
default: 'Naresh',
GCM: {
notification: {
body: 'great match!',
title: 'Portugal vs. Denmark'
},
data: {
testdata: 'Check out these awesome deals!',
url: 'www.amazon.com'
}
}
});
It will produce:
{"default":"Naresh","GCM":{"notification":{"body":"great match!","title":"Portugal vs. Denmark"},"data":{"testdata":"Check out these awesome deals!","url":"www.amazon.com"}}}
Which should work as expected.
Related
I visited the Youtube Data v3 API docs to know about how to upload videos using the client library
I got to this page
https://developers.google.com/youtube/v3/docs/videos/insert
but it doesn't seem to explain where to put the video in the request
And Also API explorer just gives the code for request, it doesn't let me execute the code for that page
I also read the resource structure page but didn't find where to put the video
https://developers.google.com/youtube/v3/docs/videos#resource
here's my current code
let req = gapi.client.youtube.videos.insert({
part: 'snippet,status',
snippet: {
title: "Test Video",
description: "Test Description",
categoryId: 28,
defaultLanguage: 'en',
defaultAudioLanguage: 'en'
},
status: {
privacyStatus: "private"
},
});
console.log(req)
try {
req.execute(function (response) {
console.log(response);
});
} catch (e) {
console.error(e);
}
Now, where do I put the video in the request?
do I have to put that as buffer?
I am fetching video from fetch API for uploading via API
and whenever I run the code I get the Error: 400 in the console
code: 400
data: [{…}]
error: {code: 400, data: Array(1), message: 'Request contains an invalid argument.'}
message: "Request contains an invalid argument."
so can you provide a working example of uploading a video using the client library that is fetched from the fetch API
and show to structure the request body when using the client library?
This is the request body I'm using. Code below was taken from this sample script: https://quanticdev.com/articles/automating-my-youtube-uploads-using-nodejs/
In my case I'm uploading an .mp4
auth: auth,
part: 'snippet,status',
requestBody: {
snippet: {
title,
description,
tags,
categoryId: 20,
defaultLanguage: 'en',
defaultAudioLanguage: 'en'
},
status: {
privacyStatus: "public",
selfDeclaredMadeForKids: false
},
},
media: {
body: fs.createReadStream(videoPath),
}
I want to respond to an inline query but there is no response from my bot. However, Telegram returns {"ok":true,"result":true} as the HTTP response. Here's my Google Apps Script code:
var execute = "https://api.telegram.org/bot" + token + "/";
function answerInlineQuery(id,text){
var output = {
method: "post",
payload: {
method: "answerInlineQuery",
inline_query_id: id,
result: [{
type: "article",
id: id,
title: "This is a title",
description: text,
input_message_content: {
message_text: text,
},
}]
}
};
UrlFetchApp.fetch(execute,output);
}
How do I solve this? Is there something wrong with my code? Or is there something to do with the bot settings (BotFather)?
In case you need a demonstration of the problem, try the bot yourself by using an inline query (type #ClearTheBot [something] in any chat).
https://t.me/ClearTheBot
Please kindly change output.payload.results[0].id to 1 and/or JSON.stringify(output.payload.result)
I am fetching some data from an api and I want to map through it inorder to get all the values inside . But I am unable to do so . Need some help.
Here's the data :
{
'id:5': {
1: {
coinid: 5,
coinname: 'Chainlink',
publishedAt: '2021-06-24T11:10:54Z',
source: 'Cointelegraph',
title:
'asset manager qr launches bitcoin etf on brazilian stock exchange',
description:
'in contrast to hashdexs crypto etf product qr asset managements product provides exposure to bitcoin exclusively',
url: 'https://cointelegraph.com/news/asset-manager-qr-launches-bitcoin-etf-on-brazilian-stock-exchange',
},
2: {
coinid: 5,
coinname: 'Chainlink',
publishedAt: '2021-06-24T13:39:56Z',
source: 'Business Wire',
title:
'truefi announces new integrations with binance chainlink and sushiswap further embedding into the defi ecosystem',
description:
'san franciscobusiness wire binancetrusttoken announces a suite of deep defi integrations designed to make the truefi platform safer more robust and more lucrative for its users',
url: 'https://www.businesswire.com/news/home/20210624005642/en/TrueFi-Announces-New-Integrations-With-Bina',
},
}
and here is my code for fetching api ( I have to unescape the api data coz it was in escaped form) :
const fetchNews = async () => {
try {
const { data } = await axios.get(
'https://h3iiccq04i.execute-api.ap-south-1.amazonaws.com/dev',
);
console.log(JSON.parse(data));
// setNewsData(JSON.parse(data));
setLoading(false);
} catch (err) {
console.log(err.message);
}
};
here the newsData is an object which I have to map and get all the values such as coinname ,url ,etc . Any help would be really appreciated .
We could use Object.values() to get in an array with all the object values and then iterate over it with a map.
const dataArray = Object.values(data['id:5'])
dataArray.map(...)
According to the react-native-fcm package you can include a custom nested object within the data object for a FCM messaging payload.
according to this post by the package author
Like this:
var payload = {
data: {
custom_notification: {
title: 'title',
body: 'body',
priority: 'high',
id: 'id',
group: 'group'
}
}
};
This is for the purpose of receiving heads up notifications in all app states, which will not happen if you do just a notification payload or data payload.
When I implement this in my cloud function I get the following error:
Error: Messaging payload contains an invalid value for the "data.custom_notification" property. Values must be strings.
So I'm at a loss as to how others can be using this successfully?
I wonder if there's some issue going on with my environment or something as the following test payload which was given to me by firebase support (and is in the docs) errors out:
var payload = {
"to":"FCM_TOKEN",
"data": {
"type":"MEASURE_CHANGE",
"body": "test body",
"title": "test title",
"color":"#00ACD4",
"priority":"high",
"id": "id",
"show_in_foreground": true
}
};
I get the following error:
Error sending message stringify: {"code":"messaging/invalid-payload","message":"Messaging payload contains an invalid \"to\" property. Valid properties are \"data\" and \"notification\"."}
Been at this for days so hopefully I can get a bit of help on this.
Thanks in advance!
So I realised just now (after days of searching) that the package react-native-fcm is using a different send method than admin.messaging().sendToDevice(token, payload, options). I had been using that for a while now and didn't realize that it was not actually what was intended to be used with this library or atleast in this scenario. Mainly because everything was working fairly well using admin.messaging() up until I wanted heads up notifications in all app states.
The other method is like this
sendData(token) {
let body = {
"to": token,
"data":{
"title": "Simple FCM Client",
"body": "This is a notification with only DATA.",
"sound": "default",
"click_action": "fcm.ACTION.HELLO",
"remote": true
},
"priority": "normal"
}
this._send(JSON.stringify(body), "data");
}
_send(body, type) {
let headers = new Headers({
"Content-Type": "application/json",
"Content-Length": parseInt(body.length),
"Authorization": "key=" + FirebaseConstants.KEY
});
fetch(API_URL, { method: "POST", headers, body })
.then(response => console.log("Send " + type + " response", response))
.catch(error => console.log("Error sending " + type, error));
}
You can use nested objects within the data object using this method. The documentation is not super clear on this unfortunately, I didn't even realise there was an example until now. Of course this could have just been me.
When using the data message payload, it is stated to use key value pairs that are String, so what you could do is have the value of your custom_notification as JSON String by enclosing them in " ".
For the sample payload provided, are you actually using the FCM_TOKEN in the to parameter? You're supposed to replace it with an actual token.
When I try to create an envelope from a template I get a response of:
{ errorCode: 'UNSPECIFIED_ERROR',
message: 'Non-static method requires a target.' }
Here's what I'm doing so far:
First I login, which returns
{ loginAccounts:
[ { name: '*****',
accountId: '*****',
baseUrl: 'https://demo.docusign.net/restapi/v2/accounts/******',
isDefault: 'true',
userName: '***** ********',
userId: '*******-*****-*****-*****-*********',
email: '********#*******.com',
siteDescription: '' } ] }
So then I take the baseUrl out of that response and I attempt to create the envelope. I'm using the hapi framework and async.waterfall of the async library, so for anyone unfamiliar with either of these my use of the async library uses the next callback to call the next function which in this case would be to get the url for the iframe, and with our usage of the hapi framework AppServer.Wreck is roughy equivalent to request:
function prepareEnvelope(baseUrl, next) {
var createEntitlementTemplateId = "99C44F50-2C97-4074-896B-2454969CAEF7";
var getEnvelopeUrl = baseUrl + "/envelopes";
var options = {
headers: {
"X-DocuSign-Authentication": JSON.stringify(authHeader),
"Content-Type": "application/json",
"Accept": "application/json",
"Content-Disposition": "form-data"
},
body : JSON.stringify({
status: "sent",
emailSubject: "Test email subject",
emailBlurb: "My email blurb",
templateId: createEntitlementTemplateId,
templateRoles: [
{
email: "anemailaddress#gmail.com",
name: "Recipient Name",
roleName: "Signer1",
clientUserId: "1099", // TODO: replace with the user's id
tabs : {
textTabs : [
{
tabLabel : "acct_nmbr",
value : "123456"
},
{
tabLabel : "hm_phn_nmbr",
value : "8005882300"
},
{
tabLabel : "nm",
value : "Mr Foo Bar"
}
]
}
}
]
})
};
console.log("--------> options: ", options); // REMOVE THIS ====
AppServer.Wreck.post(getEnvelopeUrl, options, function(err, res, body) {
console.log("Request Envelope Result: \r\n", JSON.parse(body));
next(null, body, baseUrl);
});
}
And what I get back is:
{ errorCode: 'UNSPECIFIED_ERROR',
message: 'Non-static method requires a target.' }
From a little googling it look like 'Non-static method requires a target.' is a C# error and doesn't really give me much indication of what part of my configuration object is wrong.
I've tried a simpler version of this call stripping out all of the tabs and clientUserId and I get the same response.
I created my template on the Docusign website and I haven't ruled out that something is set up incorrectly there. I created a template, confirmed that Docusign noticed the named form fields, and created a 'placeholder' templateRole.
Here's the templateRole placeholder:
Here's one of the named fields that I want to populate and corresponding data label:
As a side note, I was able to get the basic vanilla example working without named fields nor using a template using the docusign node package just fine but I didn't see any way to use tabs with named form fields with the library and decided that I'd rather have more fine-grained control over what I'm doing anyway and so I opted for just hitting the APIs.
Surprisingly when I search SO for the errorCode and message I'm getting I could only find one post without a resolution :/
Of course any help will be greatly appreciated. Please don't hesitate to let me know if you need any additional information.
Once I received feedback from Docusign that my api call had an empty body it didn't take but a couple minutes for me to realize that the issue was my options object containing a body property rather than a payload property, as is done in the hapi framework.