Firebase Cloud Function Braintree unexpectedError with Blaze Plan - google-cloud-functions

I have a firebase cloud function and want to enable payments via braintree under that function.
I have a upgraded Blaze Plan for firebase but the braintree is still throwing that unexpectedError
const functions = require('firebase-functions');
var braintree = require("braintree");
var gateway = braintree.connect({
environment: "Sandbox",
merchantId: "xxxxxxxxxxxxxxxx",
publicKey: "xxxxxxxxxxxxxxxxxxxx",
privateKey: "xxxxxxxxxxxxxxxxxxx"
});
Studying various on SO almost all posts are pointing that you must upgrade your plan but I am already in blaze plan.

Related

issue in querying mySQL db hosted in Cloud SQL with Google Run service

For a project I had to create an online db instance using MySQL in a Google Cloud SQL instance, then create a rest API to connect with the database instance in order to querying it.
Following the Google's tutorial (Link below) , I created the REST-API as service in Google Cloud Shell Editor using node.js. Via the Cloud Shell I was able to build and deploy the service, and I created a cloud Run instance connected to it.
If i connect to the basic get (see code below) it works fine, if i try to get information from the database i get nothing in return.
The url message id is 200, the query seems to be viewed as done or at least it doesn't generate an error, and after i just get nothing (if you see the code below we should get the information returned by the query in the results variable, but it is empty).
Can you help me understanding what is missing?
Here the scripts i mentioned above:
index.js
const express = require("express");
const mysql = require("mysql");
const app = express();
//pool variable
const pool = mysql.createPool({
user:'username',
password:'password',
database:'dbname',
socketpath:'the instance name given by the instance info page',
});
app.use(express.json());
const port = process.env.PORT || 8080;
app.listen(port, () =>{
console.log('oraigo rest api listening on port ${port}');
});
// function get to test on port 8080
app.get("/", async (req, res)=>{
res.json({status:"mario!!"});
});
//app get function to get from db info
app.get("/:user", async (req, res)=>{
const query = "SELECT * FROM User WHERE id_user=?";
pool.query(query, [req.params.user], (error, results)=>{
res.json(results);
/*if(!results[0]){
res.json({status:"not fuond"});
}
else{
res.json({status:"ppp"});
}*/
//res.json({status:"siamo giusti"});
});
});
package.json
{
"name": "namename",
"version": "1.0.0",
"description": "info desc",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"author": "Gigi",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"mysql": "^2.18.1"
}
}
To do so I've watched many videos from Google Cloud Tech Youtube channel, in particular this one: https://www.youtube.com/watch?v=_w_idf928WY
I've followed everything, except that i'm using the Cloud Shell instead of coding locally (but should be excatly the same)
Thanks in advance.
I believe the issue is that your socketpath variable is not being named and set correctly.
It should be named socketPath and not socketpath, with the value being set to '/cloudsql/<PROJECT-ID>:<INSTANCE-REGION>:<INSTANCE-NAME>'
Note: <PROJECT-ID>:<INSTANCE-REGION>:<INSTANCE-NAME> is also referred to sometimes as INSTANCE_CONNECTION_NAME within samples and tutorials.
So in context, your pool creation should look like this:
const pool = mysql.createPool({
user: <YOUR_DB_USER>,
password: <YOUR_DB_PASS>,
database: <YOUR_DB_NAME>,
socketPath: '/cloudsql/<PROJECT-ID>:<INSTANCE-REGION>:<INSTANCE-NAME>',
});
So if your Cloud SQL Instance was named mysql-instance, in the region us-central1, within a project with the name and ID of my-cool-project then your socket path parameter would be the following:
socketPath: '/cloudsql/my-cool-project:us-central1:mysql-instance'
P.S. Here is the tutorial source code for the video link you shared if you want to reference it directly.
I managed to make it work by forcing the connection to the SQL DataBase in the connection settings, during the service creation.

How to cancel deploying Google cloud functions?

I've started to deploy my cloud function with firebase deploy --only functions:(functionName), but 'deploying' status does not end and it's being deployed infinitely until now. I can't delete it because 'delete' button is disabled while deploying the function.
How to I terminate deploying cloud funtion by force?
Function:
exports.calculate = functions.https.onRequest(async (req, res) => {
const id = (req.query.id).toString();
let flist = (req.query.fIDs).toString();
const ret = await callCalculate(id, flist);
res.json(ret);
});
async function callCalculate() {...}
If you want to delete the function on cloud and bypass the confirmation prompt, you could add “--force” in your deploy command.
firebase deploy --only functions --project --token --force
I certainly hope this helps.
After re-deploying another cloud function, infinite deploying ended with error logs. I think it have been fallen into deadlock status.

