I have added two firebase functions to my flutter app to implement Stripe.
const functions = require("firebase-functions");
const stripe = require("stripe")(functions.config().stripe.testKey)
const calculateOrderAmount = (items) => {
prices = [];
catalog = [
{ 'id': '0', 'price': 3.99, },
{ 'id': '1', 'price': 7.99, },
{ 'id': '2', 'price': 9.99, },
];
items.array.forEach(item => {
price = catalog.find(x => x.id == item.id).price;
prices.push(price);
});
return parseInt(prices.reduce((a, b) => a + b) * 100);
}
const generateResponse = function (intent) {
switch (intent.status) {
case 'requires_action':
return {
clientSecret: intent.clientSecret,
requiresAction: true,
status: intent.status,
}
case 'requires_payment_method':
return {
'error': 'Your card was denied, please provide a new payment method',
};
case 'succeded':
console.log('Payment succeded')
return {
clientSecret: intent.clientSecret,
status: intent.status,
};
}
return {
error: 'Failed'
};
}
exports.StripePayEndpointMethodId = functions.https.onRequest(async (req, res) => {
const { paymentMethodId, items, curency: currency, useStripeSdk, } = req.body;
const orderAmount = calculateOrderAmount(items);
try {
if (paymentMethodId) {
const params = {
amount: orderAmount,
confirm: true,
confirmation_method: 'manual',
currency: currency,
payment_method: paymentMethodId,
use_stripe_sdk: useStripeSdk,
}
const intent = await stripe.paymentIntents.create(params);
console.log('Intent: ${intent}');
return res.send(generateResponse(intent));
}
res.sendStatus(400)
} catch (error) {
return res.send({ error: error.message });
}
});
exports.StripePayEndpointIntentId = functions.https.onRequest(async (req, res) => {
const { paymentIntentId } = req.body;
try {
if (paymentIntentId) {
const intent = await stripe.paymentIntents.confirm(paymentIntentId);
return res.send(generateResponse(intent));
}
return res.sendStatus(400)
} catch (error) {
return res.send({ error: error.message })
}
});
However when I run the command firebase deploy --only functions
it shows me an error. Here is the full log:
=== Deploying to 'jimv01'...
i deploying functions
✔ functions: Finished running predeploy script.
i functions: preparing codebase default for deployment
i functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i functions: ensuring required API cloudbuild.googleapis.com is enabled...
i artifactregistry: ensuring required API artifactregistry.googleapis.com is enabled...
✔ artifactregistry: required API artifactregistry.googleapis.com is enabled
✔ functions: required API cloudfunctions.googleapis.com is enabled
✔ functions: required API cloudbuild.googleapis.com is enabled
i functions: Loading and analyzing source code for codebase default to determine what to deploy
Serving at port 8950
i functions: preparing functions directory for uploading...
i functions: packaged /Users/fscozano/Desktop/GymPT_0.2/server/functions (75.05 KB) for uploading
✔ functions: functions folder uploaded successfully
i functions: updating Node.js 18 (1st Gen) function StripePayEndpointMethodId(us-central1)...
i functions: updating Node.js 18 (1st Gen) function StripePayEndpointIntentId(us-central1)...
Function failed on loading user code. This is likely due to a bug in the user code. Error message: Provided module can't be loaded.
Did you list all required modules in the package.json dependencies?
Detailed stack trace: Error: Cannot find module 'stripe'
Require stack:
- /workspace/index.js
- /layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/loader.js
- /layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/main.js
at Module._resolveFilename (node:internal/modules/cjs/loader:1134:15)
at Module._load (node:internal/modules/cjs/loader:975:27)
at Module.require (node:internal/modules/cjs/loader:1225:19)
at require (node:internal/modules/helpers:177:18)
at Object.<anonymous> (/workspace/index.js:2:16)
at Module._compile (node:internal/modules/cjs/loader:1356:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1414:10)
at Module.load (node:internal/modules/cjs/loader:1197:32)
at Module._load (node:internal/modules/cjs/loader:1013:12)
at Module.require (node:internal/modules/cjs/loader:1225:19)
Could not load the function, shutting down.. Please visit https://cloud.google.com/functions/docs/troubleshooting for in-depth troubleshooting documentation.
Function failed on loading user code. This is likely due to a bug in the user code. Error message: Provided module can't be loaded.
Did you list all required modules in the package.json dependencies?
Detailed stack trace: Error: Cannot find module 'stripe'
Require stack:
- /workspace/index.js
- /layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/loader.js
- /layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/main.js
at Module._resolveFilename (node:internal/modules/cjs/loader:1134:15)
at Module._load (node:internal/modules/cjs/loader:975:27)
at Module.require (node:internal/modules/cjs/loader:1225:19)
at require (node:internal/modules/helpers:177:18)
at Object.<anonymous> (/workspace/index.js:2:16)
at Module._compile (node:internal/modules/cjs/loader:1356:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1414:10)
at Module.load (node:internal/modules/cjs/loader:1197:32)
at Module._load (node:internal/modules/cjs/loader:1013:12)
at Module.require (node:internal/modules/cjs/loader:1225:19)
Could not load the function, shutting down.. Please visit https://cloud.google.com/functions/docs/troubleshooting for in-depth troubleshooting documentation.
Functions deploy had errors with the following functions:
StripePayEndpointIntentId(us-central1)
StripePayEndpointMethodId(us-central1)
i functions: cleaning up build files...
⚠ functions: Unhandled error cleaning up build images. This could result in a small monthly bill if not corrected. You can attempt to delete these images by redeploying or you can delete them manually at https://console.cloud.google.com/gcr/images/jimv01/us/gcf
Error: There was an error deploying functions:
- Error Failed to update function StripePayEndpointMethodId in region us-central1
- Error Failed to update function StripePayEndpointIntentId in region us-central1
Here is also the package.json file:
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint .",
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "18"
},
"main": "index.js",
"dependencies": {
"firebase-admin": "^11.8.0",
"firebase-functions": "^4.3.1"
},
"devDependencies": {
"eslint": "^8.15.0",
"eslint-config-google": "^0.14.0",
"firebase-functions-test": "^3.1.0"
},
"private": true
}
From the log, I assume that the problem is that it can’t find the stripe module and, as you can see, the stripe dependency doesn’t show even though I added it through the command npm install stripe --save
. For this reason, I tried adding it manually:
"dependencies": {
"firebase-admin": "^11.8.0",
"firebase-functions": "^4.3.1",
"stripe": "^6.28.0"
},
However, it shows another error:
=== Deploying to 'jimv01'...
i deploying functions
✔ functions: Finished running predeploy script.
i functions: preparing codebase default for deployment
i functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i functions: ensuring required API cloudbuild.googleapis.com is enabled...
i artifactregistry: ensuring required API artifactregistry.googleapis.com is enabled...
✔ functions: required API cloudbuild.googleapis.com is enabled
✔ artifactregistry: required API artifactregistry.googleapis.com is enabled
✔ functions: required API cloudfunctions.googleapis.com is enabled
i functions: Loading and analyzing source code for codebase default to determine what to deploy
Serving at port 8640
i functions: preparing functions directory for uploading...
i functions: packaged /Users/fscozano/Desktop/GymPT_0.2/server/functions (75.06 KB) for uploading
✔ functions: functions folder uploaded successfully
i functions: updating Node.js 18 (1st Gen) function StripePayEndpointMethodId(us-central1)...
i functions: updating Node.js 18 (1st Gen) function StripePayEndpointIntentId(us-central1)...
Build failed: npm ERR! code EUSAGE
npm ERR!
npm ERR! `npm ci` can only install packages when your package.json and package-lock.json or npm-shrinkwrap.json are in sync. Please update your lock file with `npm install` before continuing.
npm ERR!
npm ERR! Missing: [email protected] from lock file
npm ERR!
npm ERR! Clean install a project
npm ERR!
npm ERR! Usage:
npm ERR! npm ci
npm ERR!
npm ERR! Options:
npm ERR! [--install-strategy <hoisted|nested|shallow|linked>] [--legacy-bundling]
npm ERR! [--global-style] [--omit <dev|optional|peer> [--omit <dev|optional|peer> ...]]
npm ERR! [--include <prod|dev|optional|peer> [--include <prod|dev|optional|peer> ...]]
npm ERR! [--strict-peer-deps] [--foreground-scripts] [--ignore-scripts] [--no-audit]
npm ERR! [--no-bin-links] [--no-fund] [--dry-run]
npm ERR! [-w|--workspace <workspace-name> [-w|--workspace <workspace-name> ...]]
npm ERR! [-ws|--workspaces] [--include-workspace-root] [--install-links]
npm ERR!
npm ERR! aliases: clean-install, ic, install-clean, isntall-clean
npm ERR!
npm ERR! Run "npm help ci" for more info
npm ERR! A complete log of this run can be found in: /www-data-home/.npm/_logs/2024-03-17T19_44_48_688Z-debug-0.log; Error ID: beaf8772
Build failed: npm ERR! code EUSAGE
npm ERR!
npm ERR! `npm ci` can only install packages when your package.json and package-lock.json or npm-shrinkwrap.json are in sync. Please update your lock file with `npm install` before continuing.
npm ERR!
npm ERR! Missing: [email protected] from lock file
npm ERR!
npm ERR! Clean install a project
npm ERR!
npm ERR! Usage:
npm ERR! npm ci
npm ERR!
npm ERR! Options:
npm ERR! [--install-strategy <hoisted|nested|shallow|linked>] [--legacy-bundling]
npm ERR! [--global-style] [--omit <dev|optional|peer> [--omit <dev|optional|peer> ...]]
npm ERR! [--include <prod|dev|optional|peer> [--include <prod|dev|optional|peer> ...]]
npm ERR! [--strict-peer-deps] [--foreground-scripts] [--ignore-scripts] [--no-audit]
npm ERR! [--no-bin-links] [--no-fund] [--dry-run]
npm ERR! [-w|--workspace <workspace-name> [-w|--workspace <workspace-name> ...]]
npm ERR! [-ws|--workspaces] [--include-workspace-root] [--install-links]
npm ERR!
npm ERR! aliases: clean-install, ic, install-clean, isntall-clean
npm ERR!
npm ERR! Run "npm help ci" for more info
npm ERR! A complete log of this run can be found in: /www-data-home/.npm/_logs/2024-03-17T19_45_17_967Z-debug-0.log; Error ID: beaf8772
Functions deploy had errors with the following functions:
StripePayEndpointIntentId(us-central1)
StripePayEndpointMethodId(us-central1)
i functions: cleaning up build files...
⚠ functions: Unhandled error cleaning up build images. This could result in a small monthly bill if not corrected. You can attempt to delete these images by redeploying or you can delete them manually at https://console.cloud.google.com/gcr/images/jimv01/us/gcf
Error: There was an error deploying functions:
- Error Failed to update function StripePayEndpointMethodId in region us-central1
- Error Failed to update function StripePayEndpointIntentId in region us-central1
Then, I discarded the option of manually adding the stripe module. Moreover, when I faced the first issue, the functions were loaded on firebase but with an error, so they are there but I can’t use them.