简体   繁体   English

使用 NodeJS 向 Stripe 客户添加卡片

[英]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.我正在我的 NodeJS 应用程序中构建我的 addCard controller 以向现有的条纹客户添加卡片。 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.我正在使用 Node、express 和 mongodb。

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,
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM