Merge pull request #2769 from woocommerce/PCP-3821-link-manual-connect-button-to-server-side-endpoint

Link Manual Connect button to server side endpoint (3821)
This commit is contained in:
Emili Castells 2024-11-11 14:56:19 +01:00 committed by GitHub
commit 87ca59cf34
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
18 changed files with 536 additions and 231 deletions

View file

@ -0,0 +1,45 @@
import { Icon } from '@wordpress/components';
import { chevronDown, chevronUp } from '@wordpress/icons';
import { useState } from 'react';
const Accordion = ( {
title,
initiallyOpen = false,
className = '',
children,
} ) => {
const [ isOpen, setIsOpen ] = useState( initiallyOpen );
const toggleOpen = ( ev ) => {
setIsOpen( ! isOpen );
ev?.preventDefault();
return false;
};
const wrapperClasses = [ 'ppcp-r-accordion' ];
if ( className ) {
wrapperClasses.push( className );
}
if ( isOpen ) {
wrapperClasses.push( 'ppcp--is-open' );
}
return (
<div className={ wrapperClasses.join( ' ' ) }>
<button
onClick={ toggleOpen }
className="ppcp-r-accordion--title"
type="button"
>
<span>{ title }</span>
<Icon icon={ isOpen ? chevronUp : chevronDown } />
</button>
{ isOpen && (
<div className="ppcp-r-accordion--content">{ children }</div>
) }
</div>
);
};
export default Accordion;

View file

