Firebase Function Unable to find a valid endpoint for function app - node.js

I have a firebase functions folder which I am trying to connect to my frontend app to run calls to my backend server.
The function folder got set up and worked with the emulator, when I tried to use these function in the front end app however they didn't work. The following error showed: Error: Unable to find a valid endpoint for function app
This is what I added to the frontend firebaase.json file:
"hosting": {
"public": "build",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
},
{
"source": "/bigben",
"function": "bigben",
"region": "us-central1"
},
{
"source": "/create-customer-portal-session",
"function": "app"
}
]
}
}
Then this is the index.js file in the functions folder:
const functions = require('firebase-functions');
const express = require('express');
const app = express();
const cors = require('cors')({origin: true});
app.use(cors);
exports.app = functions.https.onRequest(app);
exports.bigben = functions.https.onRequest((req, res) => {
const hours = (new Date().getHours() % 12) + 1 // London is UTC + 1hr;
res.status(200).send(`<!doctype html>
<head>
<title>Time</title>
</head>
<body>
${'BONG '.repeat(hours)}
</body>
</html>`);
});
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY)
const priceId = 'price_1LaJC1CKMdmWgnyspBbFet9v';
const storeItems = new Map([
[
1, { priceInCents: 10000, name: 'Item 1 Name'}
],
[
2, { priceInCents: 20000, name: 'Item 2 Name'}
],
])
app.post("/create-checkout-session", async (req, res) => {
const cust = req.body.customerId
const price = req.body.priceId
const quantity = req.body.students
const quantityA = Number(quantity)
try {
const session = await stripe.checkout.sessions.create({
payment_method_types: ["card"],
mode: 'subscription',
allow_promotion_codes: true,
customer: cust,
line_items: [
{
price: price,
// For metered billing, do not pass quantity
quantity: quantityA,
},
],
success_url: `https://learning-platform.web.app/`,
cancel_url: `https://learning-platform.web.app/`,
})
res.redirect(session.url);
} catch (e) {
res.status(500).json({ error: e.message })
}
})
app.post('/create-customer-portal-session', async (req, res) => {
const cust = req.body.customerId
// Authenticate your user.
const session = await stripe.billingPortal.sessions.create({
customer: cust,
});
console.log(session.url)
res.redirect(session.url);
});
This is what is returned when I run the command: firebase deploy --only functions,hosting --debug

Related

Vonage Api Call Function

Hey I got my code to receive calls but for some reason when I run the script it doesn’t place an out going call. I am not getting no error message or anything it just simply won’t call,But I set up everything right am I missing a trigger or something? Could someone please point me in the right direction I’ve been trying to build this api for about 4 Months.
require('dotenv').config();
const Vonage = require('#vonage/server-sdk');
const express = require('express');
const morgan = require('morgan');
const app = express();
const vonage = new Vonage({
apiKey: process.env.VONAGE_API_KEY,
apiSecret: process.env.VONAGE_API_SECRET,
applicationId: process.env.VONAGE_APPLICATION_ID,
privateKey: process.env.VONAGE_PRIVATE_KEY_PATH
});
app.use(morgan('tiny'));
app.use(express.json());
app.get('/call', (req, res) => {
vonage.calls.create({
to: [{
type: 'phone',
number: process.env.TO_NUMBER
}],
from: {
type: 'phone',
number: process.env.VONAGE_NUMBER,
},
ncco: [{
"action": "talk",
"text": "This is a text to speech call from Vonage"
}]
}, (error, response) => {
if (error) console.error(error)
if (response) console.log(response)
});
res.json('ok');
});
app.post('/event', (req, res) => {
console.log(req.body);
res.status(200).send('');
});
app.post('/answer', (req, res) => {
const number = req.body.from.split('').join(' ');
const ncco = [
{
action: 'talk',
text: 'Thank you for calling from ' + number,
language: 'en-IN',
style: '4'
},
{
action: 'stream',
streamUrl: [
'https://www.albinoblacksheep.com/audio/mp3/RickRollMarioPaint.mp3'
]
}
];
res.json(ncco);
});
app.listen(process.env.PORT, () => console.log(Running on port ${process.env.PORT}));

how to use local swagger.json, istead of giving api controllers

