Skip to content

Commit

Permalink
use firebase sdk instead
Browse files Browse the repository at this point in the history
  • Loading branch information
fellnerse committed Dec 11, 2024
1 parent e1f131f commit 1623c70
Show file tree
Hide file tree
Showing 4 changed files with 85 additions and 111 deletions.
13 changes: 3 additions & 10 deletions components/SubscribeBtn.vue
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,11 @@
export default {
methods: {
async createSubscriptionPaypal() {
const response = await this.$fire.functions.httpsCallable("helloworld")();
// call fetch with https://www.sandbox.paypal.com/webapps/billing/subscriptions?ba_token=BA-2MW88471JV556644J
// const response = await fetch("https://helloworld-ypb2zslcea-uc.a.run.app", {
const response = await fetch("http://localhost:5001/whatsanalyze-80665/us-central1/helloworld", {
method: "GET",
headers: {
Accept: "application/json",
},
})
const data = await response.json();
if (!data.approveLink) alert("Error opening paypal: " + data.error);
if (!response.data.approveLink) alert("Error opening paypal: " + response.error);
location.href = data.approveLink;
location.href = response.data.approveLink;
},
},
};
Expand Down
56 changes: 21 additions & 35 deletions functions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

const { onRequest } = require("firebase-functions/v2/https");
const { initializeApp } = require("firebase-admin/app");
const { getFirestore } = require( "firebase-admin/firestore");
const { getFirestore } = require("firebase-admin/firestore");

const logger = require("firebase-functions/logger");

Expand Down Expand Up @@ -149,31 +149,15 @@ async function getSubscriptionLink(
}

exports.helloworld = onRequest(
{ secrets: ["PAYPAL_PASSWORD_DEV", "PAYPAL_PASSWORD_PROD"] },
{ secrets: ["PAYPAL_PASSWORD_DEV", "PAYPAL_PASSWORD_PROD"], cors: true },
async (request, response) => {

const allowedOrigins = ["localhost:3000","127.0.0.1:3000", "whatsanalyze.com", "a.run.app"]
const baseUrl = request.get("origin")
// Set CORS headers manually
for (const origin of allowedOrigins) {
if (baseUrl.includes(origin)) {
response.set('Access-Control-Allow-Origin', baseUrl); // Replace with your frontend's URL
break
}
}
console.log(`${baseUrl}`)
response.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
response.set('Access-Control-Allow-Headers', 'Content-Type');

// Handle preflight (OPTIONS) requests
if (request.method === 'OPTIONS') {
return response.status(204).send(''); // Respond to the preflight request (CORS-specific)
}
const origin = request.get("origin");

const token = await requestAccessToken(true);
// example value:
// {"status":"APPROVAL_PENDING","id":"I-XKCLA5KDLLK3","create_time":"2024-12-09T20:08:32Z","links":[{"href":"https://www.sandbox.paypal.com/webapps/billing/subscriptions?ba_token=BA-41P21132UV5106118","rel":"approve","method":"GET"},{"href":"https://api-m.sandbox.paypal.com/v1/billing/subscriptions/I-XKCLA5KDLLK3","rel":"edit","method":"PATCH"},{"href":"https://api-m.sandbox.paypal.com/v1/billing/subscriptions/I-XKCLA5KDLLK3","rel":"self","method":"GET"}]}
const linkStuff = await getSubscriptionLink(token.access_token, `${baseUrl}`);
const linkStuff = await getSubscriptionLink(token.access_token, `${origin}`);

logger.info("got link stuff back", { linkStuff });
logger.info("links", { links: linkStuff.links });
Expand All @@ -185,7 +169,7 @@ exports.helloworld = onRequest(
(link) => link.rel === "approve"
)[0].href;

response.send({ approveLink });
response.send({ data: { approveLink } });
}
);

Expand Down Expand Up @@ -267,7 +251,7 @@ exports.helloworld = onRequest(
}
*/

