sample-code-node icon indicating copy to clipboard operation
sample-code-node copied to clipboard

Implementation on ReactJS

Open vamshi9 opened this issue 6 years ago • 0 comments

How can I use AcceptJS on the client side? I am using ReactJS on the front end and Serverless, NodeJS on the backend. It is a bit confusing to implement AcceptJS. Previously when I have used stripe , it was pretty much straight forward.

import StripeCheckout from 'react-stripe-checkout';

import config from '../config';

class PayButton extends React.Component {
  constructor(props) {
    super(props);
    this.onToken = this.onToken.bind(this);
  }

  async onToken(token) { // On a successful tokenization request,
    const res = await fetch(config.stripe.apiUrl, { // POST to our backend server with the token and charge details
      method: 'POST',
      body: JSON.stringify({
        token,
        charge: {
          amount: this.props.amount,
          currency: config.stripe.currency,
        },
      }),
    });
    const data = await res.json();
    console.log('onToken');
    console.log(data);
  }

  render() {
    return (
      <StripeCheckout
        name="Serverless Stripe Store Inc."
        token={this.onToken}
        amount={this.props.amount}
        currency={config.stripe.currency}
        stripeKey={config.stripe.apiKey} // Stripe publishable API Key
        allowRememberMe={false}
      />
    );
  }
}```

In the backend though, it is
```const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

module.exports.handler = (event, context, callback) => {
  const requestBody = JSON.parse(event.body);
  const token = requestBody.token.id;
  const amount = requestBody.charge.amount;
  const currency = requestBody.charge.currency;

  return stripe.charges.create({ // Create Stripe charge with token
    amount,
    currency,
    description: 'Serverless Stripe Test charge',
    source: token,
  })
    .then((charge) => { // Success response
      const response = {
        statusCode: 200,
        headers: {
          'Access-Control-Allow-Origin': '*',
        },
        body: JSON.stringify({
          message: `Charge processed succesfully!`,
          charge,
        }),
      };
      callback(null, response);
    })
    .catch((err) => { // Error response
      const response = {
        statusCode: 500,
        headers: {
          'Access-Control-Allow-Origin': '*',
        },
        body: JSON.stringify({
          error: err.message,
        }),
      };
      callback(null, response);
    })
};```

Is there an equivalent method to implement this?

vamshi9 avatar Jun 20 '19 10:06 vamshi9