Add GooglePlay preview in admin settings.

This commit is contained in:
Pedro Silva 2023-09-21 11:58:51 +01:00
parent 5ca0e16b5b
commit 08d8cded5b
No known key found for this signature in database
GPG key ID: E2EE20C0669D24B3
10 changed files with 208 additions and 13 deletions

View file

@ -27,6 +27,7 @@ class WidgetBuilder {
setPaypal(paypal) { setPaypal(paypal) {
this.paypal = paypal; this.paypal = paypal;
jQuery(document).trigger('ppcp-paypal-loaded', paypal);
} }
registerButtons(wrapper, options) { registerButtons(wrapper, options) {
@ -174,4 +175,5 @@ class WidgetBuilder {
} }
} }
export default new WidgetBuilder(); window.widgetBuilder = window.widgetBuilder || new WidgetBuilder();
export default window.widgetBuilder;

View file

@ -4,6 +4,7 @@ import CheckoutHandler from "./CheckoutHandler";
import CartBlockHandler from "./CartBlockHandler"; import CartBlockHandler from "./CartBlockHandler";
import CheckoutBlockHandler from "./CheckoutBlockHandler"; import CheckoutBlockHandler from "./CheckoutBlockHandler";
import MiniCartHandler from "./MiniCartHandler"; import MiniCartHandler from "./MiniCartHandler";
import PreviewHandler from "./PreviewHandler";
class ContextHandlerFactory { class ContextHandlerFactory {
@ -22,6 +23,8 @@ class ContextHandlerFactory {
return new CartBlockHandler(buttonConfig, ppcpConfig, externalActionHandler); return new CartBlockHandler(buttonConfig, ppcpConfig, externalActionHandler);
case 'checkout-block': case 'checkout-block':
return new CheckoutBlockHandler(buttonConfig, ppcpConfig, externalActionHandler); return new CheckoutBlockHandler(buttonConfig, ppcpConfig, externalActionHandler);
case 'preview':
return new PreviewHandler(buttonConfig, ppcpConfig, externalActionHandler);
} }
} }
} }

View file

@ -0,0 +1,31 @@
import BaseHandler from "./BaseHandler";
class CartHandler extends BaseHandler {
constructor(buttonConfig, ppcpConfig, externalHandler) {
super(buttonConfig, ppcpConfig, externalHandler);
}
transactionInfo() {
throw new Error('Transaction info fail. This is just a preview.');
}
createOrder() {
throw new Error('Create order fail. This is just a preview.');
}
approveOrder(data, actions) {
throw new Error('Approve order fail. This is just a preview.');
}
actionHandler() {
throw new Error('Action handler fail. This is just a preview.');
}
errorHandler() {
throw new Error('Error handler fail. This is just a preview.');
}
}
export default CartHandler;

View file

