Add Mailchimp susbscriber through Firebase Function - javascript

Scenario :
I'm trying to create a Firebase Function to add a subscriber to a Mailchimp list using the Mailchimp API but after three days of trying different methods I've had little luck.
Currently my function resembles:
exports.addSubscriber = functions.https.onRequest((req, res) => {
const Mailchimp = require('mailchimp-api-v3')
const mailchimp = new Mailchimp('MY_API_KEY');
mailchimp.post('/lists/'MY_LIST_ID'/members', {
"email_address": 'test#gmail.com',
"status": 'pending'
}).then(function(results) {
console.log('added new user to mailchimp list');
})
.catch(function(err) {
console.log(err);
})
return null
});
When I try to trigger the function it results in a 'crash' with Error: Cannot find module 'mailchimp-api-v3' in the logs.
I've already ran npm install mailchimp-api-v3 in my local Firebase
directory so the module should be available.
Where am I going wrong?
Is there a simpler way to use the Mailchimp API with Javascript?

Try to run
npm install mailchimp-api-v3 --save
It seams the above package is missing.

Related

Send a POST request by axios with firebase functions

I am trying to send a POST request via axios andfirebase cloud function while the body of the request in axios contains data from changes occured in realtime db using the functions but everytime I deploy my code I get the error:
Function failed on loading user code. This is likely due to a bug in the user code.
Error message: Error: please examine your function logs to see the error cause:
https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs. Additional
troubleshooting documentation can be found at
https://cloud.google.com/functions/docs/troubleshooting#logging. Please visit
https://cloud.google.com/functions/docs/troubleshooting for in-depth troubleshooting
documentation.
I am quite new to firebase functions so I really don't know what I am doing here even after having some research.
Code:
const functions = require("firebase-functions");
const axios = require("axios");
exports.newNodeDetected = functions.database
.ref("Orders/{userId}/{customerId}/{ordernum}/customername")
.onCreate((snapchot, context) => {
const order = snapchot.val();
const userId = context.params.userId;
console.log(userId + "AND CUS NAME IS" + order);
axios.post("http://something.com/data.php", {
username: userId,
title: "ttl",
message: "msg",
})
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
});
Just in case anyone had the same issue. I realized I was running my npm commands outside the functions folder, therefore the package.json wasn't getting edited and my libraries were not really getting downloaded.
Always be careful to use npm inside the functions folder!!

Firestore function deployment error when using Twilio

I'm trying to integrate Twilio into a triggered Firestore function. The problem I'm having is when I add this code, I am unable to deploy ANY functions. As far as I know this is how to use twilio inside a cloud function. At the top I have this and I think firebase doesn't like something here because ALL functions stop deploying with this code.
// Used to send text messages
const twilio = require('twilio')
// const accountSid = functions.config().twilio.sid
// const authToken = functions.config().twilio.token
/* eslint new-cap: ["error", { "newIsCap": false }] */
const client = new twilio('ACblahblahblah', 'ccblahblahblah') // sid and token
const twilioNumber = '+13344714571' // your twilio phone number
Within the triggered function I have this. But I don't think the issue is here:
return client.messages.create({
to: someNumber,
from: twilioNumber,
body: 'Some message.'
}).then((data) => {
console.log(data)
}).catch((error) => {
console.log(error)
})
I have a valid Twilio account set up. The function logs don't tell me much other than that the function cannot be initialized. What am I missing? Seems like this has worked for others.
Figured it out about 5 minutes after posting the question. I had not installed twilio in the functions folder but rather the root of the project. Once I executed
npm install twilio
in the functions folder, the functions started deploying. Too bad there was no error in the logs that said something like "required package is missing" or something like that.

nodejs-dialogflow library returning TypeError: dialogflow.SessionsClient is not a constructor

I am trying to make a script that takes input from the user, runs it through Dialogflow, then returns it back to the user. The platform I am taking input from only supports Node.js. I am hosting the bot through glitch.com, but I don't think that's what's causing the issue. I wanted to check on here before I submit a bug report onto the GitHub repo.
var bot = 'the platform i use to accept inputs and send outputs'
bot.on("message", async message => {
console.log(message.content); // Log chat to console for debugging/testing
if (message.content.indexOf(config.prefix) === 0) { // Message starts with your prefix
let msg = message.content.slice(config.prefix.length); // slice of the prefix on the message
let args = msg.split(" "); // break the message into part by spaces
let cmd = args[0].toLowerCase(); // set the first word as the command in lowercase just in case
args.shift(); // delete the first word from the args
// You can find your project ID in your Dialogflow agent settings
const projectId = process.env.PROJECT_ID; //https://dialogflow.com/docs/agents#settings
const sessionId = 'quickstart-session-id';
var query = msg;
const languageCode = 'en-US';
// Instantiate a DialogFlow client.
const dialogflow = require('dialogflow');
const sessionClient = new dialogflow.SessionsClient();
// Define session path
const sessionPath = sessionClient.sessionPath(projectId, sessionId);
// The text query request.
const request = {
session: sessionPath,
queryInput: {
text: {
text: query,
languageCode: languageCode,
},
},
};
// Send request and log result
sessionClient
.detectIntent(request)
.then(responses => {
console.log('Detected intent');
const result = responses[0].queryResult;
console.log(` Query: ${result.queryText}`);
console.log(` Response: ${result.fulfillmentText}`);
if (result.intent) {
console.log(` Intent: ${result.intent.displayName}`);
} else {
console.log(` No intent matched.`);
}
})
.catch(err => {
console.error('ERROR:', err);
});
}
return;
});
That is the relevant part of the code. For those wondering, the process.env.PROJECT_ID is something glitch.com uses for anything private. Because I don't want random people getting their hands on my project id, I hide it in there and glitch hides it from anyone I don't explicitly invite.
Every time I execute this and try to query the bot, it returns an error Uncaught Promise Error: TypeError: dialogflow.SessionsClient is not a constructor.
If someone can direct me to what I'm missing, or what the problem is, that would be great!
As per #google-cloud/dialogflow - npm
IMPORTANT NOTE
Version 2.0.0 renames dialogflow to #google-cloud/dialogflow on npm, along with introducing TypeScript types.
So to update the dialogflow to use latest version, first uninstall dialogflow and then install with following command:
npm uninstall dialogflow
npm i #google-cloud/dialogflow
Also, if you were using older version 1.2.0 of dialogflow before then in code, make following changes as per their sample or refer the sample from above link (in require and to get the sessionPath):
const dialogflow = require('#google-cloud/dialogflow');
const sessionPath = sessionClient.projectAgentSessionPath(
projectId,
sessionId
);
It worked fine for me after doing this without any errors.
I figured it out. After many many refreshes, I decided to look at the npm documentation for it. Turns out some idiot listed the earliest version as 4.0.3, and the latest version as 0.7.0. I needed to explicitly tell it to use version 0.7.0 in order for it to work. Thank goodness!
Mine worked by reinstalling the dialogflow package
npm uninstall dialogflow
npm install dialogflow --save
put the code inside try and catch block. In my case by doing this, this error was removed.

How to set up Stripe API for Parse Cloud Code

How do we set up Stripe API for Parse Cloud Code. I've managed to get the code working, but I'd like to edit it. The function below is "stripe.customers.create", it only works when I remove the source line. How can I request the token? I am also trying to connect the Stripe customer to the parse user.t
Parse.Cloud.define("customer", function(request, response){
stripe.customers.create({
description: request.params.description
//source: request.params.token
}, function(err, customer) {
if(err){
console.log(err);
response.error(err);
}
else{
console.log(customer);
response.success(customer);
}
});
});
I already answered this question before. You can find my here
The idea is that in parse-server you can install any npm module that you want so in my answer i explain how you can first install the stripe npm module and then call it from your cloud code function.

Npm Packages and Meteor

I am really struggling with Meteor and the NPM package node-linkedin.
I understand how NPM integration is supposed to work. I added NPM using Meteorite and node-linkedin to packages.js. I am then calling the NPM package through Meteor.require().
Here is my server/linkedin.js file:
function Linkedin(accessToken) {
this.linkedin = Meteor.require('node-linkedin')('api', 'secret', 'callback');
this.accessToken = accessToken;
this.linkedin.init(this.accessToken);
}
Linkedin.prototype.company = function() {
var self = this;
var data = Meteor.sync(function(done) {
self.linkedin.companies.company('162479', function(err, res) {
done(null, res);
});
});
return data.result;
}
Meteor.methods({
getCompanyInfo: function () {
var linkedin = new Linkedin(Meteor.user().services.linkedin.accessToken);
var data = linkedin.company();
return data;
}
});
Unfortunately, it does not work when I call getCompanyInfo()... I get the following error: "Cannot call method 'company' of undefined".
Linkedin Auth works fine (thanks to accounts-linkedin). But I also need to connect to Linkedin API.
I had previously followed this article to play with FB Graph API in Meteor. Everything was fine.
Maybe the problem comes from Metheor.require(). I am wondering what I am supposed to do with the second set of parameters in Metheor.require(). Should I add these npm packages to packages.json as well? Does Method.require() handle this second set of parameters correctly?
Thank you for your help!

Categories

Resources