mirror of
https://github.com/woocommerce/woocommerce-paypal-payments.git
synced 2025-09-05 08:59:14 +08:00
52 lines
No EOL
1.3 KiB
JavaScript
52 lines
No EOL
1.3 KiB
JavaScript
const storageKey = 'ppcp-data-client-id';
|
|
|
|
const validateToken = (token, user) => {
|
|
if (! token) {
|
|
return false;
|
|
}
|
|
if (token.user !== user) {
|
|
return false;
|
|
}
|
|
const currentTime = new Date().getTime();
|
|
const isExpired = currentTime >= token.expiration * 1000;
|
|
return ! isExpired;
|
|
}
|
|
|
|
const storedTokenForUser = (user) => {
|
|
const token = JSON.parse(sessionStorage.getItem(storageKey));
|
|
if (validateToken(token, user)) {
|
|
return token.token;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
const storeToken = (token) => {
|
|
sessionStorage.setItem(storageKey, JSON.stringify(token));
|
|
}
|
|
|
|
const dataClientIdAttributeHandler = (script, config) => {
|
|
const token = storedTokenForUser(config.user);
|
|
if (token) {
|
|
script.setAttribute('data-client-token', token);
|
|
document.body.append(script);
|
|
return;
|
|
}
|
|
fetch(config.endpoint, {
|
|
method: 'POST',
|
|
body: JSON.stringify({
|
|
nonce: config.nonce
|
|
})
|
|
}).then((res)=>{
|
|
return res.json();
|
|
}).then((data)=>{
|
|
const isValid = validateToken(data, config.user);
|
|
if (!isValid) {
|
|
return;
|
|
}
|
|
storeToken(data);
|
|
script.setAttribute('data-client-token', data.token);
|
|
document.body.append(script);
|
|
});
|
|
}
|
|
|
|
export default dataClientIdAttributeHandler; |