@ -1,6 +1,7 @@
import ContextHandlerFactory from "./Context/ContextHandlerFactory"; import ContextHandlerFactory from "./Context/ContextHandlerFactory";
import {setVisible} from '../../../ppcp-button/resources/js/modules/Helper/Hiding'; import {setVisible} from '../../../ppcp-button/resources/js/modules/Helper/Hiding';
import {setEnabled} from '../../../ppcp-button/resources/js/modules/Helper/ButtonDisabler'; import {setEnabled} from '../../../ppcp-button/resources/js/modules/Helper/ButtonDisabler';
import widgetBuilder from "../../../ppcp-button/resources/js/modules/Renderer/WidgetBuilder";
class GooglepayButton { class GooglepayButton {
@ -152,6 +153,7 @@ class GooglepayButton {
buttonLocale: buttonStyle.language || 'en', buttonLocale: buttonStyle.language || 'en',
buttonSizeMode: 'fill', buttonSizeMode: 'fill',
}); });
jQuery(wrapper).append(button); jQuery(wrapper).append(button);
} }
@ -207,7 +209,7 @@ class GooglepayButton {
console.log('[GooglePayButton] processPayment: createOrder', id, this.context); console.log('[GooglePayButton] processPayment: createOrder', id, this.context);
const confirmOrderResponse = await paypal.Googlepay().confirmOrder({ const confirmOrderResponse = await widgetBuilder.paypal.Googlepay().confirmOrder({
orderId: id, orderId: id,
paymentMethodData: paymentData.paymentMethodData paymentMethodData: paymentData.paymentMethodData
}); });

View file

@ -0,0 +1,98 @@
import {loadCustomScript} from "@paypal/paypal-js";
import GooglepayButton from "./GooglepayButton";
import widgetBuilder from "../../../ppcp-button/resources/js/modules/Renderer/WidgetBuilder";
(function ({
buttonConfig,
jQuery
}) {
let googlePayConfig;
let buttonQueue = [];
let bootstrapped = false;
jQuery(document).on('ppcp_paypal_render_preview', (ev, ppcpConfig) => {
if (bootstrapped) {
createButton(ppcpConfig);
} else {
buttonQueue.push({
ppcpConfig: JSON.parse(JSON.stringify(ppcpConfig))
});
}
});
const createButton = function (ppcpConfig) {
const selector = ppcpConfig.button.wrapper + 'GooglePay';
buttonConfig = JSON.parse(JSON.stringify(buttonConfig));
buttonConfig.button.wrapper = selector;
const wrapperElement = `<div id="${selector.replace('#', '')}" class="ppcp-button-googlepay"></div>`;
if (!jQuery(selector).length) {
jQuery(ppcpConfig.button.wrapper).after(wrapperElement);
} else {
jQuery(selector).replaceWith(wrapperElement);
}
const button = new GooglepayButton(
'preview',
null,
buttonConfig,
ppcpConfig,
);
button.init(googlePayConfig);
}
const bootstrap = async function () {
googlePayConfig = await widgetBuilder.paypal.Googlepay().config();
let options;
while (options = buttonQueue.pop()) {
createButton(options.ppcpConfig);
}
};
document.addEventListener(
'DOMContentLoaded',
() => {
if (typeof (buttonConfig) === 'undefined') {
console.error('PayPal button could not be configured.');
return;
}
let paypalLoaded = false;
let googlePayLoaded = false;
const tryToBoot = () => {
if (!bootstrapped && paypalLoaded && googlePayLoaded) {
bootstrapped = true;
bootstrap();
}
}
// Load GooglePay SDK
loadCustomScript({ url: buttonConfig.sdk_url }).then(() => {
googlePayLoaded = true;
tryToBoot();
});
// Wait for PayPal to be loaded externally
if (typeof widgetBuilder.paypal !== 'undefined') {
paypalLoaded = true;
tryToBoot();
}
jQuery(document).on('ppcp-paypal-loaded', () => {
paypalLoaded = true;
tryToBoot();
});
},
);
})({
buttonConfig: window.wc_ppcp_googlepay_admin,
jQuery: window.jQuery
});

View file

@ -358,6 +358,34 @@ class Button implements ButtonInterface {
); );
} }
/**
* Enqueues scripts/styles for admin.
*/
public function enqueue_admin(): void {
wp_register_style(
'wc-ppcp-googlepay-admin',
untrailingslashit( $this->module_url ) . '/assets/css/styles.css',
array(),
$this->version
);
wp_enqueue_style( 'wc-ppcp-googlepay-admin' );
wp_register_script(
'wc-ppcp-googlepay-admin',
untrailingslashit( $this->module_url ) . '/assets/js/boot-admin.js',
array(),
$this->version,
true
);
wp_enqueue_script( 'wc-ppcp-googlepay-admin' );
wp_localize_script(
'wc-ppcp-googlepay-admin',
'wc_ppcp_googlepay_admin',
$this->script_data()
);
}
/** /**
* The configuration for the smart buttons. * The configuration for the smart buttons.
* *

View file

@ -66,6 +66,21 @@ class GooglepayModule implements ModuleInterface {
} }
); );
add_action(
'admin_enqueue_scripts',
static function () use ( $c, $button ) {
if ( ! is_admin() ) {
return;
}
/**
* Should add this to the ButtonInterface.
*
* @psalm-suppress UndefinedInterfaceMethod
*/
$button->enqueue_admin();
}
);
add_action( add_action(
'woocommerce_blocks_payment_method_type_registration', 'woocommerce_blocks_payment_method_type_registration',
function( PaymentMethodRegistry $payment_method_registry ) use ( $c, $button ): void { function( PaymentMethodRegistry $payment_method_registry ) use ( $c, $button ): void {
@ -75,6 +90,16 @@ class GooglepayModule implements ModuleInterface {
} }
); );
add_action(
'woocommerce_paypal_payments_admin_gateway_settings',
function( array $settings ) use ( $c, $button ): array {
if ( is_array( $settings['components'] ) ) {
$settings['components'][] = 'googlepay';
}
return $settings;
}
);
// Clear product status handling. // Clear product status handling.
add_action( add_action(
'woocommerce_paypal_payments_clear_apm_product_status', 'woocommerce_paypal_payments_clear_apm_product_status',

View file

@ -11,6 +11,7 @@ module.exports = {
entry: { entry: {
'boot': path.resolve('./resources/js/boot.js'), 'boot': path.resolve('./resources/js/boot.js'),
'boot-block': path.resolve('./resources/js/boot-block.js'), 'boot-block': path.resolve('./resources/js/boot-block.js'),
'boot-admin': path.resolve('./resources/js/boot-admin.js'),
"styles": path.resolve('./resources/css/styles.scss') "styles": path.resolve('./resources/css/styles.scss')
}, },
output: { output: {

View file

@ -88,6 +88,7 @@ document.addEventListener(
try { try {
renderer.render({}); renderer.render({});
jQuery(document).trigger('ppcp_paypal_render_preview', settings);
} catch (err) { } catch (err) {
console.error(err); console.error(err);
} }
@ -114,7 +115,7 @@ document.addEventListener(
'client-id': PayPalCommerceGatewaySettings.client_id, 'client-id': PayPalCommerceGatewaySettings.client_id,
'currency': PayPalCommerceGatewaySettings.currency, 'currency': PayPalCommerceGatewaySettings.currency,
'integration-date': PayPalCommerceGatewaySettings.integration_date, 'integration-date': PayPalCommerceGatewaySettings.integration_date,
'components': ['buttons', 'funding-eligibility', 'messages'], 'components': PayPalCommerceGatewaySettings.components,
'enable-funding': ['venmo', 'paylater'], 'enable-funding': ['venmo', 'paylater'],
}; };

View file

@ -211,16 +211,20 @@ class SettingsPageAssets {
wp_localize_script( wp_localize_script(
'ppcp-gateway-settings', 'ppcp-gateway-settings',
'PayPalCommerceGatewaySettings', 'PayPalCommerceGatewaySettings',
array( apply_filters(
'is_subscriptions_plugin_active' => $this->subscription_helper->plugin_is_active(), 'woocommerce_paypal_payments_admin_gateway_settings',
'client_id' => $this->client_id, array(
'currency' => $this->currency, 'is_subscriptions_plugin_active' => $this->subscription_helper->plugin_is_active(),
'country' => $this->country, 'client_id' => $this->client_id,
'environment' => $this->environment->current_environment(), 'currency' => $this->currency,
'integration_date' => PAYPAL_INTEGRATION_DATE, 'country' => $this->country,
'is_pay_later_button_enabled' => $this->is_pay_later_button_enabled, 'environment' => $this->environment->current_environment(),
'disabled_sources' => $this->disabled_sources, 'integration_date' => PAYPAL_INTEGRATION_DATE,
'all_funding_sources' => $this->all_funding_sources, 'is_pay_later_button_enabled' => $this->is_pay_later_button_enabled,
'disabled_sources' => $this->disabled_sources,
'all_funding_sources' => $this->all_funding_sources,
'components' => array( 'buttons', 'funding-eligibility', 'messages' ),
)
) )
); );
} }