/** * Form to set the stripe's public and private keys */ import React, { ReactNode, useEffect, useRef, useState } from 'react'; import { Loader } from './loader'; import { useTranslation } from 'react-i18next'; import SettingAPI from '../api/setting'; import { SettingName } from '../models/setting'; import { FabInput } from './fab-input'; import StripeAPI from '../api/stripe'; interface StripeKeysFormProps { onValidKeys: (stripePublic: string, stripeSecret:string) => void } const stripeKeys = SettingAPI.query([SettingName.StripePublicKey, SettingName.StripeSecretKey]); const StripeKeysFormComponent: React.FC = ({ onValidKeys }) => { const { t } = useTranslation('admin'); const mounted = useRef(null); const [publicKey, setPublicKey] = useState(''); const [publicKeyAddOn, setPublicKeyAddOn] = useState(null); const [publicKeyAddOnClassName, setPublicKeyAddOnClassName] = useState(''); const [secretKey, setSecretKey] = useState(''); const [secretKeyAddOn, setSecretKeyAddOn] = useState(null); const [secretKeyAddOnClassName, setSecretKeyAddOnClassName] = useState(''); useEffect(() => { const keys = stripeKeys.read(); setPublicKey(keys.get(SettingName.StripePublicKey)); setSecretKey(keys.get(SettingName.StripeSecretKey)); }, []); useEffect(() => { const validClassName = 'key-valid'; if (publicKeyAddOnClassName === validClassName && secretKeyAddOnClassName === validClassName) { onValidKeys(publicKey, secretKey); } }, [publicKeyAddOnClassName, secretKeyAddOnClassName]); /** * Send a test call to the Stripe API to check if the inputted public key is valid */ const testPublicKey = (key: string) => { if (!key.match(/^pk_/)) { setPublicKeyAddOn(); setPublicKeyAddOnClassName('key-invalid'); return; } StripeAPI.createPIIToken(key, 'test').then(() => { if (!mounted.current) return; setPublicKey(key); setPublicKeyAddOn(); setPublicKeyAddOnClassName('key-valid'); }, reason => { if (!mounted.current) return; if (reason.response.status === 401) { setPublicKeyAddOn(); setPublicKeyAddOnClassName('key-invalid'); } }); } /** * Send a test call to the Stripe API to check if the inputted secret key is valid */ const testSecretKey = (key: string) => { if (!key.match(/^sk_/)) { setSecretKeyAddOn(); setSecretKeyAddOnClassName('key-invalid'); return; } StripeAPI.listAllCharges(key).then(() => { if (!mounted.current) return; setSecretKey(key); setSecretKeyAddOn(); setSecretKeyAddOnClassName('key-valid'); }, reason => { if (!mounted.current) return; if (reason.response.status === 401) { setSecretKeyAddOn(); setSecretKeyAddOnClassName('key-invalid'); } }); } return (
} value={publicKey} onChange={testPublicKey} addOn={publicKeyAddOn} addOnClassName={publicKeyAddOnClassName} debounce={200} required />
} value={secretKey} onChange={testSecretKey} addOn={secretKeyAddOn} addOnClassName={secretKeyAddOnClassName} debounce={200} required/>
); } export const StripeKeysForm: React.FC = ({ onValidKeys }) => { return ( ); }