-
Notifications
You must be signed in to change notification settings - Fork 152
/
oauth.tsx
89 lines (80 loc) · 2.61 KB
/
oauth.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import React, { useCallback, useState } from 'react';
import {
usePlaidLink,
PlaidLinkOnSuccess,
PlaidLinkOnEvent,
PlaidLinkOnExit,
PlaidLinkOptions,
} from 'react-plaid-link';
const PlaidLinkWithOAuth = () => {
const [token, setToken] = useState<string | null>(null);
const isOAuthRedirect = window.location.href.includes('?oauth_state_id=');
// generate a link_token when component mounts
React.useEffect(() => {
// do not generate a new token if page is handling an OAuth redirect.
// instead setLinkToken to previously generated token from localStorage
// https://plaid.com/docs/link/oauth/#reinitializing-link
if (isOAuthRedirect) {
setToken(localStorage.getItem('link_token'));
return;
}
const createLinkToken = async () => {
const response = await fetch('/api/create_link_token', {
method: 'POST',
});
const { link_token } = await response.json();
setToken(link_token);
// store link_token temporarily in case of OAuth redirect
localStorage.setItem('link_token', link_token);
}
createLinkToken();
}, []);
const onSuccess = useCallback<PlaidLinkOnSuccess>((publicToken, metadata) => {
// send public_token to your server
// https://plaid.com/docs/api/tokens/#token-exchange-flow
console.log(publicToken, metadata);
}, []);
const onEvent = useCallback<PlaidLinkOnEvent>((eventName, metadata) => {
// log onEvent callbacks from Link
// https://plaid.com/docs/link/web/#onevent
console.log(eventName, metadata);
}, []);
const onExit = useCallback<PlaidLinkOnExit>((error, metadata) => {
// log onExit callbacks from Link, handle errors
// https://plaid.com/docs/link/web/#onexit
console.log(error, metadata);
}, []);
const config: PlaidLinkOptions = {
// token must be the same token used for the first initialization of Link
token,
onSuccess,
onEvent,
onExit,
};
if (isOAuthRedirect) {
// receivedRedirectUri must include the query params
config.receivedRedirectUri = window.location.href;
}
const {
open,
ready,
// error,
// exit
} = usePlaidLink(config);
React.useEffect(() => {
// If OAuth redirect, instantly open link when it is ready instead of
// making user click the button
if (isOAuthRedirect && ready) {
open();
}
}, [ready, open, isOAuthRedirect]);
// No need to render a button on OAuth redirect as link opens instantly
return isOAuthRedirect ? (
<></>
) : (
<button onClick={() => open()} disabled={!ready}>
Connect a bank account
</button>
);
};
export default PlaidLinkWithOAuth;