@ -12,47 +12,53 @@ import { debounce } from '../../../../../ppcp-blocks/resources/js/Helper/debounc
* @param {Function} props.onChange Change handler
* @param {number} [props.delay=300] Debounce delay in milliseconds
*/
const DataStoreControl = ( {
control: ControlComponent,
value: externalValue,
onChange,
delay = 300,
...props
} ) => {
const [ internalValue, setInternalValue ] = useState( externalValue );
const onChangeRef = useRef( onChange );
onChangeRef.current = onChange;
const debouncedUpdate = useRef(
debounce( ( value ) => {
onChangeRef.current( value );
}, delay )
).current;
useEffect( () => {
setInternalValue( externalValue );
debouncedUpdate?.cancel();
}, [ externalValue ] );
useEffect( () => {
return () => debouncedUpdate?.cancel();
}, [ debouncedUpdate ] );
const handleChange = useCallback(
( newValue ) => {
setInternalValue( newValue );
debouncedUpdate( newValue );
const DataStoreControl = React.forwardRef(
(
{
control: ControlComponent,
value: externalValue,
onChange,
delay = 300,
...props
},
[ debouncedUpdate ]
);
ref
) => {
const [ internalValue, setInternalValue ] = useState( externalValue );
const onChangeRef = useRef( onChange );
onChangeRef.current = onChange;
return (
<ControlComponent
{ ...props }
value={ internalValue }
onChange={ handleChange }
/>
);
};
const debouncedUpdate = useRef(
debounce( ( value ) => {
onChangeRef.current( value );
}, delay )
).current;
useEffect( () => {
setInternalValue( externalValue );
debouncedUpdate?.cancel();
}, [ externalValue ] );
useEffect( () => {
return () => debouncedUpdate?.cancel();
}, [ debouncedUpdate ] );
const handleChange = useCallback(
( newValue ) => {
setInternalValue( newValue );
debouncedUpdate( newValue );
},
[ debouncedUpdate ]
);
return (
<ControlComponent
ref={ ref }
{ ...props }
value={ internalValue }
onChange={ handleChange }
/>
);
}
);
export default DataStoreControl;

View file

@ -1,14 +1,42 @@
import { ToggleControl } from '@wordpress/components';
import { useRef } from '@wordpress/element';
import SpinnerOverlay from './SpinnerOverlay';
const SettingsToggleBlock = ( {
isToggled,
setToggled,
isLoading = false,
...props
} ) => {
const toggleRef = useRef( null );
const blockClasses = [ 'ppcp-r-toggle-block' ];
if ( isLoading ) {
blockClasses.push( 'ppcp--is-loading' );
}
const handleLabelClick = () => {
if ( ! toggleRef.current || isLoading ) {
return;
}
toggleRef.current.click();
toggleRef.current.focus();
};
const SettingsToggleBlock = ( { isToggled, setToggled, ...props } ) => {
return (
<div className="ppcp-r-toggle-block">
<div className={ blockClasses.join( ' ' ) }>
<div className="ppcp-r-toggle-block__wrapper">
<div className="ppcp-r-toggle-block__content">
{ props?.label && (
<span className="ppcp-r-toggle-block__content-label">
// eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions -- keyboard element is ToggleControl
<div
className="ppcp-r-toggle-block__content-label"
onClick={ handleLabelClick }
>
{ props.label }
</span>
</div>
) }
{ props?.description && (
<p
@ -21,15 +49,16 @@ const SettingsToggleBlock = ( { isToggled, setToggled, ...props } ) => {
</div>
<div className="ppcp-r-toggle-block__switch">
<ToggleControl
ref={ toggleRef }
checked={ isToggled }
onChange={ ( newValue ) => {
setToggled( newValue );
} }
onChange={ ( newState ) => setToggled( newState ) }
disabled={ isLoading }
/>
</div>
</div>
{ props.children && isToggled && (
<div className="ppcp-r-toggle-block__toggled-content">
{ isLoading && <SpinnerOverlay /> }
{ props.children }
</div>
) }

View file

@ -0,0 +1,11 @@
import { Spinner } from '@wordpress/components';
const SpinnerOverlay = () => {
return (
<div className="ppcp-r-spinner-overlay">
<Spinner />
</div>
);
};
export default SpinnerOverlay;

View file

@ -0,0 +1,180 @@
import { __, sprintf } from '@wordpress/i18n';
import { Button, TextControl } from '@wordpress/components';
import { useRef } from '@wordpress/element';
import { useDispatch } from '@wordpress/data';
import { store as noticesStore } from '@wordpress/notices';
import SettingsToggleBlock from '../../../ReusableComponents/SettingsToggleBlock';
import Separator from '../../../ReusableComponents/Separator';
import DataStoreControl from '../../../ReusableComponents/DataStoreControl';
import { useManualConnect, useOnboardingStepWelcome } from '../../../../data';
const AdvancedOptionsForm = ( { setCompleted } ) => {
const {
isManualConnectionBusy,
isSandboxMode,
setSandboxMode,
isManualConnectionMode,
setManualConnectionMode,
clientId,
setClientId,
clientSecret,
setClientSecret,
} = useOnboardingStepWelcome();
const { createSuccessNotice, createErrorNotice } =
useDispatch( noticesStore );
const { connectManual } = useManualConnect();
const refClientId = useRef( null );
const refClientSecret = useRef( null );
const handleFormValidation = () => {
const fields = [
{
ref: refClientId,
value: clientId,
errorMessage: __(
'Please enter your Client ID',
'woocommerce-paypal-payments'
),
},
{
ref: refClientSecret,
value: clientSecret,
errorMessage: __(
'Please enter your Secret Key',
'woocommerce-paypal-payments'
),
},
];
for ( const { ref, value, errorMessage } of fields ) {
if ( value ) {
continue;
}
ref?.current?.focus();
createErrorNotice( errorMessage );
return false;
}
return true;
};
const handleServerError = ( res ) => {
if ( res.message ) {
createErrorNotice( res.message );
} else {
createErrorNotice(
__(
'Could not connect to PayPal. Please make sure your Client ID and Secret Key are correct.',
'woocommerce-paypal-payments'
)
);
}
};
const handleServerSuccess = () => {
createSuccessNotice(
__( 'Connected to PayPal', 'woocommerce-paypal-payments' )
);
setCompleted( true );
};
const handleConnect = async () => {
if ( ! handleFormValidation() ) {
return;
}
const res = await connectManual();
if ( res.success ) {
handleServerSuccess();
} else {
handleServerError( res );
}
};
const advancedUsersDescription = sprintf(
// translators: %s: Link to PayPal REST application guide
__(
'For advanced users: Connect a custom PayPal REST app for full control over your integration. For more information on creating a PayPal REST application, <a target="_blank" href="%s">click here</a>.',
'woocommerce-paypal-payments'
),
'https://woocommerce.com/document/woocommerce-paypal-payments/#manual-credential-input'
);
return (
<>
<SettingsToggleBlock
label={ __(
'Enable Sandbox Mode',
'woocommerce-paypal-payments'
) }
description={ __(
'Activate Sandbox mode to safely test PayPal with sample data. Once your store is ready to go live, you can easily switch to your production account.',
'woocommerce-paypal-payments'
) }
isToggled={ !! isSandboxMode }
setToggled={ setSandboxMode }
>
<Button variant="secondary">
{ __( 'Connect Account', 'woocommerce-paypal-payments' ) }
</Button>
</SettingsToggleBlock>
<Separator className="ppcp-r-page-welcome-mode-separator" />
<SettingsToggleBlock
label={ __(
'Manually Connect',
'woocommerce-paypal-payments'
) }
description={ advancedUsersDescription }
isToggled={ !! isManualConnectionMode }
setToggled={ setManualConnectionMode }
isLoading={ isManualConnectionBusy }
>
<DataStoreControl
control={ TextControl }
ref={ refClientId }
label={
isSandboxMode
? __(
'Sandbox Client ID',
'woocommerce-paypal-payments'
)
: __(
'Live Client ID',
'woocommerce-paypal-payments'
)
}
value={ clientId }
onChange={ setClientId }
/>
<DataStoreControl
control={ TextControl }
ref={ refClientSecret }
label={
isSandboxMode
? __(
'Sandbox Secret Key',
'woocommerce-paypal-payments'
)
: __(
'Live Secret Key',
'woocommerce-paypal-payments'
)
}
value={ clientSecret }
onChange={ setClientSecret }
type="password"
/>
<Button variant="secondary" onClick={ handleConnect }>
{ __( 'Connect Account', 'woocommerce-paypal-payments' ) }
</Button>
</SettingsToggleBlock>
</>
);
};
export default AdvancedOptionsForm;

View file

@ -1,51 +1,63 @@
import OnboardingHeader from '../../ReusableComponents/OnboardingHeader';
import { __, sprintf } from '@wordpress/i18n';
import { Button, TextControl } from '@wordpress/components';
import PaymentMethodIcons from '../../ReusableComponents/PaymentMethodIcons';
import SettingsToggleBlock from '../../ReusableComponents/SettingsToggleBlock';
import Separator from '../../ReusableComponents/Separator';
import { useOnboardingStepWelcome, useManualConnect } from '../../../data';
import { Button } from '@wordpress/components';
import DataStoreControl from '../../ReusableComponents/DataStoreControl';
import BadgeBox, { BADGE_BOX_TITLE_BIG } from "../../ReusableComponents/BadgeBox";
import OnboardingHeader from '../../ReusableComponents/OnboardingHeader';
import PaymentMethodIcons from '../../ReusableComponents/PaymentMethodIcons';
import Separator from '../../ReusableComponents/Separator';
import BadgeBox, {
BADGE_BOX_TITLE_BIG,
} from '../../ReusableComponents/BadgeBox';
import AdvancedOptionsForm from './Components/AdvancedOptionsForm';
import AccordionSection from '../../ReusableComponents/AccordionSection';
const StepWelcome = ( { setStep, currentStep, setCompleted } ) => {
return (
<div className="ppcp-r-page-welcome">
<OnboardingHeader
title={__(
'Welcome to PayPal Payments',
'woocommerce-paypal-payments'
)}
description={__(
'Your all-in-one integration for PayPal checkout solutions that enable buyers<br/> to pay via PayPal, Pay Later, all major credit/debit cards, Apple Pay, Google Pay, and more.',
'woocommerce-paypal-payments'
)}
/>
<div className="ppcp-r-inner-container">
<WelcomeFeatures/>
<PaymentMethodIcons icons="all"/>
<p className="ppcp-r-button__description">{__(
`Click the button below to be guided through connecting your existing PayPal account or creating a new one.You will be able to choose the payment options that are right for your store.`,
'woocommerce-paypal-payments'
)}
</p>
<Button
className="ppcp-r-button-activate-paypal"
variant="primary"
onClick={() => setStep(currentStep + 1)}
>
{__(
'Activate PayPal Payments',
'woocommerce-paypal-payments'
)}
</Button>
</div>
<Separator className="ppcp-r-page-welcome-mode-separator"/>
<WelcomeDocs/>
<WelcomeForm setCompleted={setCompleted}/>
</div>
);
<div className="ppcp-r-page-welcome">
<OnboardingHeader
title={ __(
'Welcome to PayPal Payments',
'woocommerce-paypal-payments'
) }
description={ __(
'Your all-in-one integration for PayPal checkout solutions that enable buyers<br/> to pay via PayPal, Pay Later, all major credit/debit cards, Apple Pay, Google Pay, and more.',
'woocommerce-paypal-payments'
) }
/>
<div className="ppcp-r-inner-container">
<WelcomeFeatures />
<PaymentMethodIcons icons="all" />
<p className="ppcp-r-button__description">
{ __(
`Click the button below to be guided through connecting your existing PayPal account or creating a new one.You will be able to choose the payment options that are right for your store.`,
'woocommerce-paypal-payments'
) }
</p>
<Button
className="ppcp-r-button-activate-paypal"
variant="primary"
onClick={ () => setStep( currentStep + 1 ) }
>
{ __(
'Activate PayPal Payments',
'woocommerce-paypal-payments'
) }
</Button>
</div>
<Separator className="ppcp-r-page-welcome-mode-separator" />
<WelcomeDocs />
<Separator text={ __( 'or', 'woocommerce-paypal-payments' ) } />
<AccordionSection
title={ __(
'See advanced options',
'woocommerce-paypal-payments'
) }
className="onboarding-advanced-options"
initiallyOpen={ false }
>
<AdvancedOptionsForm setCompleted={ setCompleted } />
</AccordionSection>
</div>
);
};
const WelcomeFeatures = () => {
@ -73,20 +85,20 @@ const WelcomeFeatures = () => {
'woocommerce-paypal-payments'
) }
</span>
<p>{ __( 'Supported', 'woocommerce-paypal-payments' ) }</p>
</div>
</div>
);
<p>{ __( 'Supported', 'woocommerce-paypal-payments' ) }</p>
</div>
</div>
);
};
const WelcomeDocs = () => {
const pricesBasedDescription = sprintf(
// translators: %s: Link to PayPal REST application guide
__(
'<sup>1</sup>Prices based on domestic transactions as of October 25th, 2024. <a target="_blank" href="%s">Click here</a> for full pricing details.',
'woocommerce-paypal-payments'
),
'https://woocommerce.com/document/woocommerce-paypal-payments/#manual-credential-input '
)
const pricesBasedDescription = sprintf(
// translators: %s: Link to PayPal REST application guide
__(
'<sup>1</sup>Prices based on domestic transactions as of October 25th, 2024. <a target="_blank" href="%s">Click here</a> for full pricing details.',
'woocommerce-paypal-payments'
),
'https://woocommerce.com/document/woocommerce-paypal-payments/#manual-credential-input '
);
return (
<div className="ppcp-r-welcome-docs">
@ -228,116 +240,4 @@ const WelcomeDocs = () => {
);
};
const WelcomeForm = ( { setCompleted } ) => {
const {
isSandboxMode,
setSandboxMode,
isManualConnectionMode,
setManualConnectionMode,
clientId,
setClientId,
clientSecret,
setClientSecret,
} = useOnboardingStepWelcome();
const { connectManual } = useManualConnect();
const handleConnect = async () => {
try {
const res = await connectManual(
clientId,
clientSecret,
isSandboxMode
);
if ( ! res.success ) {
throw new Error( 'Request failed.' );
}
console.log(`Merchant ID: ${res.merchantId}, email: ${res.email}`);
setCompleted( true );
} catch ( exc ) {
console.error( exc );
alert( 'Connection failed.' );
}
};
const advancedUsersDescription = sprintf(
// translators: %s: Link to PayPal REST application guide
__(
'For advanced users: Connect a custom PayPal REST app for full control over your integration. For more information on creating a PayPal REST application, <a target="_blank" href="%s">click here</a>.',
'woocommerce-paypal-payments'
),
'https://woocommerce.com/document/woocommerce-paypal-payments/#manual-credential-input '
);
return (
<>
<SettingsToggleBlock
label={ __(
'Enable Sandbox Mode',
'woocommerce-paypal-payments'
) }
description={ __(
'Activate Sandbox mode to safely test PayPal with sample data. Once your store is ready to go live, you can easily switch to your production account.',
'woocommerce-paypal-payments'
) }
isToggled={ !! isSandboxMode }
setToggled={ setSandboxMode }
>
<Button variant="secondary">
{ __( 'Connect Account', 'woocommerce-paypal-payments' ) }
</Button>
</SettingsToggleBlock>
<Separator className="ppcp-r-page-welcome-mode-separator" />
<SettingsToggleBlock
label={ __(
'Manually Connect',
'woocommerce-paypal-payments'
) }
description={ advancedUsersDescription }
isToggled={ !! isManualConnectionMode }
setToggled={ setManualConnectionMode }
>
<DataStoreControl
control={ TextControl }
label={
isSandboxMode
? __(
'Sandbox Client ID',
'woocommerce-paypal-payments'
)
: __(
'Live Client ID',
'woocommerce-paypal-payments'
)
}
value={ clientId }
onChange={ setClientId }
/>
<DataStoreControl
control={ TextControl }
label={
isSandboxMode
? __(
'Sandbox Secret Key',
'woocommerce-paypal-payments'
)
: __(
'Live Secret Key',
'woocommerce-paypal-payments'
)
}
value={ clientSecret }
onChange={ setClientSecret }
type="password"
/>
<Button variant="secondary" onClick={ handleConnect }>
{ __( 'Connect Account', 'woocommerce-paypal-payments' ) }
</Button>
</SettingsToggleBlock>
</>
);
};
export default StepWelcome;

View file

@ -4,6 +4,7 @@ export default {
// Transient data.
SET_ONBOARDING_IS_READY: 'SET_ONBOARDING_IS_READY',
SET_IS_SAVING_ONBOARDING: 'SET_IS_SAVING_ONBOARDING',
SET_MANUAL_CONNECTION_BUSY: 'SET_MANUAL_CONNECTION_BUSY',
// Persistent data.
SET_ONBOARDING_COMPLETED: 'SET_ONBOARDING_COMPLETED',

View file

@ -38,6 +38,19 @@ export const setIsSaving = ( isSaving ) => {
};
};
/**
* Non-persistent. Changes the "manual connection is busy" flag.
*
* @param {boolean} isBusy
* @return {{type: string, isBusy}} The action.
*/
export const setManualConnectionIsBusy = ( isBusy ) => {
return {
type: ACTION_TYPES.SET_MANUAL_CONNECTION_BUSY,
isBusy,
};
};
/**
* Persistent. Set the full onboarding details, usually during app initialization.
*
@ -155,10 +168,47 @@ export const setProducts = ( products ) => {
};
};
/**
* Attempts to establish a connection using client ID and secret via the server-side
* connection endpoint.
*
* @return {Object} The server response object
*/
export function* connectViaIdAndSecret() {
let result = null;
try {
const path = `${ NAMESPACE }/connect_manual`;
const { clientId, clientSecret, useSandbox } =
yield select( STORE_NAME ).getPersistentData();
yield setManualConnectionIsBusy( true );
result = yield apiFetch( {
path,
method: 'POST',
data: {
clientId,
clientSecret,
useSandbox,
},
} );
} catch ( e ) {
result = {
success: false,
error: e,
};
} finally {
yield setManualConnectionIsBusy( false );
}
return result;
}
/**
* Saves the persistent details to the WP database.
*
* @return {any} A generator function that handles the saving process.
* @return {boolean} True, if the values were successfully saved.
*/
export function* persist() {
let error = null;

View file

@ -25,6 +25,10 @@ const useOnboardingDetails = () => {
return select( STORE_NAME ).getTransientData().isReady;
} );
const isManualConnectionBusy = useSelect( ( select ) => {
return select( STORE_NAME ).getTransientData().isManualConnectionBusy;
}, [] );
// Read-only flags.
const flags = useSelect( ( select ) => {
return select( STORE_NAME ).getFlags();
@ -78,6 +82,7 @@ const useOnboardingDetails = () => {
return {
isSaving,
isReady,
isManualConnectionBusy,
step,
setStep: ( value ) => setDetailAndPersist( setOnboardingStep, value ),
completed,
@ -105,6 +110,7 @@ const useOnboardingDetails = () => {
export const useOnboardingStepWelcome = () => {
const {
isSaving,
isManualConnectionBusy,
isSandboxMode,
setSandboxMode,
isManualConnectionMode,
@ -117,6 +123,7 @@ export const useOnboardingStepWelcome = () => {
return {
isSaving,
isManualConnectionBusy,
isSandboxMode,
setSandboxMode,
isManualConnectionMode,
@ -148,19 +155,9 @@ export const useOnboardingStep = () => {
};
export const useManualConnect = () => {
const connectManual = async ( clientId, clientSecret, isSandboxMode ) => {
return await apiFetch( {
path: `${ NAMESPACE }/connect_manual`,
method: 'POST',
data: {
clientId,
clientSecret,
useSandbox: isSandboxMode,
},
} );
};
const { connectViaIdAndSecret } = useDispatch( STORE_NAME );
return {
connectManual,
connectManual: connectViaIdAndSecret,
};
};

View file

@ -3,6 +3,7 @@ import ACTION_TYPES from './action-types';
const defaultState = {
isReady: false,
isSaving: false,
isManualConnectionBusy: false,
// Data persisted to the server.
data: {
@ -59,6 +60,9 @@ export const onboardingReducer = (
case ACTION_TYPES.SET_IS_SAVING_ONBOARDING:
return setTransient( { isSaving: action.isSaving } );
case ACTION_TYPES.SET_MANUAL_CONNECTION_BUSY:
return setTransient( { isManualConnectionBusy: action.isBusy } );
// Persistent data.
case ACTION_TYPES.SET_ONBOARDING_DETAILS:
const newState = setPersistent( action.payload.data );