create channel with flex api from twilio serverless function

I am trying t ocreate a chat channel through nodejs twilio flex api, I can create it from other server or node project, but if I deploy it in twilio's serverless function it causes error ,seems it doesn't recognize flex api.
It gives error can not read property create of undefined.
Does twilio function has not included flex api yet?
code is as below:
const twilio = require('twilio')(context.ACCOUNT_SID, context.AUTH_TOKEN);
threadID=from
fromName=from
fromAddress=from
const channelArgs = {
flexFlowSid: 'FO.....',
identity: from,
chatUniqueName: from,
chatUserFriendlyName: from,
chatFriendlyName: from,
target: from,
preEngagementData: JSON.stringify({
threadID,
fromName,
fromAddress,
subject
})
};
twilio.flexApi.channel.create(channelArgs).then(channel => {
console.log('got chat channel', channel.sid);
Verify the Twilio Helper Library in use by your Twilio Functions environment is up to date.
You can find the most up to date Twilio Node Helper Library for twilio is below.
twilio-node changelog

Trigger a cloud build pipeline using Cloud Function

I'm trying to create a cloud function listening to cloudbuilds topic and making an API call to trigger the build. I think I'm missing something in my index.js file (I'm new to Node.js). Can you provide a sample example of a Cloud Function making an API call to the Cloud Build API?
Here is my function:
const request = require('request')
const accessToken = '$(gcloud config config-helper --format='value(credential.access_token)')';
request({
url: 'https://cloudbuild.googleapis.com/v1/projects/[PROJECT_ID]/builds',
auth: {
'bearer': accessToken
},
method: 'POST',
json: {"steps": [{"name":"gcr.io/cloud-builders/gsutil", "args": ['cp','gs://adolfo-test-cloudbuilds/cloudbuild.yaml', 'gs://adolfo-test_cloudbuild/cloudbuild.yaml']}]},
},
module.exports.build = (err, res) => {
console.log(res.body);
});
I was executing the command gcloud config config-helper --format='value(credential.access_token)', copying the token, and putting it as a value to the variable accessToken. But this didn't work for me.
Here is the error: { error: { code: 403, message: 'The caller does not have permission', status: 'PERMISSION_DENIED' } }
I had the same exact problem and I have solved it by writing a small package, you can use it or read the source code.
https://github.com/MatteoGioioso/google-cloud-build-trigger
With this package you can run a pre-configured trigger from cloud build.
You can also extend to call other cloud build API endpoints.
As my understanding cloud build API requires either OAuth2 or a service account. Make sure you gave the right permission to cloud build in the gcp console under IAM. After that you should be able to download the service-account.json file.

Does sending mail via nodemailer in firebase cloud functions require billing account?

I had deployed a firebase cloud function to send a welcome mail when a user signs in for the first time.
In the firebase console, in firebase cloud function log messages, I saw this error message when the function was invoked.
Error Message:
Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account to remove these restrictions
Is it not possible to send emails for free using firebase cloud functions? if it is possible, please explain the procedure. (Possiblly with a sample code)
Edit 1:
1. I am currently using nodemailer for sending mail.
2. I am using Gmail as the mail service.
Does sending mail via nodemailer in firebase cloud functions require billing account?
NO, You DO NOT need a billing account to send email via nodmailer using cloud functions.
I was getting the billing error as yours in my cloud function. And I have done 2 simple steps and it's gone.
1. In your gmail account setting, enable Less secure app access to ON
2. Also go to this link and click continue https://accounts.google.com/DisplayUnlockCaptcha .
After doing the above 2 steps, the billing error is gone, and email is sending successfully from the cloud function.
And here is my nodejs code for your refernce:
const functions = require('firebase-functions');
const nodemailer = require('nodemailer');
const mailTransport = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'xyzz#gmail.com',
pass: '123'
},
});
exports.sendMail = functions.https.onRequest(async (req, res) => {
const mailOptions = {
from: '"Test." <noreply#firebase.com>',
to: 'xyz#gmail.com'
};
// Building Email message.
mailOptions.subject = 'Thanks and Welcome!'
mailOptions.text = 'Thanks you for subscribing to our newsletter. You will receive our next weekly newsletter.'
try {
await mailTransport.sendMail(mailOptions);
console.log('subscription confirmation email sent to');
return res.send('Sended');
} catch (error) {
console.error('There was an error while sending the email:', error);
return res.send(error.toString());
}
});
You can test locally before you deploy it
firebase serve --only functions
you will get a link http://localhost:5000/project-name/us-central1/sendMail; paste it in the browser and the cloud function will run. If any errors it will show up in the browser and console/powershell