Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to initialize a customer for the first time. I have a form where they sign up and everything, and they submit it. On the client, the following happens:

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

On the serverside, I am trying to do something like this:

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

It would seem that the Stripe API doesn't like this

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

Is there a canonical way to make multiple requests to stripe on the server for a single token?

like image 971
corvid Avatar asked May 19 '15 19:05

corvid


1 Answers

It seems that you're running into this issue because you're accidentally trying to reuse a token to create a new card for a customer when, unbeknownst to you, you've already used that token to create that card for that user. Creating a customer with a stored card is actually much easier than you expect: when you initialize a customer object with a token, the Stripe API goes ahead and stores that card in association with the new customer. That is, you can immediately go ahead and make a charge to your customer upon creation as in:

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

For more information, I'd recommend the Stripe docs at https://support.stripe.com/questions/can-i-save-a-card-and-charge-it-later and https://stripe.com/docs/api/node#create_customer.

Let me know if that solves your problem!

like image 167
agentcoops Avatar answered Nov 01 '22 10:11

agentcoops