Ad

Stripe Error: You Cannot Use A PaymentMethod As A Source For Customers

I am new to NodeJS, and I am trying to integrate Stripe payments, using Firebase Cloud functions. I Followed these steps:

  1. I got the token from client-side, stored it in Firestore, the token looks like this: pm_1FFhvNDcXKDMgaqV...
  2. I've created a Customer on Stripe

    exports.createNewStripeCustomer = 
    functions.auth.user().onCreate(
    async (user) => {
    const customer = await stripe.customers.create({email: 
    user.email}) ;
    return admin.firestore()
        .collection('customers')
        .doc(user.uid)
        .set({customer_id: customer.id});
    }
    );
    
  3. The above code works.

  4. Now I've tried to add a payment source using the token as specified in tutorials and docs and I keep getting the following error:

Error: You cannot use a payment method as a source for Customers. Instead, use the payment methods API to Attach a Customer to a payment method. See https://stripe.com/docs/api/payment_methods/attach

Here's the code that causes the error:

    exports.newPaymentSource =  functions.firestore.document('customers/{userId}/tokens/{tokenId}').onWrite(async (change, context) => {
    //Get token that strike sdk gave to the client...
    const data = change.after.data();

    if (data ===null) { return null }
    const token = data.tokenId;
    const snapshot = await firestore.collection('customers').doc(context.params.userId).get();
    const customer = snapshot.data().customer_id;

    //calling stripe api...
    console.log(customer + ":"  + token + ":" + context.params.userId);
    const respFromStripe = await stripe.customers.createSource(customer, { source: token });
    // console.log(respFromStripe);
    return firestore.collection('users').doc(context.params.userId)
        .collection('sources').doc(respFromStripe.card.fingerprint).set(respFromStripe, { merge: true });
});
Ad

Answer

PaymentMethod objects (which represent your user's cards) need to be attached to a Customer with /v1/payment_methods/pm_123/attach endpoint or in Stripe-Node:

pm = await stripe.paymentMethods.attach('pm_678', {customer: 'cus_123'});

https://stripe.com/docs/api/payment_methods/attach?lang=node

The way you're using it (customer.createSource()) works for older Tokens (tok_123) and Source (src_123) objects, not PaymentMethods.

Ad
source: stackoverflow.com
Ad