Attach a Source Attach a payment source to the customer record

This lesson is available for PRO members or as a single course purchase. Sign-in and choose a plan below.
Get Unlimited PRO Access

OR


*Enrollment provides full access to this course (and updates) for life.

file_type_typescript sources.ts
import * as functions from 'firebase-functions';
import { assert, assertUID, catchErrors } from './helpers';
import { stripe } from './config'; 
import { getOrCreateCustomer } from './customers';


/**
Attaches a payment source to a stripe customer account.
*/
export const attachSource = async(uid: string, source: string) => {

    const customer = await getOrCreateCustomer(uid);

    const existingSource = customer.sources.data.filter(s => s.id === source).pop(); 

    if (existingSource) {
        return existingSource;
    } 
    else {
        await stripe.customers.createSource(customer.id, { source: source });
        // update default
        return await stripe.customers.update(customer.id, { default_source: source });
    }
}

/////// DEPLOYABLE FUNCTIONS ////////

export const stripeAttachSource = functions.https.onCall( async (data, context) => {
    const uid = assertUID(context);
    const source = assert(data, 'source');

    return catchErrors(attachSource(uid, source));
});

Questions?

Ask questions via GitHub below OR chat on Slack #questions