I am new to swagger. I am creating an express-nodejs-typescript, rest api project. I have configured swagger and it is working fine, please see my code below.
import swaggerUi from "swagger-ui-express";
import swaggerJsdoc from 'swagger-jsdoc'
const app = express()
const swaggerOptions: swaggerJsdoc.Options = {
definition: {
openapi: "3.0.0",
info: {
title: "REST API Docs",
version: '1.0',
},
components: {
securitySchemas: {
bearerAuth: {
type: "http",
scheme: "bearer",
bearerFormat: "JWT",
},
},
},
security: [
{
bearerAuth: [],
},
],
},
apis: ['src/apis/**/*.controller.ts', 'src/schemas/*.schema.ts'],
};
const swaggerDocs = swaggerJsdoc(swaggerOptions);
app.use(
"/docs",
swaggerUi.serve,
swaggerUi.setup(swaggerDocs, { explorer: true })
);
What i want is to use local swagger.json file, instead on giving apis array apis: ['src/apis/**/*.controller.ts', 'src/schemas/*.schema.ts'],
How can I do that, please help.
something like this should work:
const app = express();
const swaggerUi = require('swagger-ui-express');
try {
const swaggerDoc = require('./your/doc/swagger.json');
app.use('/doc', swaggerUi.serve, swaggerUi.setup(swaggerDoc));
} catch (error) {
console.error('Error loading Swagger json: ', error);
}
app.listen(3000, '0.0.0.0', () => {
console.log(`🚀 Server started: http://localhost:3000/doc`);
});

firebase.json rewrites issue for nodejs/vuejs firebase hosting?

i do not know exactly what problem i'm facing. here is my console out
I have client side and server side. In client side, developing front-end using vuejs. server side used node js/express.js for sending data to front end.
i have already deployed my project into firebase hosting. configured firebase json too.
Client side: client-> service->Api.js
import axios from 'axios'
export default() => {
return axios.create({
baseURL: `https://dev-cloudthrifty-com.firebaseapp.com`
// https://dev-cloudthrifty-com.firebaseapp.com/
// http://localhost:8081
})
}
Client side: vue.config.js
const path = require('path')
module.exports = {
devServer: {
compress: true,
disableHostCheck: true,
},
outputDir: path.resolve(__dirname, '../dist'), // build all the assets inside server/dist folder
pluginOptions: {
'style-resources-loader': {
preProcessor: 'scss',
patterns: [path.resolve(__dirname, './src/styles/global.scss')]
}
},
chainWebpack: config => {
if (config.plugins.has('optimize-css')) {
config.plugins.delete('optimize-css')
}
}
}
Firebase.json
{
"hosting": {
"public": "dist",
"rewrites": [
{ "source": "/", "function": "app"},
{ "source": "**", "destination": "/index.html"}
],
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"headers": [ {
"source": "**/*.#(eot|otf|ttf|ttc|woff|font.css)",
"headers": [ {
"key": "Access-Control-Allow-Origin",
"value": "*"
} ]
}, {
"source": "**/*.#(jpg|jpeg|gif|png)",
"headers": [ {
"key": "Cache-Control",
"value": "max-age=7200"
} ]
}, {
"source": "404.html",
"headers": [ {
"key": "Cache-Control",
"value": "max-age=300"
} ]
} ],
"cleanUrls": true
}
}
server side: app.js
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const morgan = require('morgan')
var firebase = require('firebase');
const functions = require('firebase-functions');
const axios = require('axios');
const credentials = new Buffer('testing:testing123').toString('base64')
const app = express()
app.use(morgan('combined'))
app.use(bodyParser.json())
app.use(cors())
var Post = require("./models/post");
const firebaseConfig = {
apiKey: "AIzaSyBDwqFKPt4D0eIspjsziweLI0nc49BRDrU",
authDomain: "cloudthrifty-demo.firebaseapp.com",
databaseURL: "https://cloudthrifty-demo.firebaseio.com",
projectId: "cloudthrifty-demo",
storageBucket: "cloudthrifty-demo.appspot.com",
messagingSenderId: "638814042535",
appId: "1:638814042535:web:221da9fcf361554b"
};
firebase.initializeApp(firebaseConfig);
var db = firebase.firestore();
app.get('/GCPScheduler', (req, res) => {
res.send(
[{
title: "Hello World!",
description: "Hi there! How are you?"
}]
)
})
// serve dist folder
if (process.env.NODE_ENV === 'production') {
// Static folder
app.use(express.static(__dirname + '/dist'));
// Handle SPA
app.get('*', (req, res) => res.sendFile(__dirname + '/dist/index.html'));
}
// Add new post
app.post('/list-server', (req, res) => {
var token = req.body.token;
var ccExp = req.body.ccExp;
var cardNumber = req.body.cardNumber;
var currentUserUUID = req.body.currentUserUUID;
var amount = req.body.amount;
console.log(token);
console.log(ccExp);
console.log(cardNumber);
console.log(currentUserUUID);
console.log(amount);
(async() => {
const paymentRequest = await getAuthTokenForThePayment({
account: cardNumber,
merchid: '496160873888',
amount: amount, // Smallest currency unit. e.g. 100 cents to charge $1.00
expiry: ccExp,
currency: 'USD'
});
const charge = await makeCharge({
merchid: paymentRequest.data.merchid,
retref: paymentRequest.data.retref
});
console.log(charge);
console.log(charge.data.respstat)
if (charge.data.respstat == 'A'){
var data = db.collection('transactionTable').doc(charge.data.retref);
var setAlan = data.set({
'respstat': charge.data.respstat,
'retref': charge.data.retref,
'account': charge.data.account,
'token': charge.data.token,
'batchid': charge.data.batchid,
'amount': charge.data.amount,
'resptext': charge.data.resptext,
'respcode': charge.data.respcode,
'commcard': charge.data.commcard,
'setlstat': charge.data.setlstat,
});
res.send(charge.data.respstat);
} else if(charge.data.respstat == 'B'){
console.log("Declined");
res.send(charge.data.respstat);
}else if(charge.data.respstat == 'C'){
console.log("Retry");
res.send(charge.data.respstat);
}
})();
})

