Skip to content

Instantly share code, notes, and snippets.

@reichert621
Last active July 2, 2019 03:13
Show Gist options
  • Save reichert621/3bce0d5c150171a7aa653a473ccfeeb6 to your computer and use it in GitHub Desktop.
Save reichert621/3bce0d5c150171a7aa653a473ccfeeb6 to your computer and use it in GitHub Desktop.
import request from 'superagent';
import React from 'react';
import ReactDOM from 'react-dom';
import {
StripeProvider,
Elements,
CardElement,
injectStripe
} from 'react-stripe-elements';
// Replace with your public key (https://dashboard.stripe.com/test/apikeys)
const STRIPE_API_KEY = 'pk_test_xxx';
// Create a charge by sending an HTTP POST request to our API endpoint
// with the token generated from Stripe Elements below in the form
const createCharge = token => {
return request
.post('/api/charges')
.send({ token })
.then(res => res.body.charge);
};
const Form = props => {
const handleCreateCharge = e => {
e.preventDefault();
// We can use `props.stripe` as a result of the `injectStripe` higher
// order component created below, and then call `createSource` to tokenize
// the user's credit card details provided in the <CardElement />
return props.stripe
.createSource({
type: 'card',
owner: {
name: 'Test User',
email: '[email protected]'
}
})
.then(({ source }) => {
const token = source.id;
return createCharge(token);
})
// We're just using `alert`s for the sake of quick, simple feedback
.then(charge => alert('Charge successfully created!'))
.catch(err => alert('Error creating a charge!'));
};
return (
<form onSubmit={handleCreateCharge}>
<CardElement />
<button type="submit">Create Charge</button>
</form>
);
};
// Calling `injectStripe` makes the `stripe` object
// available on the <Form /> component's `props`
const StripeForm = injectStripe(Form);
// The `<StripeProvider />` passes our API key to the Stripe
// client, and allows us to `injectStripe` into our form above.
// The `<Elements /> component handles mounting our inputs
// (e.g. <CardElement />) with Stripe Elements. For more details:
// https://github.com/stripe/react-stripe-elements#getting-started
const App = () => {
return (
<StripeProvider apiKey={STRIPE_API_KEY}>
<Elements>
<StripeForm />
</Elements>
</StripeProvider>
);
};
ReactDOM.render(<App />, document.getElementById('app'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment