简体   繁体   中英

Stripe Checkout in ReactJS

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

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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