├── .gitignore
├── package-lock.json
├── package.json
├── public
├── favicon.ico
├── index.html
└── manifest.json
├── src
├── @types
│ └── react-toast-notifications.d.ts
├── App.test.js
├── App.tsx
├── Components
│ ├── ErrorHandler.tsx
│ ├── ErrorMessage.tsx
│ ├── Styles.tsx
│ └── SubscribeToProduct.tsx
├── Theme
│ ├── Colors.ts
│ └── index.ts
├── Utils
│ ├── API.ts
│ └── Consts.ts
├── index.tsx
├── react-app-env.d.ts
└── serviceWorker.js
└── tsconfig.json
/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # production
12 | /build
13 |
14 | # misc
15 | .DS_Store
16 | .env.local
17 | .env.development.local
18 | .env.test.local
19 | .env.production.local
20 |
21 | npm-debug.log*
22 | yarn-debug.log*
23 | yarn-error.log*
24 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "payment-frontend",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "bootstrap": "^4.3.1",
7 | "react": "^16.8.6",
8 | "react-dom": "^16.8.6",
9 | "react-scripts": "3.0.0",
10 | "react-stripe-checkout": "^2.6.3",
11 | "react-toast-notifications": "^1.4.0",
12 | "reactstrap": "^8.0.0",
13 | "styled-components": "^4.2.0"
14 | },
15 | "scripts": {
16 | "start": "react-scripts start",
17 | "build": "react-scripts build",
18 | "test": "react-scripts test",
19 | "eject": "react-scripts eject"
20 | },
21 | "eslintConfig": {
22 | "extends": "react-app"
23 | },
24 | "browserslist": {
25 | "production": [
26 | ">0.2%",
27 | "not dead",
28 | "not op_mini all"
29 | ],
30 | "development": [
31 | "last 1 chrome version",
32 | "last 1 firefox version",
33 | "last 1 safari version"
34 | ]
35 | },
36 | "devDependencies": {
37 | "@types/react": "^16.8.16",
38 | "@types/react-dom": "^16.8.4",
39 | "@types/reactstrap": "^8.0.1",
40 | "@types/styled-components": "^4.1.14",
41 | "typescript": "^3.4.5"
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LukeMwila/react-stripe-subscriptions-frontend/e5268c35e5438c7a7586e7ab1779282dbcc0f76d/public/favicon.ico
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
22 | React App
23 |
24 |
25 |
26 |
27 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React App",
3 | "name": "Create React App Sample",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | }
10 | ],
11 | "start_url": ".",
12 | "display": "standalone",
13 | "theme_color": "#000000",
14 | "background_color": "#ffffff"
15 | }
16 |
--------------------------------------------------------------------------------
/src/@types/react-toast-notifications.d.ts:
--------------------------------------------------------------------------------
1 | declare module "react-toast-notifications";
2 |
--------------------------------------------------------------------------------
/src/App.test.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import App from './App';
4 |
5 | it('renders without crashing', () => {
6 | const div = document.createElement('div');
7 | ReactDOM.render(, div);
8 | ReactDOM.unmountComponentAtNode(div);
9 | });
10 |
--------------------------------------------------------------------------------
/src/App.tsx:
--------------------------------------------------------------------------------
1 | import * as React from "react";
2 | import { ToastProvider } from "react-toast-notifications";
3 | import SubscribeToProduct from "./Components/SubscribeToProduct";
4 |
5 | /** Styling */
6 | import { AppWrapper } from "./Components/Styles";
7 |
8 | const App: React.FC<{}> = () => {
9 | return (
10 |
11 |
12 |
13 |
14 |
15 | );
16 | };
17 |
18 | export default App;
19 |
--------------------------------------------------------------------------------
/src/Components/ErrorHandler.tsx:
--------------------------------------------------------------------------------
1 | import * as React from "react";
2 |
3 | const useErrorHandler = (initialState: string | null) => {
4 | const [error, setError] = React.useState(initialState);
5 | const showError = (errorMessage: string | null) => {
6 | setError(errorMessage);
7 | window.setTimeout(() => {
8 | setError(null);
9 | }, 3000);
10 | };
11 | return { error, showError };
12 | };
13 |
14 | export default useErrorHandler;
15 |
--------------------------------------------------------------------------------
/src/Components/ErrorMessage.tsx:
--------------------------------------------------------------------------------
1 | import * as React from "react";
2 | import styled from "styled-components";
3 |
4 | /** Theme */
5 | import { Colors } from "../Theme";
6 |
7 | type ErrorMessageProps = {
8 | errorMessage: string | null;
9 | };
10 |
11 | const ErrorMessage = styled.p`
12 | text-align: center;
13 | margin-top: 10px;
14 | color: ${Colors.red};
15 | `;
16 |
17 | const ErrorMessageContainer: React.SFC = ({
18 | errorMessage
19 | }) => {
20 | return {errorMessage};
21 | };
22 |
23 | export default ErrorMessageContainer;
24 |
--------------------------------------------------------------------------------
/src/Components/Styles.tsx:
--------------------------------------------------------------------------------
1 | import styled from "styled-components";
2 |
3 | /** Theme */
4 | import { Colors } from "../Theme";
5 |
6 | export const AppWrapper = styled.div`
7 | display: flex;
8 | flex: 1;
9 | min-height: 100vh;
10 | margin: 20px;
11 | flex-direction: column;
12 | `;
13 |
14 | export const SubscriptionPlansWrapper = styled.div`
15 | width: 100%;
16 | height: auto;
17 | `;
18 |
19 | export const SubscriptionPlanCard = styled.div`
20 | margin: auto;
21 | padding: 10px;
22 | border-radius: 8px;
23 | border-top: 5px solid ${Colors.aqua};
24 | height: auto;
25 | box-shadow: 0 2px 2px 0 rgba(14, 30, 37, 0.32);
26 | `;
27 |
28 | export const SubscriptionPlanCardHeading = styled.h2`
29 | text-align: center;
30 | font-size: 1.65em;
31 | color: ${Colors.aqua};
32 | padding: 7px;
33 | text-transform: capitalize;
34 | `;
35 |
36 | export const SubscriptionPlanCardPrice = styled.h2`
37 | color: ${Colors.aqua};
38 | text-align: center;
39 | font-size: 2.95em;
40 | `;
41 |
42 | export const CurrencySymbol = styled.span`
43 | color: ${Colors.grey};
44 | font-size: 0.5em;
45 | `;
46 |
47 | export const SubscriptionPlanCardSubHeading = styled.p`
48 | color: ${Colors.aqua};
49 | font-weight: 100;
50 | text-align: center;
51 | border-bottom: 1px dotted ${Colors.lightGrey};
52 | padding-bottom: 10px;
53 | `;
54 |
--------------------------------------------------------------------------------
/src/Components/SubscribeToProduct.tsx:
--------------------------------------------------------------------------------
1 | import * as React from "react";
2 | import { Row, Col, Button } from "reactstrap";
3 | import { withToastManager } from "react-toast-notifications";
4 | import StripeCheckout from "react-stripe-checkout";
5 | import ErrorMessage from "./ErrorMessage";
6 | import useErrorHandler from "./ErrorHandler";
7 |
8 | /** Styling */
9 | import {
10 | CurrencySymbol,
11 | SubscriptionPlansWrapper,
12 | SubscriptionPlanCard,
13 | SubscriptionPlanCardHeading,
14 | SubscriptionPlanCardPrice,
15 | SubscriptionPlanCardSubHeading
16 | } from "./Styles";
17 |
18 | /** Utils */
19 | import {
20 | PRODUCT_PLANS,
21 | Product,
22 | STRIPE_PUBLISHABLE_KEY
23 | } from "../Utils/Consts";
24 | import { apiRequest } from "../Utils/API";
25 |
26 | type StripeToken = {
27 | card: {};
28 | client_ip: string;
29 | created: number;
30 | email: string;
31 | id: string;
32 | object: string;
33 | type: string;
34 | used: boolean;
35 | livemode: boolean;
36 | };
37 |
38 | type ToastNotificationType = {
39 | add(message: string, {}): void;
40 | };
41 |
42 | type Props = {
43 | toastManager: ToastNotificationType;
44 | };
45 |
46 | const SubscribeToProduct: React.FC = ({ toastManager }) => {
47 | const { error, showError } = useErrorHandler(null);
48 |
49 | /**
50 | * Make request to AWS lambda function that handles creating
51 | * a customer and a subscription plan on stripe
52 | * @param token - token with stripe key and details entered in stripe form
53 | * @param productPlan - id of the product plan the user is subscribing to
54 | */
55 | const subscribeToProductPlan = async (
56 | token: StripeToken,
57 | productPlan: string
58 | ) => {
59 | const bodyParams = {
60 | stripeToken: token.id,
61 | email: token.email,
62 | productPlan
63 | };
64 |
65 | const response = await apiRequest(
66 | "http://localhost:4000/create-customer",
67 | "POST",
68 | bodyParams
69 | ).catch(e => {
70 | showError(e.message);
71 | });
72 |
73 | toastNotification("Subscription successful");
74 | };
75 |
76 | /**
77 | * List product plans
78 | * @param productPlans - array of product plans created in Stripe account that a user can subscribe to
79 | */
80 | const displayProductPlans = (
81 | productPlans: Array
82 | ): React.ReactNode => {
83 | if (productPlans && productPlans.length) {
84 | return productPlans.map((product: Product, i: number) => {
85 | return (
86 |
87 |
88 |
89 | {product.name}
90 |
91 |
92 | $ {product.price}
93 |
94 |
95 | billed monthly
96 |
97 |
98 | {product.description}
99 |
100 |
101 | {product.users}
102 |
103 |
104 |
105 | subscribeToProductPlan(token, product.id)}
109 | billingAddress={true}
110 | zipCode={true}
111 | panelLabel="Subscribe"
112 | stripeKey={STRIPE_PUBLISHABLE_KEY}
113 | >
114 |
115 |
116 |
117 |
118 | );
119 | });
120 | }
121 | return "No existing product plans";
122 | };
123 |
124 | /**
125 | * Toast notification
126 | * @param message - notification message to be displayed
127 | */
128 | const toastNotification = (message: string) => {
129 | toastManager.add(message, {
130 | appearance: "success",
131 | autoDismiss: true
132 | });
133 | };
134 |
135 | return (
136 |
137 | {displayProductPlans(PRODUCT_PLANS)}
138 | {error && }
139 |
140 | );
141 | };
142 |
143 | export default withToastManager(SubscribeToProduct);
144 |
--------------------------------------------------------------------------------
/src/Theme/Colors.ts:
--------------------------------------------------------------------------------
1 | const Colors = {
2 | aqua: "#33cccc",
3 | grey: "#666",
4 | lightGrey: "#ccc",
5 | red: "#cc0000"
6 | };
7 |
8 | export default Colors;
9 |
--------------------------------------------------------------------------------
/src/Theme/index.ts:
--------------------------------------------------------------------------------
1 | import Colors from "./Colors";
2 |
3 | export { Colors };
4 |
--------------------------------------------------------------------------------
/src/Utils/API.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * API Request
3 | * @param endPoint - api endpoint
4 | * @param httpMethod - the http method defining the type of request (POST/GET/PUT/PATCH)
5 | * @param bodyParams - object with properties being passed with the request
6 | */
7 |
8 | export const apiRequest = async (
9 | endPoint: string,
10 | httpMethod: string,
11 | bodyParams?: object
12 | ): Promise => {
13 | const response = await fetch(endPoint, {
14 | method: httpMethod,
15 | headers: {
16 | Accept: "application/json",
17 | "Content-Type": "application/json"
18 | },
19 | body: JSON.stringify(bodyParams)
20 | });
21 |
22 | return await response.json();
23 | };
24 |
--------------------------------------------------------------------------------
/src/Utils/Consts.ts:
--------------------------------------------------------------------------------
1 | export type Product = {
2 | id: string;
3 | name: string;
4 | description: string;
5 | users: string;
6 | price: number;
7 | };
8 |
9 | /** Stripe publishable key */
10 | export const STRIPE_PUBLISHABLE_KEY = "";
11 |
12 | /** Stripe product plan ids */
13 | const STANDARD_PRODUCT_ID = "";
14 | const PREMIUM_PRODUCT_ID = "";
15 | const ENTERPRISE_PRODUCT_ID = "";
16 |
17 | /** Stripe product plans */
18 | export const PRODUCT_PLANS: Array = [
19 | {
20 | id: STANDARD_PRODUCT_ID,
21 | name: "Standard",
22 | description: "For small teams.",
23 | users: "4 users",
24 | price: 10
25 | },
26 | {
27 | id: PREMIUM_PRODUCT_ID,
28 | name: "Premium",
29 | description: "For medium sized teams.",
30 | users: "20 users",
31 | price: 25
32 | },
33 | {
34 | id: ENTERPRISE_PRODUCT_ID,
35 | name: "Enterprise",
36 | description: "For large teams.",
37 | users: "100+ users",
38 | price: 50
39 | }
40 | ];
41 |
--------------------------------------------------------------------------------
/src/index.tsx:
--------------------------------------------------------------------------------
1 | import * as React from "react";
2 | import * as ReactDOM from "react-dom";
3 | import App from "./App";
4 | import * as serviceWorker from "./serviceWorker";
5 |
6 | /** Bootstrap */
7 | import "bootstrap/dist/css/bootstrap.css";
8 |
9 | ReactDOM.render(, document.getElementById("root"));
10 |
11 | // If you want your app to work offline and load faster, you can change
12 | // unregister() to register() below. Note this comes with some pitfalls.
13 | // Learn more about service workers: https://bit.ly/CRA-PWA
14 | serviceWorker.unregister();
15 |
--------------------------------------------------------------------------------
/src/react-app-env.d.ts:
--------------------------------------------------------------------------------
1 | ///
2 |
--------------------------------------------------------------------------------
/src/serviceWorker.js:
--------------------------------------------------------------------------------
1 | // This optional code is used to register a service worker.
2 | // register() is not called by default.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on subsequent visits to a page, after all the
7 | // existing tabs open on the page have been closed, since previously cached
8 | // resources are updated in the background.
9 |
10 | // To learn more about the benefits of this model and instructions on how to
11 | // opt-in, read https://bit.ly/CRA-PWA
12 |
13 | const isLocalhost = Boolean(
14 | window.location.hostname === 'localhost' ||
15 | // [::1] is the IPv6 localhost address.
16 | window.location.hostname === '[::1]' ||
17 | // 127.0.0.1/8 is considered localhost for IPv4.
18 | window.location.hostname.match(
19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
20 | )
21 | );
22 |
23 | export function register(config) {
24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
25 | // The URL constructor is available in all browsers that support SW.
26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
27 | if (publicUrl.origin !== window.location.origin) {
28 | // Our service worker won't work if PUBLIC_URL is on a different origin
29 | // from what our page is served on. This might happen if a CDN is used to
30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
31 | return;
32 | }
33 |
34 | window.addEventListener('load', () => {
35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
36 |
37 | if (isLocalhost) {
38 | // This is running on localhost. Let's check if a service worker still exists or not.
39 | checkValidServiceWorker(swUrl, config);
40 |
41 | // Add some additional logging to localhost, pointing developers to the
42 | // service worker/PWA documentation.
43 | navigator.serviceWorker.ready.then(() => {
44 | console.log(
45 | 'This web app is being served cache-first by a service ' +
46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA'
47 | );
48 | });
49 | } else {
50 | // Is not localhost. Just register service worker
51 | registerValidSW(swUrl, config);
52 | }
53 | });
54 | }
55 | }
56 |
57 | function registerValidSW(swUrl, config) {
58 | navigator.serviceWorker
59 | .register(swUrl)
60 | .then(registration => {
61 | registration.onupdatefound = () => {
62 | const installingWorker = registration.installing;
63 | if (installingWorker == null) {
64 | return;
65 | }
66 | installingWorker.onstatechange = () => {
67 | if (installingWorker.state === 'installed') {
68 | if (navigator.serviceWorker.controller) {
69 | // At this point, the updated precached content has been fetched,
70 | // but the previous service worker will still serve the older
71 | // content until all client tabs are closed.
72 | console.log(
73 | 'New content is available and will be used when all ' +
74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
75 | );
76 |
77 | // Execute callback
78 | if (config && config.onUpdate) {
79 | config.onUpdate(registration);
80 | }
81 | } else {
82 | // At this point, everything has been precached.
83 | // It's the perfect time to display a
84 | // "Content is cached for offline use." message.
85 | console.log('Content is cached for offline use.');
86 |
87 | // Execute callback
88 | if (config && config.onSuccess) {
89 | config.onSuccess(registration);
90 | }
91 | }
92 | }
93 | };
94 | };
95 | })
96 | .catch(error => {
97 | console.error('Error during service worker registration:', error);
98 | });
99 | }
100 |
101 | function checkValidServiceWorker(swUrl, config) {
102 | // Check if the service worker can be found. If it can't reload the page.
103 | fetch(swUrl)
104 | .then(response => {
105 | // Ensure service worker exists, and that we really are getting a JS file.
106 | const contentType = response.headers.get('content-type');
107 | if (
108 | response.status === 404 ||
109 | (contentType != null && contentType.indexOf('javascript') === -1)
110 | ) {
111 | // No service worker found. Probably a different app. Reload the page.
112 | navigator.serviceWorker.ready.then(registration => {
113 | registration.unregister().then(() => {
114 | window.location.reload();
115 | });
116 | });
117 | } else {
118 | // Service worker found. Proceed as normal.
119 | registerValidSW(swUrl, config);
120 | }
121 | })
122 | .catch(() => {
123 | console.log(
124 | 'No internet connection found. App is running in offline mode.'
125 | );
126 | });
127 | }
128 |
129 | export function unregister() {
130 | if ('serviceWorker' in navigator) {
131 | navigator.serviceWorker.ready.then(registration => {
132 | registration.unregister();
133 | });
134 | }
135 | }
136 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "lib": [
5 | "dom",
6 | "dom.iterable",
7 | "esnext"
8 | ],
9 | "allowJs": true,
10 | "skipLibCheck": true,
11 | "esModuleInterop": true,
12 | "allowSyntheticDefaultImports": true,
13 | "strict": true,
14 | "forceConsistentCasingInFileNames": true,
15 | "module": "esnext",
16 | "moduleResolution": "node",
17 | "resolveJsonModule": true,
18 | "isolatedModules": true,
19 | "noEmit": true,
20 | "jsx": "preserve"
21 | },
22 | "include": [
23 | "src"
24 | ]
25 | }
26 |
--------------------------------------------------------------------------------