GCP Cloud Function for Slash command not working - node.js

so i'm trying to make an slash command on my slack using nodejs and Cloud Functions. I'm getting error 403 when the slash command goes out to the function, but i'm having problems to identify why it's giving me the error.
The code of the function is this:
const { WebClient } = require('#slack/web-api');
exports.slashCommand = (req, res) => {
// Verify that the request is coming from Slack
if (!req.body.token || req.body.token !== process.env.SLACK_TOKEN) {
res.status(403).end();
return;
}
// Parse the request body and extract the Slack user ID, command text, and response URL
const { user_id, text, response_url } = req.body;
// Use the Slack Web API client to post a message to the response URL
const web = new WebClient();
web.chat.postMessage({
channel: user_id,
blocks: [
{
type: 'section',
text: {
type: 'plain_text',
text: 'This is a section block'
}
},
{
type: 'divider'
},
{
type: 'section',
fields: [
{
type: 'plain_text',
text: 'This is a field'
},
{
type: 'plain_text',
text: 'This is another field'
}
]
}
]
});
// Send a 200 OK response to acknowledge receipt of the request
res.status(200).end();
};
I'm using nodeJS 18 to build
I also created gen 1 and gen2 with the same code, but the problem persists. I've given permission to allUsers to call the URL, but still no go. My SLACK_TOKEN is configured in the env. I'm suspecting that's something in the payload but i'm not understanding why this is happening. ( i'm new to this, so i'm sorry for the lack of details, if theres something i should add, let me know ).
Tried to give permission to allUsers, and still getting error. I'm really struggling to make slack validate the payload so my guess is the code checking if the payload and the token is valid is breaking everything.

Related

Stripe "Missing required param: line_items[0][currency]." Node js

I'm creating subscription on node js backend. It had been working good but today I got this error. I didn't made any changes in code - it just starts returning this error.
backend code:
app.post('/api/subscription', async (req, res) => {
const { priceId } = req.body;
try {
const session = await stripe.checkout.sessions.create({
mode: "subscription",
payment_method_types: ["card"],
line_items: [
{
price: priceId,
// For metered billing, do not pass quantity
quantity: 1,
},
],
// {CHECKOUT_SESSION_ID} is a string literal; do not change it!
// the actual Session ID is returned in the query parameter when your customer
// is redirected to the success page.
success_url: 'https://someurl',
cancel_url: 'https://someurl',
});
res.send({
sessionId: session.id,
});
} catch (e) {
console.log(e)
res.status(400);
return res.send({
error: {
message: e.message,
}
});
}
})
from client I'm sending
fetch("http://localhost:8000/api/subscription", {
method: "POST",
body: JSON.stringify({ priceId }),
});
I've taken this code from official stripe example here https://stripe.com/docs/billing/subscriptions/checkout
And as I said it works fine, and now I've tested it on two different stripe accounts and getting the same error. It looks like something changed on stripe but not in their documentation
If priceId is undefined/null it won't be sent in the request. If the Price isn't present the API assumes you're trying to specify information about a line item without using a Price, and one of the first checks it performs is for a valid currency (which you don't have), which results in the Missing required param: line_items[0][currency]. error.
To fix the issue you'll need to figure out why priceId isn't being populated as expected, and you may also want to add a check to make sure priceId is valid before proceeding to the Checkout Session creation step.

Firebase fcm sendMulticast Error: "Exactly one of topic, token or condition is required"

I am using version 7.2.0 of firebase admin to send fcm push notification, using sendMutlicast method:
async function sendPushRequest({tokens, title, body, customData}) => {
const message = {
notification: {
title,
body,
},
data: customData,
tokens,
}
return firebase.messaging().sendMulticast(message)
}
This is the error I am getting
Error: Exactly one of topic, token or condition is required
at FirebaseMessagingError.Error (native)
at FirebaseMessagingError.FirebaseError [as constructor] (/user_code/node_modules/firebase-admin/lib/utils/error.js:39:28)
...
I tried logging the data and here is the object that sendPushRequest function is called with:
{
tokens: [ null, null, null, 'home-test', null, null ], // this one is a recent sample, I've been getting this error for a while now
title: 'some string',
body: 'some other string',
customData: {
title: 'some string',
body: 'some other string',
bigText: 'again another string',
color: '#9f0e27',
smallIcon: 'notificon',
sound: 'default'
}
}
I'm not sure what is causing the error!
I struggled with this problem too, its quite difficult to configure google admin firebase in nodejs. I find out there is a package that can handle this nicely.
https://www.npmjs.com/package/fcm-notification
but it has some little problem . you can not pass it multiple firebase configuration. here is some example :
const fcm = require('fcm-notification');
const fcm_key = require('../config/customer/fcm.json');
const FcM = new fcm(fcm_key);
module.exports.sendToSingleUser = async (message, token) => {
let message_body = {
notification: {
...message
},
token: token
};
FcM.send(message_body, function (err, response) {
if (err) {
return err
} else {
return response
}
})
}
Facing this error too. Figure out that our tokens array contains null or undefiend value. Resolved by remove that from tokens array and everything works fine.

TEAMS bot in node.js: 'Authorization has been denied for this request' in CreateConversation method

