Stripe Checkout in ReactJS

1.3k views Asked by At

I'm using Stripe Checkout in my React App. Somehow I'm not passing the properties to my onToken function correctly as I'm getting not defined errors.

I eventually need to send a bunch of props, but for now just trying to get it to work correctly.

import axios from 'axios'
import React from 'react'
import StripeCheckout from 'react-stripe-checkout';

const PAYMENT_SERVER_URL = '3RD_PARTY_SERVER';
const CURRENCY = 'USD';

export default class Stripe25 extends React.Component {

  onToken = (token) => {
    axios.post(PAYMENT_SERVER_URL,
        {
          description,
          source: token.id,
          currency: CURRENCY,
          amount: amount
        })
        .then(successPayment)
        .catch(errorPayment);
  }

  render() {
    return (
      <StripeCheckout
        token={this.onToken}
        stripeKey="STRIPE_PUBLIC_KEY"
        name=""
        description=""
        image=""
        panelLabel="Donate"
        amount={2500} // cents
        currency="USD"
        locale="auto"
        zipCode={false}
        billingAddress={true}
      >
      <button className="btn btn-primary">
        $25
      </button>
    </StripeCheckout>
    )
  }
}
3

There are 3 answers

1
Feather On

Try changing source: token.id to source: token && token.id.

The token may not yet be defined when you are trying to set the id. This is often an issue with dot chaining in an async environment.

0
Jack On

From what I can see, in your onToken method, the only available variable is token. But you're also referencing description and amount, neither of which are available anywhere in the scope from what I can tell.

1
tfogg2 On

You will need to pass description and amount into your onToken constant. You can see an example of this as well as how to pass Shipping information into Stripe in this article:

Send Shipping Info to Stripe with React-Stripe-Checkout

The solution will look like this:

const onToken = (amount, description) => (token, args) =>
  axios.post(PAYMENT_SERVER_URL,
    {
      description,
      source: token.id,
      currency: CURRENCY,
      amount: fromDollarToCent(amount),
      metadata: args
    })
    .then(successPayment)
    .catch(errorPayment);

The (token, args) and metadata: args are optional incase you want to pass shipping information into Stripe.