fractal5
fractal5

Reputation: 2132

React - Using async with stripe createPaymentMethod

I am migrating from Stripe V2 to V3.

With V2 I was using an async method to get the stripe token

  Stripe.card.createToken({
    number: creditCardNumber,
    cvc: securityCode,
    name: creditCardHolderName,
    exp_month: expiryMonth,
    exp_year: expiryYear,
  }, async (status, response) => {
    console.log('do stuff here')
  })

And this works fine

But when I use createPaymentMethod from stripe V3 in the same way:

  stripe.createPaymentMethod({
    type: 'card',
    card: cardElement,
    billing_details: {
      name: 'Jenny Rosen',
    },
  }, async (status, response) => {
    console.log('do stuff here')
  })

The network request to Stripe works and returns a 200 success, but it doesn't reach the console.log statement.

Am I doing something wrong here? I don't see why this wouldn't work.

Thanks

Upvotes: 1

Views: 1246

Answers (1)

segFault
segFault

Reputation: 4054

The reason your V2 stripe.card.createToken() call works as expected, is because that function accepts 2 arguments, the payload and a response handler. Whereas V3 stripe.createPaymentMethod() does not allow for the same syntax, it only accepts a payload and returns a Promise.

In order to use async/await with createPaymentMethod() you could try to adjust your syntax as follows:

const { paymentMethod, error } = await stripe.createPaymentMethod({
    type: 'card',
    card: cardElement,
    billing_details: {
      name: 'Jenny Rosen',
    },
});

Alternatively, the traditional Promise.then() should work too.

Example:

stripe.createPaymentMethod({
    type: 'card',
    card: cardElement,
    billing_details: {
      name: 'Jenny Rosen',
    },
}).then(({ paymentMethod, error }) => {
    // do your stuff here...
});

Upvotes: 2

Related Questions