how to deploy vuejs/nodejs app in firebase hosting?

My project structure
client part contains vue app and server part contains nodejs. In client side handling api service which is created from server. Created api services inside client folder to get response from server.
here is my structure of client-> services->api.js.
here is client -> services -> api.js code:
import axios from 'axios'
export default() => {
return axios.create({
baseURL: `https://dev-cloudthrifty-com.firebaseapp.com`
// https://dev-cloudthrifty-com.firebaseapp.com/
// http://localhost:8081
})
}
client -> vue.config.js configuration file.
const path = require('path')
module.exports = {
devServer: {
compress: true,
disableHostCheck: true,
},
outputDir: path.resolve(__dirname, '../server/dist'), // build all the assets inside server/dist folder
pluginOptions: {
'style-resources-loader': {
preProcessor: 'scss',
patterns: [path.resolve(__dirname, './src/styles/global.scss')]
}
},
chainWebpack: config => {
if (config.plugins.has('optimize-css')) {
config.plugins.delete('optimize-css')
}
}
}
Here is my firebase configuration: firebase.json
{
"hosting": {
"public": "./server/dist",
"rewrites": [
{
"source": "**",
"destination": "/index.html"
},
{ "source": "**", "function": "app"}
],
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"headers": [ {
"source": "**/*.#(eot|otf|ttf|ttc|woff|font.css)",
"headers": [ {
"key": "Access-Control-Allow-Origin",
"value": "*"
} ]
}, {
"source": "**/*.#(jpg|jpeg|gif|png)",
"headers": [ {
"key": "Cache-Control",
"value": "max-age=7200"
} ]
}, {
"source": "404.html",
"headers": [ {
"key": "Cache-Control",
"value": "max-age=300"
} ]
} ],
"cleanUrls": true
}
}
Server-> app.js where i'm creating api for front-end
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const morgan = require('morgan')
const firebase = require('firebase');
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const axios = require('axios');
const credentials = new Buffer('testing:testing123').toString('base64')
const app = express()
app.use(morgan('combined'))
app.use(bodyParser.json())
app.use(cors())
var Post = require("./models/post");
const firebaseConfig = {
apiKey: "AIzaSyDHDKttdke4WArImpRu1pIU",
authDomain: "dev-cxxxxxy-com.firebaseapp.com",
databaseURL: "https://dev-cxxxx-com.firebaseio.com",
projectId: "dev-clxxxx-com",
storageBucket: "dev-cxxxx-com.appspot.com",
messagingSenderId: "830534343916",
appId: "1:83916:web:e0fd232ebb1"
};
const firebaseApp = admin.initializeApp(firebaseConfig);
var db = firebaseApp.firestore();
app.get('/gcp-scheduler', (req, res) => {
res.send(
[{
title: "Hello World!",
description: "Hi there! How are you?"
}]
)
})
// serve dist folder
if (process.env.NODE_ENV === 'production') {
// Static folder
app.use(express.static(__dirname + '/dist'));
// Handle SPA
app.get('**', (req, res) => res.sendFile(__dirname + '/dist/index.html'));
}
// Add new post
app.post('/list-server', (req, res) => {
var token = req.body.token;
var ccExp = req.body.ccExp;
var cardNumber = req.body.cardNumber;
var currentUserUUID = req.body.currentUserUUID;
var amount = req.body.amount;
console.log(token);
console.log(ccExp);
(async() => {
const paymentRequest = await getAuthTokenForThePayment({
account: cardNumber,
merchid: '496160873888',
amount: amount, // Smallest currency unit. e.g. 100 cents to charge $1.00
expiry: ccExp,
currency: 'USD'
});
const charge = await makeCharge({
merchid: paymentRequest.data.merchid,
retref: paymentRequest.data.retref
});
console.log(charge);
console.log(charge.data.respstat)
if (charge.data.respstat == 'A'){
var data = db.collection('transactionTable').doc(charge.data.retref);
var setAlan = data.set({
'respstat': charge.data.respstat,
'retref': charge.data.retref,
'account': charge.data.account,
'token': charge.data.token,
'batchid': charge.data.batchid,
'amount': charge.data.amount,
'resptext': charge.data.resptext,
'respcode': charge.data.respcode,
'commcard': charge.data.commcard,
'setlstat': charge.data.setlstat,
});
res.send(charge.data.respstat);
} else if(charge.data.respstat == 'B'){
console.log("Declined");
res.send(charge.data.respstat);
}else if(charge.data.respstat == 'C'){
console.log("Retry");
res.send(charge.data.respstat);
}
})();
})
const getAuthTokenForThePayment = async (data) => {
try {
const config = {
headers: {
'Content-Type': 'application/json',
'Authorization': `Basic ${credentials}`
}
};
const URL = 'https://fts.cardconnect.com:6443/cardconnect/rest/auth';
return await axios.put(URL, data, config);
} catch (error) {
throw (error);
}
}
const makeCharge = async (data) => {
try {
const config = {
headers: {
'Content-Type': 'application/json',
'Authorization': `Basic ${credentials}`
}
};
const URL = 'https://fts.cardconnect.com:6443/cardconnect/rest/capture';
return await axios.put(URL, data, config);
} catch (error) {
throw (error);
}
}
// app.listen(process.env.PORT || 8081)
exports.app = functions.https.onRequest(app);
My issue when i click on checkout button in cart view, it should send current user card details with token to the server(app.js) through post api. After receiving card details from front-end, it should call cardconnect charge api functionality which i have implemented in app.js. In browser console current user card details received successfully but while clicking checkout charge api are not called it shows some other which is unrelated to api.
But everything works in localhost. client side localhost url: http://localhost:8080 and server side localhost url: http://localhost8081.
my firebase hosting url: https://dev-xxxx.firebaseapp.com
here is my console output screenshot:
Dont where i am making mistakes in firebase vuejs/nodejs hosting, rewrites path.
it show error in postservice.js file
import Api from '#/services/Api'
export default {
fetchPosts () {
return Api().get('gcp-scheduler')
},
addPost (params) {
return Api().post('list-server', params)
}
}
Any help much appreciated pls..

Paypal rest sdk does successful transaction but with no history of it on sandbox

I am working on this sdk for paypal here and I'm running into a bunch of errors like: "The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator, webmaster#paypal.com and inform them of the time the error occurred, and anything you might have done that may have caused the error.
More information about this error may be available in the server error log"
when everything seems to go right, I get transferred to the /success with all the payment json back. the problem is that the console.log("payerId = " + payerId) never logs and when i log into my sandbox I have no history of any transaction even though I went though the motions of one. I get no error back so idk what I am doing wrong. THX!
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path')
let port = 5007;
let app = express();
// const ejs = require('ejs');
const paypal = require('paypal-rest-sdk');
// const Paypal = require('./Server/Paypal_api.js')
// const Nodemailer = require('./Server/Nodemailer.js')
// app.use(express.static(path.join(__dirname, 'public')));
// app.use(express.static('assets'))
// app.use(cors())
// app.use(bodyParser.json())
paypal.configure({
'mode': 'sandbox', //sandbox or live
'client_id': 'AYoej9yvsPTO_giNMnI5pMecd4vbelcK_N',
'client_secret': 'EE8rJValbapV4Dk-g5yFFMG7pMC-bwwwv7sO'
});
client id & secret not real but you get it
app.post('/pay', (req, res) => {
const create_payment_json = {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"redirect_urls": {
"return_url": "http://localhost:3000/success",
"cancel_url": "http://localhost:3000/cancel"
},
"transactions": [{
"item_list": {
"items": [{
"name": "Red Sox Hat",
"sku": "001",
"price": "25.00",
"currency": "USD",
"quantity": 1
}]
},
"amount": {
"currency": "USD",
"total": "25.00"
},
"description": "Hat for the best team ever"
}]
};
paypal.payment.create(create_payment_json, (error, payment) =>{
if (error) {
throw error;
} else {
// console.log(payment)
for(let i = 0;i < payment.links.length;i++){
if(payment.links[i].rel === 'approval_url'){
res.redirect(payment.links[i].href);
}
}
}
});
});
app.get('/success', (req, res) => {
const payerId = req.query.PayerID;
const paymentId = req.query.paymentId;
console.log("payerId = " + payerId)
const execute_payment_json = {
"payer_id": payerId,
"transactions": [{
"amount": {
"currency": "USD",
"total": "25.00"
}
}]
};
paypal.payment.execute(paymentId, execute_payment_json, (error, payment) =>{
if (error) {
console.log(error.response);
throw error;
} else {
console.log(JSON.stringify(payment));
res.send('Success');
}
});
});
app.get('/cancel', (req, res) => res.send('Cancelled'));
app.listen(port, () => {
console.log("resonating on port " + port)
})

Resources