devjavi
devjavi

Reputation: 23

Adding Card to Stripe customer with NodeJS

I'm building my addCard controller in my NodeJS app to add a card to an existing stripe customer. Currently I have it working with the following code:

const user = await User.findById(req.params.user_id)

    //Send error if user is not found
    if(!user){
        return next(new ErrorResponse('Resource not found', 404))
    }
await Stripe.customers.retrieve(
        user.stripe.customer_id,
        async function(err, customer) {
            if (err){
                return next(new ErrorResponse(err.message, err.statusCode))
            } else{
                if(customer.sources.data.length > 0){
                    return next(new ErrorResponse('User already has a card on file', 403));
                } else{
                    //If no card on file, create a new card for the user
                    await Stripe.customers.createSource(
                        user.stripe.customer_id,
                        {source: req.body.cardtok}, //card token generated by client
                        async function(err, card) {
                            if(err){
                                return next(new ErrorResponse(err.message, err.statusCode));
                            } else{
                                res.status(200).json({
                                    success: true,
                                    data: card
                                });            
                            }
                        }
                    );

                }
            }
        }
    );

Is there a better way? While my code does work as expected I can't avoid thinking is a little messy. I'm using Node, express and mongodb.

Upvotes: 0

Views: 450

Answers (1)

floatingLomas
floatingLomas

Reputation: 8727

It looks like you're mixing up async/await and callbacks here; I think you can do it like this instead:

const user = await User.findById(req.params.user_id);

//Send error if user is not found
if (!user) {
  return next(new ErrorResponse("Resource not found", 404));
}

let customer;
try {
  customer = await Stripe.customers.retrieve(user.stripe.customer_id);
} catch (err) {
  return next(new ErrorResponse(err.message, err.statusCode));
}

if (customer.sources.data.length > 0) {
  return next(new ErrorResponse("User already has a card on file", 403));
}

//If no card on file, create a new card for the user
let card;

try {
  card = Stripe.customers.createSource(
    user.stripe.customer_id,
    { source: req.body.cardtok } //card token generated by client
  );
} catch (err) {
  return next(new ErrorResponse(err.message, err.statusCode));
}

res.status(200).json({
  success: true,
  data: card,
});

Upvotes: 1

Related Questions