Skip to content

Instantly share code, notes, and snippets.

@kianaditya
Last active August 30, 2019 14:04
Show Gist options
  • Save kianaditya/2b81eb7a168884ac16078f37c93243b9 to your computer and use it in GitHub Desktop.
Save kianaditya/2b81eb7a168884ac16078f37c93243b9 to your computer and use it in GitHub Desktop.
Adds stripe elements and creates a basic payment form
//CheckoutForm.js
import React, { Component } from "react";
import {
CardNumberElement,
CardExpiryElement,
CardCVCElement,
injectStripe
} from "react-stripe-elements";
const axios = require("axios");
class CheckoutForm extends Component {
state = {
error: false,
loading: false
};
payWithStripe = async ev => {
ev.preventDefault();
this.setState({ loading: true });
//We use stripe.createToken method to crete a stripe token and optionally pass arguments
await this.props.stripe.createToken().then(({ token }) => {
if (token) {
this.payment(token.id); //pass received token to our payment function
} else {
this.props.broadcastError("Something went wrong, please try again");
this.setState({ error: true, loading: false });
}
});
};
// Payment function handles API calls and processes confirmation/error from API
payment = async stripeToken => {
try {
let response = await axios.post(
stripeToken,
// Params requied by API go here
);
if (response.data) {
// Process data, update states etc.
}
} catch (error) {
console.log(error);
this.setState({ loading: false });
}
};
// We are rendering Stripe Elements, comments added for further clarity
render() {
return (
<div>
<label>Card number </label>
<CardNumberElement id="card_number" /> //Card number input
<label> Expiration date</label>
<CardExpiryElement /> // Card expiry date
<label>CVC</label>
<CardCVCElement /> // CVC/CVV input element
// Submit button goes below the form
<Button
onClick={this.payWithStripe} // triggers payWithStripe function
>
Submit Payment
</Button>
</div>
);
}
}
//InjectStripe is the HOC required to process information typed in the Stripe elements by user.
export default injectStripe(CheckoutForm);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment