Skip to content

Instantly share code, notes, and snippets.

@mitchellhuang
Created February 24, 2018 06:40
Show Gist options
  • Save mitchellhuang/5de1db8a4954f7660890b2dd2e8abf58 to your computer and use it in GitHub Desktop.
Save mitchellhuang/5de1db8a4954f7660890b2dd2e8abf58 to your computer and use it in GitHub Desktop.
Stripe Elements Next.js (works with SSR)
import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
import { compose } from 'react-apollo';
import cookies from 'next-cookies';
import jsCookie from 'js-cookie';
import Script from 'react-load-script';
import { StripeProvider, Elements } from 'react-stripe-elements';
import Main from '../layouts/Main';
import withData from '../lib/withData';
import { viewerGraphql } from '../apollo/queries/viewer';
import CheckoutForm from '../components/checkout/CheckoutForm';
import checkLoggedIn from '../lib/checkLoggedIn';
import redirect from '../lib/redirect';
class Checkout extends Component {
constructor(props) {
super(props);
this.state = {
stripe: null
};
}
onStripeLoad() {
if (window.Stripe) {
this.setState({
stripe: window.Stripe(process.env.STRIPE_PUB_KEY)
});
}
}
render() {
const { viewerData: { viewer }, token } = this.props;
const checkoutWithStripe = (
<StripeProvider stripe={this.state.stripe}>
<Elements>
<Fragment>
<CheckoutForm
viewer={viewer}
token={token} />
<Script
url='https://js.stripe.com/v3/'
onLoad={() => this.onStripeLoad()} />
</Fragment>
</Elements>
</StripeProvider>
);
return (
<Main viewer={viewer}>
<section className='container container container--no-pad-alt'>
{checkoutWithStripe}
</section>
</Main>
);
}
}
Checkout.getInitialProps = async (context, apolloClient) => {
const { viewer } = await checkLoggedIn(context, apolloClient);
if (!viewer || viewer.acl.id <= 1) {
if (process.browser) {
jsCookie.set('action', context.asPath);
} else {
context.res.cookie('action', context.asPath);
}
redirect(context, '/signup');
}
return { token: cookies(context).token };
};
Checkout.propTypes = {
viewerData: PropTypes.object,
token: PropTypes.string
};
export default compose(
withData,
viewerGraphql
)(Checkout);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment