如何使用 Stripe 在一次操作中同时创建客户和卡片?

How to create both a customer and a card in a single action with Stripe?

我是第一次尝试初始化客户。我有一个表格,他们可以在上面注册和填写所有内容,然后他们提交。在客户端上,会发生以下情况:

var cardValues = AutoForm.getFormValues('credit-card-form').insertDoc;
Stripe.createToken(cardValues, function (err, token) {
  if (!err && token) {
    Meteor.call('Stripe.initializeCustomer', token);
  }
});

在服务器端,我正在尝试做这样的事情:

Meteor.methods({
  'Stripe.initializeCustomer': function (token) {
    var Stripe = StripeAPI(process.env.STRIPE_KEY);
    // some validation here that nobody cares about
    Stripe.customers.create({
      source: token
    }).then(function (customer) {
      return Stripe.customers.createCard(customer.id, {
        source: token
      })
    }).catch(function (error) {
      // need to do something here
    })
  }
});

条纹 API 似乎不喜欢这样

Unhandled rejection Error: You cannot use a Stripe token more than once

是否有一种规范的方法可以针对单个令牌在服务器上发出多个条带化请求?

您 运行 似乎陷入了这个问题,因为您不小心尝试重复使用令牌为客户创建新卡,而您并不知道您已经使用了该令牌为该用户创建该卡。使用存储卡创建客户实际上比您预期的要容易得多:当您使用令牌初始化客户对象时,Stripe API 会继续存储与新客户关联的卡。也就是说,您可以立即继续并在创建后向您的客户收费,如下所示:

Stripe.customers.create({
  source: token.id
}).then(function (customer) {
    Stripe.charge.create({
       amount: 1000,
       currency: 'usd',
       customer: customer.id 
    });
});

有关更多信息,我推荐 https://support.stripe.com/questions/can-i-save-a-card-and-charge-it-later and https://stripe.com/docs/api/node#create_customer 上的 Stripe 文档。

如果这能解决您的问题,请告诉我!