I have a TEAMS node.js bot running locally (with ngrok). I receive messages from TEAMS client and echo works
context.sendActivity(`You said '${context.activity.text}'`);
Now I want to send a 1to1 message to this user, but I receive
Error: Authorization has been denied for this request
when creating a conversation.
My code:
var sUserId = "29:1shb_5I6CkkerBVq4qPqcv5dGwDfkXx11Jbjc1UnGCIv"
var sServiceUrl = "https://smba.trafficmanager.net/emea/";
var sTenantId = "942369d2-208e-438b-894c-0d0e1510cf61";
var credentials = new BotConnector.MicrosoftAppCredentials({
appId: "xxxxxxx",
appPassword: "yyyyyyyy"
});
var connectorClient = new BotConnector.ConnectorClient(credentials, { baseUri: sServiceUrl });
const parameters = {
members: [ { id: sUserId } ],
isGroup: false,
channelData:
{
tenant: {
id: sTenantId
}
}
};
var conversationResource = await connectorClient.conversations.createConversation(parameters);
// I get the error here, next is not executed
await connectorClient.conversations.sendToConversation(conversationResource.id, {
type: "message",
from: { id: "xxxxxxx" },
recipient: { id: sUserId },
text: 'This a message from Bot Connector Client (NodeJS)'
});
appId & appPassword are valid (from .env file), if they are wrong I can not receive messages from TEAMS client
I have the same code to create a conversation in a .NET bot and it works for me:
var parameters = new ConversationParameters
{
Members = new[] { new ChannelAccount(sUserId) },
ChannelData = new TeamsChannelData
{
Tenant = new TenantInfo(sTenantId),
},
};
retValue = await connectorClient.Conversations.CreateConversationAsync(parameters);
What is wrong in my node.js code?
Thanks,
Diego
Have you trusted the service? It don't think so based on your code, and it's a classic cause of 401 in your case.
In node.js, do the following:
MicrosoftAppCredentials.trustServiceUrl(serviceUrl);
If you want more details around that, have a look to the documentation about getting 401 when sending proactive messages here
And also this SO answer about Teams and Proactive messaging, in particular last block.
Proactive messaging bot in Teams without mentioning the bot beforehand

How to get `fcm_options.link` functioning in firebase web notifications

I'm trying to get my FCM web notifications to contain a clickable link to my site, using the firebase admin SDK (version 7.0.0) for node.js. As far as I can tell I'm following the documentation to a T, but I'm unable to get the link working. To clarify, my notifications are working fine otherwise, it's just the link that I haven't got to work.
The documentation states:
For notification messages sent from the app server, the FCM JavaScript API supports the fcm_options.link key. Typically this is set to a page in your web app
I've included webpush.fcm_options.link inside my notification message. I've made sure to include an explicit notification payload in my message, as the documentation states that data messages don't support fcm_options.link.
Here's the structure of my message currently:
{
notification: {
title: 'Title',
body: 'Body',
},
data: {
// my data here
},
webpush: {
notification: {
requireInteraction: true,
icon: '/icons/notification.png'
},
fcm_options: {
link: 'https://example.com/'
}
},
// android: {},
// apns: {},
topic: 'sometopic'
};
Here's the function I'm using to send the message:
const admin = require('firebase-admin')
const sendMessage = message => {
admin
.messaging()
.send(message)
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
});
};
The link property should be working according to the documentation: my url includes https and my notification is being sent from the app server, and includes an explicit notification payload. At the moment, clicking on the notification just makes it disappear, with nothing else happening.
UPDATE: I worked out what the issue was - my service worker was using the importScripts function, but I was using an out-of-date version of the firebase script that didn't support fcm_options.link. I changed it to my current version of firebase (5.8.5) and it works. All sorted!
in notification try This
"notification":{
"title":"IssA",
"body":"Lafi",
"icon": "Icon URL",
"click_action": "Your URL here"
}
In the last version, using firebase admin in node js, this is the right configuration:
var message = {
notification: {
title: "",
body: ""
},
webpush: {
fcmOptions: {
link: "https://yourlink.web.app"
}
}
};

braintree + NodeJS gives an "authentication Error "

I'm trying to build a payment gateway library using braintree's NodeJS library, I'm making an ajax call from front end with the card data.
Client-Side
var card_data = {
type: "AmEx",
number: "3XXXXXXXXXXXXXX",
expire_month: "XX",
expire_year: "201X",
cvv2: "XXX",
name: "sandeep",
price : "200",
currency : "USD"
};
Ajax call,
$.ajax({
method: "GET",
url: "http://localhost:3000/paymentPath_braintree",
data: card_data
}).done(function(message){
console.log(message);
}).fail(function(data, message){
console.log(message);
});
Server-Side
var braintreePay = require('braintree');
app.get("/payment_braintree", function(request, response){
var data = request.query;
var gateway = braintreePay.connect({
environment: braintreePay.Environment.Sandbox,
merchantId: "MymerchentID",
publicKey: "MypublicKey",
privateKey: "MyprivateKey",
});
var saleRequest = {
amount: data.price,
creditCard: {
number: data.number,
cvv: data.cvv2,
expirationMonth: data.expire_month,
expirationYear: data.expire_year.slice(2),
cardHolder: data.name
},
options: {
submitForSettlement: true
}
};
gateway.transaction.sale(saleRequest, function(error, result){
if(error){
console.log(error.name);
throw error;
}
if(result.success){
response.send(result.transaction.id);
} else {
response.send(result.message);
}
});
});
I have cross checked everything, from keys and card data everything is in order but i am getting an error in callback after making gateway.transaction.sale(...); called Authentication Error . Which i tried to figure out for hours but could not get through.
error object is
authenticationError: Authentication Error
arguments: undefined
message: "Authentication Error"
name: "authenticationError"
stack: undefined
type: "authenticationError"
Where am i going wrong?
I have created an account sandbox.braintreegateway those key credentials are from the account that i have created, i din't create an app like how its done in paypal.
I am going through lack of understanding in Braintree integration.
Are their any proper documented resource.

Resources