exports.paypalwebhook = onRequest({ secrets: ["PAYPAL_PASSWORD_DEV", "PAYPAL_PASSWORD_PROD"] },async (req,res) => {
exports.paypalwebhook = onRequest({ secrets: ["PAYPAL_PASSWORD_DEV", "PAYPAL_PASSWORD_PROD"] }, async (req, res) => {
// get data
const webhookData = req.body;
console.log(webhookData);
Expand All @@ -278,9 +262,9 @@ exports.paypalwebhook = onRequest({ secrets: ["PAYPAL_PASSWORD_DEV", "PAYPAL_PAS
// get customer information
const token = await requestAccessToken(true);

const subscriptionData = await showSubscriptions(token.access_token, subscriptionId)
const subscriptionData = await showSubscriptions(token.access_token, subscriptionId);

const emailAddress = subscriptionData.subscriber.email_address
const emailAddress = subscriptionData.subscriber.email_address;

const docRef = db.collection("subscriptions")
.doc(emailAddress);
Expand All @@ -293,33 +277,35 @@ exports.paypalwebhook = onRequest({ secrets: ["PAYPAL_PASSWORD_DEV", "PAYPAL_PAS
expirationTimestamp
}, { merge: true });
}
res.status(200).end()
res.status(200).end();
});

exports.checksubscriberstatus = onRequest({ secrets: ["PAYPAL_PASSWORD_DEV", "PAYPAL_PASSWORD_PROD"] },async (req,res) => {
exports.checksubscriberstatus = onRequest({ secrets: ["PAYPAL_PASSWORD_DEV", "PAYPAL_PASSWORD_PROD"], cors: true }, async (req, res) => {
// get data
const id = req.body.email || req.body.subscriptionId;
const isEmail = !!req.body.email;
const id = req.body.data.email || req.body.data.subscriptionId;
const isEmail = !!req.body.data.email;

if (!id){
if (!id) {
res.status(400).send("No id provided");
return
return;
}

let exists = false;
if(isEmail){
if (isEmail) {
exists = (await db.collection("subscriptions")
.doc(id).get()).exists;
}
else{
} else {
exists = !(await db.collection("subscriptions")
.where("subscriptionData.id", "==", id).limit(1).get()).empty;
}
res.status(200).send({isValid: exists});
res.status(200).send({
data: {
isValid: exists
}
});
});



/*
async function saveTransactionInFirebase(id, productIds, amount, email) {
await db.collection('transactions')
Expand Down
111 changes: 57 additions & 54 deletions nuxt.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ import { messages } from "./utils/translations.js";
// eslint-disable-next-line no-undef
const local = process.env.NUXT_ENV_LOCAL !== undefined;
const baseUrl = // eslint-disable-next-line no-undef
(process.env.BASE_URL || "https://www.whatsanalyze.com").replace(
"http:",
"https:"
);
(process.env.BASE_URL || "https://www.whatsanalyze.com").replace(
"http:",
"https:"
);

export default {
publicRuntimeConfig: {
Expand All @@ -19,8 +19,8 @@ export default {
: "AUMWxSZrtBOA1RicR_3nGijYb8yYxyq2lxBjiwoQKfVc-8jfdPr5N7X5EFUackMCLb_K7HiKswnDBUJ8",
privateRuntimeConfig: {
// eslint-disable-next-line no-undef
SENTRY_AUTH_TOKEN: process.env.SENTRY_AUTH_TOKEN,
},
SENTRY_AUTH_TOKEN: process.env.SENTRY_AUTH_TOKEN
}
},

// Target: https://go.nuxtjs.dev/config-target
Expand All @@ -30,7 +30,7 @@ export default {
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
htmlAttrs: {
lang: "en",
lang: "en"
},

meta: [
Expand All @@ -41,13 +41,13 @@ export default {
{
hid: "og:image",
property: "og:image",
content: baseUrl + "/sharePreview.png",
},
content: baseUrl + "/sharePreview.png"
}
],
link: [
{ rel: "icon", href: "/favicon.ico" },
{ rel: "apple-touch-icon", href: "/favicon.ico" },
],
{ rel: "apple-touch-icon", href: "/favicon.ico" }
]
},
pwa: {
manifest: {
Expand All @@ -70,20 +70,20 @@ export default {
files: [
{
name: "file",
accept: ["*/*"],
},
],
},
},
accept: ["*/*"]
}
]
}
}
},
workbox: {
importScripts: ["custom-sw.js"],
dev: local,
dev: local
},
icon: {
source: "/assets",
fileName: "whatsanalyze-logo-black-PWA.png",
},
fileName: "whatsanalyze-logo-black-PWA.png"
}
},

