Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

stripe cloud function and express #2

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion adminhere/adminsonly
Submodule adminsonly updated from 27f1a6 to da0f5c
5 changes: 5 additions & 0 deletions backend/.firebaserc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"projects": {
"default": "native-functions-dd65b"
}
}
14 changes: 14 additions & 0 deletions backend/firebase.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"functions": [
{
"source": "functions",
"codebase": "default",
"ignore": [
"node_modules",
".git",
"firebase-debug.log",
"firebase-debug.*.log"
]
}
]
}
1 change: 1 addition & 0 deletions backend/functions/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules/
167 changes: 167 additions & 0 deletions backend/functions/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const stripe = require('stripe')(functions.config().stripe.secret_key);
const twilio = require('twilio')(functions.config().twilio.account_sid, functions.config().twilio.auth_token);
const serviceAccount = require('./ivanprojo-72b52-firebase-adminsdk-48vxh-3b0f8c89bf.json');
const cors = require('cors')({ origin: true });
const getRawBody = require('raw-body');
const express = require('express');
const app = express();

// Setting timeout and memory for the deploy
const runtimeOpts = {
timeoutSeconds: 540,
memory: '2GB'
}


admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
const db = admin.firestore();

exports.stripeWebhook = functions.https.onRequest(async (request, response) => {
cors(request, response, async () => {

let event;

try {
const rawBody = await getRawBody(request);
//const body = request.rawBody.toString();
console.log(`Webhook received! Raw body: ${rawBody}`)
event = stripe.webhooks.constructEvent(
body,
request.headers['stripe-signature'],
functions.config().stripe.payments_webhook_secret
);
} catch (err) {
console.error(`Webhook Error: ${err.message}`);
return response.status(400).send(`Webhook Error: ${err.message}`);
}


switch (event.type) {
case 'checkout.session.completed':
const session = event.data.object;
const customerEmail = session.customer_details.email;
const customerPhone = session.customer_details.phone;
const amount = session.amount_total / 100;
const paymentTime = new Date(session.payment_intent.created * 1000);

// Store order details in Firestore
await db.collection('orders').add({
email: customerEmail,
amount,
service: session.line_items.data[0].description,
paymentTime,
status: 'completed',
});

sendSMS(customerPhone, `Payment successful! Amount: $${amount} Service: ${session.line_items.data[0].description} Paid at: ${paymentTime.toLocaleString()}`);
break;

case 'checkout.session.expired':
const expiredSession = event.data.object;
const expiredPhone = expiredSession.customer_details.phone;

sendSMS(expiredPhone, 'Your payment link has expired. Please try again.');
break;

case 'checkout.session.async_payment_failed':
const failedSession = event.data.object;
const failedPhone = failedSession.customer_details.phone;

sendSMS(failedPhone, 'Payment failed. Please try again.');
break;

default:
console.log(`Unhandled event type ${event.type}.`);
}

response.status(200).send("ok").end();
});

function sendSMS(phoneNumber, message) {
twilio.messages
.create({
body: message,
from: functions.config().twilio.phone_number,
to: phoneNumber,
})
.then((message) => console.log(`SMS sent: ${message.sid}`))
.catch((error) => console.error(`Error sending SMS: ${error}`));
}
}
)


exports.stripeWebhook = functions.https.onRequest(async (request, response) => {
cors(request, response, async () => {
const event = request.rawBody;

switch (event.type) {
case 'payment_intent.succeeded':
const paymentIntent = event.data.object;
console.log('Payment intent succeeded:', paymentIntent);
// Handle the successful payment intent
handlePaymentIntentSucceeded(paymentIntent);
break;

case 'payment_method.attached':
const paymentMethod = event.data.object;
console.log('Payment method attached:', paymentMethod);
// Handle the successful attachment of a PaymentMethod
handlePaymentMethodAttached(paymentMethod);
break;

// ... handle other event types

default:
console.log(`Unhandled event type ${event.type}`);
}

response.json({ received: true });
});
});

function handlePaymentIntentSucceeded(paymentIntent) {
// Your code to handle a successful payment intent
// For example, you can store the payment details in Firestore
const customerEmail = paymentIntent.charges.data[0].billing_details.email;
const amount = paymentIntent.charges.data[0].amount / 100;
const paymentTime = new Date(paymentIntent.charges.data[0].created * 1000);

db.collection('orders').add({
email: customerEmail,
amount,
paymentTime,
status: 'completed',
});

// You can also send an SMS notification
const customerPhone = paymentIntent.charges.data[0].billing_details.phone;
sendSMS(customerPhone, `Payment successful! Amount: $${amount} Paid at: ${paymentTime.toLocaleString()}`);
}

function handlePaymentMethodAttached(paymentMethod) {
// Your code to handle the successful attachment of a PaymentMethod
// For example, you can store the payment method details in Firestore
const customerId = paymentMethod.customer;
const paymentMethodId = paymentMethod.id;

db.collection('customers').doc(customerId).collection('paymentMethods').doc(paymentMethodId).set({
paymentMethodId,
created: paymentMethod.created,
});
}

function sendSMS(phoneNumber, message) {
twilio.messages
.create({
body: message,
from: functions.config().twilio.phone_number,
to: phoneNumber,
})
.then((message) => console.log(`SMS sent: ${message.sid}`))
.catch((error) => console.error(`Error sending SMS: ${error}`));
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"type": "service_account",
"project_id": "ivanprojo-72b52",
"private_key_id": "3b0f8c89bfbc207b7d9d0c8034754489f8ee21d3",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDeG1vYV8/MgzYR\nQswTe2QwM2Fxl+JW/318jki/Aea8Vt9cVY2qHiJdX4UtYd3O+4VOaVH2unWQPfdO\nTiA2/0FBsarnGzZzGdV/hRbp0Xea7WuxUfUJvbEDC3Q4/xFKpr3bjBvBrPi5uvnI\nOOfVk7HmHK4geHSTXtxNpuFoobjlATodNF/64V/g6vLnN2Z1E8p2o/vW+GnI0Obs\nGFVkPflVm+2m+la4Lvj6wKIyNVcs6Z3QfNAn1WSEMUIr1AMAnpbsVrhMxiUyZTAU\nwY3d7N9I9IHIjsj6dz4sWRFy2oaWAwaNd4GQsd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EBDGOGu48eF\n7AyQXJpnbM+8PvM+9MUBIjxwgnznqyaRLPISHuZVAoGAUHa8bL+2Wgfnn+6etR00\nI/6a1xmk9BOFa1ia0OwopsoWrCrw5+sj7depQ1EDLrf3oriAr4fHCUbDpde69V2k\nM55VWib92+7hqEZA7DeImF5dUlb5vOYOPjbIhdBbJUeVGDnxyWEcIKae926ICblq\nSMb9s/o21lie2goIRLQGses=\n-----END PRIVATE KEY-----\n",
"client_email": "firebase-adminsdk-48vxh@ivanprojo-72b52.iam.gserviceaccount.com",
"client_id": "108319491395249892768",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-48vxh%40ivanprojo-72b52.iam.gserviceaccount.com",
"universe_domain": "googleapis.com"
}

Loading