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

Functions: Handle "charge.updated" events to process updated balance transactions from Stripe #1007

Merged
merged 2 commits into from
Jan 12, 2025
Merged
Changes from 1 commit
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
Next Next commit
Functions: Handle "charge.updated" events to process updated balance …
…transactions from Stripe
mkue committed Jan 11, 2025
commit 1089964e546d79060fa4349ec33f338de60544d5
9 changes: 5 additions & 4 deletions functions/src/webhooks/stripe/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { DocumentReference, DocumentSnapshot } from 'firebase-admin/firestore';
import { logger } from 'firebase-functions';
import { onRequest } from 'firebase-functions/v2/https';
import Stripe from 'stripe';
import { FirestoreAdmin } from '../../../../shared/src/firebase/admin/FirestoreAdmin';
import { SendgridSubscriptionClient } from '../../../../shared/src/sendgrid/SendgridSubscriptionClient';
import { StripeEventHandler } from '../../../../shared/src/stripe/StripeEventHandler';
@@ -43,12 +42,14 @@ export default onRequest(async (request, response) => {
try {
const sig = request.headers['stripe-signature']!;
const event = stripeEventHandler.constructWebhookEvent(request.rawBody, sig, STRIPE_WEBHOOK_SECRET);
const charge = event.data.object as Stripe.Charge;
switch (event.type) {
case 'charge.succeeded':
// The charge.succeeded events do sometimes not contain the balance_transaction, so we need to listen to charge.updated event
// to get the final balance_transaction and update the contribution document with the final amount.
case 'charge.updated':
case 'charge.failed': {
const contributionRef = await stripeEventHandler.handleChargeEvent(charge);
logger.info(`Charge event ${event.type} handled for charge ${charge.id}.`);
const contributionRef = await stripeEventHandler.handleChargeEvent(event.data.object);
logger.info(`Charge event ${event.type} handled for charge ${event.data.object.id}.`);
if (contributionRef) {
logger.info(`Created contribution ${contributionRef.id}. Adding contributor to newsletter.`);
try {
17 changes: 9 additions & 8 deletions shared/src/stripe/StripeEventHandler.ts
Original file line number Diff line number Diff line change
@@ -33,12 +33,12 @@ export class StripeEventHandler {

const checkoutMetadata = await this.getCheckoutMetadata(charge);

// We only store non-successful charges if the user already exists.
// This prevents us from having users in the database that never made a successful contribution.
if (
fullCharge.status === 'succeeded' ||
(await this.findFirestoreUser(await this.retrieveStripeCustomer(fullCharge.customer as string)))
) {
const firestoreUser = await this.findFirestoreUser(
await this.retrieveStripeCustomer(fullCharge.customer as string),
);
if (fullCharge.status === 'succeeded' || firestoreUser) {
// We only store non-successful charges if the user already exists.
// This prevents us from having users in the database that never made a successful contribution.
return await this.storeCharge(fullCharge, checkoutMetadata);
}
return null;
@@ -101,6 +101,7 @@ export class StripeEventHandler {
const plan = (charge.invoice as Stripe.Invoice)?.lines?.data[0]?.plan;
const monthlyInterval = plan?.interval === 'month' ? plan?.interval_count : plan?.interval === 'year' ? 12 : 0;
const balanceTransaction = charge.balance_transaction as Stripe.BalanceTransaction;

const contribution = {
source: ContributionSourceKey.STRIPE,
created: toFirebaseAdminTimestamp(DateTime.fromSeconds(charge.created)),
@@ -205,8 +206,8 @@ export class StripeEventHandler {
const contributionRef = (
userRef.collection(CONTRIBUTION_FIRESTORE_PATH) as CollectionReference<StripeContribution>
).doc(charge.id);
await contributionRef.set(contribution);
console.info(`Ingested ${charge.id} into firestore for user ${userRef.id}`);
await contributionRef.set(contribution, { merge: true });
console.info(`Updated contribution document: ${contributionRef.path}`);
await this.maybeUpdateCampaign(contribution);
return contributionRef;
};