// Global CSS: https://go.nuxtjs.dev/config-css
Expand All @@ -94,8 +94,8 @@ export default {
"@/plugins/gtag",
{
src: "~/plugins/amcharts.js",
ssr: false,
},
ssr: false
}
],

// Auto import components: https://go.nuxtjs.dev/config-components
Expand All @@ -107,15 +107,15 @@ export default {
"@nuxtjs/vuetify",
"nuxt-compress",
"@nuxtjs/sentry",
"@nuxt/typescript-build",
"@nuxt/typescript-build"
],
"nuxt-compress": {
gzip: {
cache: true,
cache: true
},
brotli: {
threshold: 10240,
},
threshold: 10240
}
},

// Modules: https://go.nuxtjs.dev/config-modules
Expand All @@ -124,7 +124,7 @@ export default {
"@nuxtjs/pwa",
"@nuxtjs/gtm",
"nuxt-i18n",
"@nuxtjs/firebase",
"@nuxtjs/firebase"
],
firebase: {
config: {
Expand All @@ -134,35 +134,38 @@ export default {
storageBucket: "whatsanalyze-80665.appspot.com",
messagingSenderId: "116352567232",
appId: "1:116352567232:web:b44bef99e5a4fc6c962a25",
measurementId: "G-H1WL9MXJ17",
measurementId: "G-H1WL9MXJ17"
},
services: {
firestore: true, // Just as example. Can be any other service.
},
functions: {
emulatorPort: local ? 5001 : undefined,
}
}
},
i18n: {
seo: true,
locales: [
{
code: "en",
iso: "en-US",
iso: "en-US"
},
{
code: "de",
iso: "de-DE",
iso: "de-DE"
},
{
code: "es",
iso: "es-ES",
iso: "es-ES"
},
{
code: "fr",
iso: "fr-FR",
iso: "fr-FR"
},
{
code: "pt",
iso: "pt-PT",
},
iso: "pt-PT"
}
],
defaultLocale: "en",
detectBrowserLanguage: {
Expand All @@ -172,13 +175,13 @@ export default {
useCookie: true,
cookieCrossOrigin: false,
cookieKey: "i18n_redirected",
cookieSecure: false,
cookieSecure: false
},
vueI18n: {
fallbackLocale: "en",
messages,
messages
},
vueI18nLoader: true,
vueI18nLoader: true
},

// Vuetify module configuration: https://go.nuxtjs.dev/config-vuetify
Expand All @@ -195,13 +198,13 @@ export default {
info: colors.teal.lighten1,
warning: colors.amber.base,
error: colors.deepOrange.accent4,
success: colors.green.accent3,
},
},
},
success: colors.green.accent3
}
}
}
},
gtm: {
id: "GTM-W32PNH3",
id: "GTM-W32PNH3"
},
sentry: {
dsn:
Expand All @@ -222,18 +225,18 @@ export default {
tracingOptions: {
hooks: ["mount", "update"],
timeout: 2000,
trackComponents: true,
},
trackComponents: true
}
},
browserOptions: {},
browserOptions: {}
},
clientConfig: "~/plugins/sentry.client.config.js",
webpackConfig: {
include: ["./dist/"],
ignore: ["node_modules"],
org: "whatsanalyze",
project: "whatsanalyze",
},
project: "whatsanalyze"
}
},

// Build Configuration: https://go.nuxtjs.dev/config-build
Expand All @@ -245,17 +248,17 @@ export default {
} else if (isClient) {
config.devtool = "hidden-source-map";
}
},
}
},
server: {
host: "0.0.0.0",
https:
// eslint-disable-next-line no-undef
// eslint-disable-next-line no-undef
process.env.NODE_ENV !== "production" || local
? {
key: fs.readFileSync("./localhost-key.pem"),
cert: fs.readFileSync("./localhost.pem"),
}
: {},
},
key: fs.readFileSync("./localhost-key.pem"),
cert: fs.readFileSync("./localhost.pem")
}
: {}
}
};
Loading

0 comments on commit 1623c70

Please sign in to comment.