Merge branch 'trunk' into PCP-461-error-when-adding-changing-subscription-payment-method-to-pay-pal-dcc-while-no-vault-token-exists

This commit is contained in:
Emili Castells Guasch 2024-01-08 09:27:51 +01:00
commit 09d6ccc92d
31 changed files with 3064 additions and 65 deletions

View file

@ -0,0 +1,55 @@
import MessagesBootstrap from "../../../../ppcp-button/resources/js/modules/ContextBootstrap/MessagesBootstap";
import {debounce} from "../Helper/debounce";
class BlockCheckoutMessagesBootstrap {
constructor(scriptData) {
this.messagesBootstrap = new MessagesBootstrap(scriptData, null);
this.lastCartTotal = null;
}
init() {
this.messagesBootstrap.init();
this._updateCartTotal();
if (wp.data?.subscribe) {
wp.data.subscribe(debounce(() => {
this._updateCartTotal();
}, 300));
}
}
/**
* @private
*/
_getCartTotal() {
if (!wp.data.select) {
return null;
}
const cart = wp.data.select('wc/store/cart')
if (!cart) {
return null;
}
const totals = cart.getCartTotals();
return parseInt(totals.total_price, 10) / 10 ** totals.currency_minor_unit;
}
/**
* @private
*/
_updateCartTotal() {
const currentTotal = this._getCartTotal();
if (currentTotal === null) {
return;
}
if (currentTotal !== this.lastCartTotal) {
this.lastCartTotal = currentTotal;
jQuery(document.body).trigger('ppcp_block_cart_total_updated', [currentTotal]);
}
}
}
export default BlockCheckoutMessagesBootstrap;

View file

@ -0,0 +1,9 @@
export const debounce = (callback, delayMs) => {
let timeoutId = null;
return (...args) => {
window.clearTimeout(timeoutId);
timeoutId = window.setTimeout(() => {
callback.apply(null, args);
}, delayMs);
};
};

View file

@ -8,6 +8,7 @@ import {
normalizeStyleForFundingSource
} from '../../../ppcp-button/resources/js/modules/Helper/Style'
import buttonModuleWatcher from "../../../ppcp-button/resources/js/modules/ButtonModuleWatcher";
import BlockCheckoutMessagesBootstrap from "./Bootstrap/BlockCheckoutMessagesBootstrap";
const config = wc.wcSettings.getSetting('ppcp-gateway_data');
@ -15,6 +16,8 @@ window.ppcpFundingSource = config.fundingSource;
let registeredContext = false;
let paypalScriptPromise = null;
const PayPalComponent = ({
onClick,
onClose,
@ -33,6 +36,16 @@ const PayPalComponent = ({
const [paypalOrder, setPaypalOrder] = useState(null);
const [gotoContinuationOnError, setGotoContinuationOnError] = useState(false);
const [paypalScriptLoaded, setPaypalScriptLoaded] = useState(false);
if (!paypalScriptLoaded) {
if (!paypalScriptPromise) {
// for editor, since canMakePayment was not called
paypalScriptPromise = loadPaypalScriptPromise(config.scriptData)
}
paypalScriptPromise.then(() => setPaypalScriptLoaded(true));
}
const methodId = fundingSource ? `${config.id}-${fundingSource}` : config.id;
useEffect(() => {
@ -309,7 +322,11 @@ const PayPalComponent = ({
const style = normalizeStyleForFundingSource(config.scriptData.button.style, fundingSource);
const PayPalButton = window.paypal.Buttons.driver("react", { React, ReactDOM });
if (!paypalScriptLoaded) {
return null;
}
const PayPalButton = paypal.Buttons.driver("react", { React, ReactDOM });
return (
<PayPalButton
@ -363,8 +380,6 @@ if (config.scriptData.continuation) {
},
});
} else if (!config.usePlaceOrder) {
const paypalScriptPromise = loadPaypalScriptPromise(config.scriptData);
for (const fundingSource of ['paypal', ...config.enabledFundingSources]) {
registerExpressPaymentMethod({
name: `${config.id}-${fundingSource}`,
@ -374,6 +389,13 @@ if (config.scriptData.continuation) {
edit: <PayPalComponent isEditing={true} fundingSource={fundingSource}/>,
ariaLabel: config.title,
canMakePayment: async () => {
if (!paypalScriptPromise) {
paypalScriptPromise = loadPaypalScriptPromise(config.scriptData);
paypalScriptPromise.then(() => {
const messagesBootstrap = new BlockCheckoutMessagesBootstrap(config.scriptData);
messagesBootstrap.init();
});
}
await paypalScriptPromise;
return paypal.Buttons({fundingSource}).isEligible();

View file

@ -224,19 +224,22 @@ class PayPalPaymentMethod extends AbstractPaymentMethodType {
}
}
$disabled_funding_sources = explode( ',', $script_data['url_params']['disable-funding'] ?? '' ) ?: array();
$funding_sources = array_values(
array_diff(
array_keys( $this->all_funding_sources ),
$disabled_funding_sources
)
);
$funding_sources = array();
if ( ! $this->is_editing() ) {
$disabled_funding_sources = explode( ',', $script_data['url_params']['disable-funding'] ?? '' ) ?: array();
$funding_sources = array_values(
array_diff(
array_keys( $this->all_funding_sources ),
$disabled_funding_sources
)
);
}
return array(
'id' => $this->gateway->id,
'title' => $this->gateway->title,
'description' => $this->gateway->description,
'enabled' => $this->settings_status->is_smart_button_enabled_for_location( $script_data['context'] ),
'enabled' => $this->settings_status->is_smart_button_enabled_for_location( $script_data['context'] ?? 'checkout' ),
'fundingSource' => $this->session_handler->funding_source(),
'finalReviewEnabled' => $this->final_review_enabled,
'addPlaceOrderMethod' => $this->add_place_order_method,
@ -253,4 +256,15 @@ class PayPalPaymentMethod extends AbstractPaymentMethodType {
'scriptData' => $script_data,
);
}
/**
* Checks if it is the block editing mode.
*/
private function is_editing(): bool {
if ( ! function_exists( 'get_current_screen' ) ) {
return false;
}
$screen = get_current_screen();
return $screen && $screen->is_block_editor();
}
}

View file

@ -1,13 +1,20 @@
import {setVisible} from "../Helper/Hiding";
import MessageRenderer from "../Renderer/MessageRenderer";
class MessagesBootstrap {
constructor(gateway, messageRenderer) {
this.gateway = gateway;
this.renderer = messageRenderer;
this.renderers = [];
this.lastAmount = this.gateway.messages.amount;
if (messageRenderer) {
this.renderers.push(messageRenderer);
}
}
init() {
if (this.gateway.messages?.block?.enabled) {
this.discoverBlocks();
}
jQuery(document.body).on('ppcp_cart_rendered ppcp_checkout_rendered', () => {
this.render();
});
@ -16,7 +23,7 @@ class MessagesBootstrap {
this.render();
});
jQuery(document.body).on('ppcp_cart_total_updated ppcp_checkout_total_updated ppcp_product_total_updated', (e, amount) => {
jQuery(document.body).on('ppcp_cart_total_updated ppcp_checkout_total_updated ppcp_product_total_updated ppcp_block_cart_total_updated', (e, amount) => {
if (this.lastAmount !== amount) {
this.lastAmount = amount;
@ -27,28 +34,40 @@ class MessagesBootstrap {
this.render();
}
shouldShow() {
discoverBlocks() {
Array.from(document.querySelectorAll('.ppcp-paylater-message-block')).forEach(blockElement => {
const config = {wrapper: '#' + blockElement.id};
if (!blockElement.getAttribute('data-pp-placement')) {
config.placement = this.gateway.messages.placement;
}
this.renderers.push(new MessageRenderer(config));
});
}
shouldShow(renderer) {
if (this.gateway.messages.is_hidden === true) {
return false;
}
const eventData = {result: true}
jQuery(document.body).trigger('ppcp_should_show_messages', [eventData]);
jQuery(document.body).trigger('ppcp_should_show_messages', [eventData, renderer.config.wrapper]);
return eventData.result;
}
shouldRender() {
return this.shouldShow() && this.renderer.shouldRender();
}
render() {
setVisible(this.gateway.messages.wrapper, this.shouldShow());
this.renderers.forEach(renderer => {
const shouldShow = this.shouldShow(renderer);
setVisible(renderer.config.wrapper, shouldShow);
if (!shouldShow) {
return;
}
if (!this.shouldRender()) {
return;
}
if (!renderer.shouldRender()) {
return;
}
this.renderer.renderWithAmount(this.lastAmount);
renderer.renderWithAmount(this.lastAmount);
});
}
}

View file

@ -56,10 +56,12 @@ export const loadPaypalScript = (config, onLoaded, onError = null) => {
// Build the PayPal script options.
let scriptOptions = keysToCamelCase(config.url_params);
scriptOptions = merge(scriptOptions, config.script_attributes);
if (config.script_attributes) {
scriptOptions = merge(scriptOptions, config.script_attributes);
}
// Load PayPal script for special case with data-client-token
if (config.data_client_id.set_attribute) {
if (config.data_client_id?.set_attribute) {
dataClientIdAttributeHandler(scriptOptions, config.data_client_id, callback, errorCallback);
return;
}

View file

@ -15,9 +15,13 @@ class MessageRenderer {
const options = {
amount,
placement: this.config.placement,
style: this.config.style
};
if (this.config.placement) {
options.placement = this.config.placement;
}
if (this.config.style) {
options.style = this.config.style;
}
// sometimes the element is destroyed while the options stay the same
if (document.querySelector(this.config.wrapper).getAttribute('data-render-number') !== this.currentNumber.toString()) {

View file

@ -32,6 +32,7 @@ use WooCommerce\PayPalCommerce\Button\Endpoint\ValidateCheckoutEndpoint;
use WooCommerce\PayPalCommerce\Button\Helper\ContextTrait;
use WooCommerce\PayPalCommerce\Button\Helper\MessagesApply;
use WooCommerce\PayPalCommerce\Onboarding\Environment;
use WooCommerce\PayPalCommerce\PayLaterBlock\PayLaterBlockModule;
use WooCommerce\PayPalCommerce\Session\SessionHandler;
use WooCommerce\PayPalCommerce\WcSubscriptions\FreeTrialHandlerTrait;
use WooCommerce\PayPalCommerce\WcSubscriptions\Helper\SubscriptionHelper;
@ -393,7 +394,7 @@ class SmartButton implements SmartButtonInterface {
* @return bool
*/
private function render_message_wrapper_registrar(): bool {
if ( ! $this->settings_status->is_pay_later_messaging_enabled() ) {
if ( ! $this->settings_status->is_pay_later_messaging_enabled() || ! $this->settings_status->has_pay_later_messaging_locations() ) {
return false;
}
@ -605,7 +606,7 @@ document.querySelector("#payment").before(document.querySelector("#ppcp-messages
case 'product':
return $smart_button_enabled_for_current_location || $smart_button_enabled_for_mini_cart;
default:
return $smart_button_enabled_for_mini_cart;
return $smart_button_enabled_for_mini_cart || $this->is_block_editor();
}
}
@ -618,6 +619,10 @@ document.querySelector("#payment").before(document.querySelector("#ppcp-messages
return false;
}
if ( ! $this->settings_status->is_pay_later_messaging_enabled() ) {
return false;
}
if ( ! $this->messages_apply->for_country() || $this->is_free_trial_cart() ) {
return false;
}
@ -626,6 +631,8 @@ document.querySelector("#payment").before(document.querySelector("#ppcp-messages
$messaging_enabled_for_current_location = $this->settings_status->is_pay_later_messaging_enabled_for_location( $location );
$has_paylater_block = has_block( 'woocommerce-paypal-payments/paylater-messages' ) && PayLaterBlockModule::is_enabled();
switch ( $location ) {
case 'checkout':
case 'cart':
@ -634,8 +641,13 @@ document.querySelector("#payment").before(document.querySelector("#ppcp-messages
case 'shop':
case 'home':
return $messaging_enabled_for_current_location;
case 'block-editor':
return true;
case 'checkout-block':
case 'cart-block':
return $has_paylater_block || $this->is_block_editor();
default:
return false;
return $has_paylater_block;
}
}
@ -843,9 +855,10 @@ document.querySelector("#payment").before(document.querySelector("#ppcp-messages
}
$product = wc_get_product();
$amount = ( is_a( $product, WC_Product::class ) ) ? wc_get_price_including_tax( $product ) : 0;
if ( is_checkout() || is_cart() ) {
$amount = 0;
if ( is_a( $product, WC_Product::class ) ) {
$amount = wc_get_price_including_tax( $product );
} elseif ( isset( WC()->cart ) ) {
$amount = WC()->cart->get_total( 'raw' );
}
@ -863,6 +876,9 @@ document.querySelector("#payment").before(document.querySelector("#ppcp-messages
return array(
'wrapper' => '#ppcp-messages',
'is_hidden' => ! $this->is_pay_later_filter_enabled_for_location( $this->context() ),
'block' => array(
'enabled' => PayLaterBlockModule::is_enabled(),
),
'amount' => $amount,
'placement' => $placement,
'style' => array(
@ -878,7 +894,6 @@ document.querySelector("#payment").before(document.querySelector("#ppcp-messages
'ratio' => $ratio,
),
);
}
/**

View file

@ -12,7 +12,7 @@ namespace WooCommerce\PayPalCommerce\Button\Endpoint;
use Psr\Log\LoggerInterface;
use Throwable;
use WooCommerce\PayPalCommerce\ApiClient\Entity\Money;
use WooCommerce\PayPalCommerce\Button\Assets\SmartButton;
use WooCommerce\PayPalCommerce\Button\Assets\SmartButtonInterface;
/**
* Class CartScriptParamsEndpoint.
@ -25,7 +25,7 @@ class CartScriptParamsEndpoint implements EndpointInterface {
/**
* The SmartButton.
*
* @var SmartButton
* @var SmartButtonInterface
*/
private $smart_button;
@ -39,11 +39,11 @@ class CartScriptParamsEndpoint implements EndpointInterface {
/**
* CartScriptParamsEndpoint constructor.
*
* @param SmartButton $smart_button he SmartButton.
* @param LoggerInterface $logger The logger.
* @param SmartButtonInterface $smart_button he SmartButton.
* @param LoggerInterface $logger The logger.
*/
public function __construct(
SmartButton $smart_button,
SmartButtonInterface $smart_button,
LoggerInterface $logger
) {
$this->smart_button = $smart_button;
@ -73,6 +73,10 @@ class CartScriptParamsEndpoint implements EndpointInterface {
$include_shipping = (bool) wc_clean( wp_unslash( $_GET['shipping'] ?? '' ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$script_data = $this->smart_button->script_data();
if ( ! $script_data ) {
wp_send_json_error();
return false;
}
$total = (float) WC()->cart->get_total( 'numeric' );

View file

@ -131,6 +131,10 @@ trait ContextTrait {
return 'add-payment-method';
}
if ( $this->is_block_editor() ) {
return 'block-editor';
}
return 'mini-cart';
}
@ -207,4 +211,15 @@ trait ContextTrait {
return $page_id && is_page( $page_id ) && isset( $wp->query_vars['add-payment-method'] );
}
/**
* Checks if it is the block editor page.
*/
protected function is_block_editor(): bool {
if ( ! function_exists( 'get_current_screen' ) ) {
return false;
}
$screen = get_current_screen();
return $screen && $screen->is_block_editor();
}
}

View file

@ -0,0 +1,14 @@
{
"presets": [
[
"@babel/preset-env",
{
"useBuiltIns": "usage",
"corejs": "3.25.0"
}
],
[
"@babel/preset-react"
]
]
}

View file

@ -0,0 +1,3 @@
node_modules
assets/js
assets/css

View file

@ -0,0 +1,48 @@
{
"$schema": "https://schemas.wp.org/trunk/block.json",
"apiVersion": 3,
"name": "woocommerce-paypal-payments/paylater-messages",
"title": "PayPal Pay Later messaging",
"category": "woocommerce",
"description": "PayPal Pay Later messaging will be displayed for eligible customers. Customers automatically see the most relevant Pay Later offering.",
"example": {},
"attributes": {
"id": {
"type": "string"
},
"layout": {
"type": "string",
"default": "flex"
},
"logo": {
"type": "string",
"default": "inline"
},
"position": {
"type": "string",
"default": "left"
},
"color": {
"type": "string",
"default": "black"
},
"flexColor": {
"type": "string",
"default": "white"
},
"flexRatio": {
"type": "string",
"default": "8x1"
},
"placement": {
"type": "string",
"default": "auto"
}
},
"supports": {
"html": false
},
"textdomain": "woocommerce-paypal-payments",
"editorScript": "ppcp-paylater-block",
"editorStyle": "file:./assets/css/edit.css"
}

View file

@ -0,0 +1,17 @@
{
"name": "woocommerce/ppcp-paylater-block",
"type": "dhii-mod",
"description": "Pay Later Block module for PPCP",
"license": "GPL-2.0",
"require": {
"php": "^7.2 | ^8.0",
"dhii/module-interface": "^0.3.0-alpha1"
},
"autoload": {
"psr-4": {
"WooCommerce\\PayPalCommerce\\PayLaterBlock\\": "src"
}
},
"minimum-stability": "dev",
"prefer-stable": true
}

View file

@ -0,0 +1,12 @@
<?php
/**
* The Pay Later block module extensions.
*
* @package WooCommerce\PayPalCommerce\PayLaterBlock
*/
declare(strict_types=1);
namespace WooCommerce\PayPalCommerce\PayLaterBlock;
return array();

View file

@ -0,0 +1,16 @@
<?php
/**
* The Pay Later block module.
*
* @package WooCommerce\PayPalCommerce\PayLaterBlock
*/
declare(strict_types=1);
namespace WooCommerce\PayPalCommerce\PayLaterBlock;
use WooCommerce\PayPalCommerce\Vendor\Dhii\Modular\Module\ModuleInterface;
return static function (): ModuleInterface {
return new PayLaterBlockModule();
};

View file

@ -0,0 +1,33 @@
{
"name": "ppcp-paylater-block",
"version": "1.0.0",
"license": "GPL-3.0-or-later",
"browserslist": [
"> 0.5%",
"Safari >= 8",
"Chrome >= 41",
"Firefox >= 43",
"Edge >= 14"
],
"dependencies": {
"core-js": "^3.25.0"
},
"devDependencies": {
"@babel/core": "^7.19",
"@babel/preset-env": "^7.19",
"@babel/preset-react": "^7.18.6",
"@woocommerce/dependency-extraction-webpack-plugin": "^2.2.0",
"babel-loader": "^8.2",
"cross-env": "^7.0.3",
"file-loader": "^6.2.0",
"sass": "^1.42.1",
"sass-loader": "^12.1.0",
"webpack": "^5.76",
"webpack-cli": "^4.10"
},
"scripts": {
"build": "cross-env BABEL_ENV=default NODE_ENV=production webpack",
"watch": "cross-env BABEL_ENV=default NODE_ENV=production webpack --watch",
"dev": "cross-env BABEL_ENV=default webpack --watch"
}
}

View file

@ -0,0 +1,19 @@
.ppcp-overlay-parent {
display: grid;
grid-template-columns: 1fr;
}
.ppcp-overlay-child {
grid-row-start: 1;
grid-column-start: 1;
}
.ppcp-unclicable-overlay {
z-index: 10;
}
.ppcp-paylater-unavailable {
p.block-editor-warning__message {
margin-bottom: 10px;
}
}

View file

@ -0,0 +1,29 @@
import { useRef, useEffect } from '@wordpress/element';
export default function PayPalMessages({
amount,
style,
onRender,
}) {
const containerRef = useRef(null);
useEffect(() => {
const messages = paypal.Messages({
amount,
style,
onRender,
});
messages.render(containerRef.current)
.catch(err => {
// Ignore when component destroyed.
if (!containerRef.current || containerRef.current.children.length === 0) {
return;
}
console.error(err);
});
}, [amount, style, onRender]);
return <div ref={containerRef}/>
}

View file

@ -0,0 +1,196 @@
import { __ } from '@wordpress/i18n';
import { useState, useEffect } from '@wordpress/element';
import { InspectorControls, useBlockProps } from '@wordpress/block-editor';
import { PanelBody, SelectControl, Spinner } from '@wordpress/components';
import { useScriptParams } from "./hooks/script-params";
import { loadPaypalScript } from '../../../ppcp-button/resources/js/modules/Helper/ScriptLoading'
import PayPalMessages from "./components/PayPalMessages";
export default function Edit( { attributes, clientId, setAttributes } ) {
const { layout, logo, position, color, flexColor, flexRatio, placement, id } = attributes;
const isFlex = layout === 'flex';
const [paypalScriptState, setPaypalScriptState] = useState(null);
const [rendered, setRendered] = useState(false);
let amount = undefined;
const postContent = String(wp.data.select('core/editor')?.getEditedPostContent());
if (postContent.includes('woocommerce/checkout') || postContent.includes('woocommerce/cart')) {
amount = 50.0;
}
const previewStyle = {
layout,
logo: {
position,
type: logo,
},
color: flexColor,
ratio: flexRatio,
text: {
color,
},
};
let classes = ['ppcp-paylater-block-preview', 'ppcp-overlay-parent'];
if (PcpPayLaterBlock.vaultingEnabled) {
classes = ['ppcp-paylater-block-preview', 'ppcp-paylater-unavailable', 'block-editor-warning'];
}
const props = useBlockProps({className: classes});
const loadingElement = <div {...props}><Spinner/></div>;
useEffect(() => {
if (!id) {
setAttributes({id: 'ppcp-' + clientId});
}
}, []);
if (PcpPayLaterBlock.vaultingEnabled) {
return <div {...props}>
<div className={'block-editor-warning__contents'}>
<h3>{__('PayPal Pay Later Messaging', 'woocommerce-paypal-payments')}</h3>
<p className={'block-editor-warning__message'}>{__('Pay Later Messaging cannot be used while PayPal Vaulting is active. Disable PayPal Vaulting in the PayPal Payment settings to reactivate this block', 'woocommerce-paypal-payments')}</p>
<div className={'class="block-editor-warning__actions"'}>
<span className={'block-editor-warning__action'}>
<a href={PcpPayLaterBlock.settingsUrl} className={'components-button is-primary'}>
{__('PayPal Payments Settings', 'woocommerce-paypal-payments')}
</a>
</span>
<span className={'block-editor-warning__action'}>
<button onClick={() => wp.data.dispatch( 'core/block-editor' ).removeBlock(clientId)} type={'button'} className={'components-button is-secondary'}>
{__('Remove Block', 'woocommerce-paypal-payments')}
</button>
</span>
</div>
</div>
</div>
}
let scriptParams = useScriptParams(PcpPayLaterBlock.ajax.cart_script_params);
if (scriptParams === null) {
return loadingElement;
}
if (scriptParams === false) {
scriptParams = {
url_params: {
clientId: 'test',
}
}
}
scriptParams.url_params.components = 'messages,buttons,funding-eligibility';
if (!paypalScriptState) {
loadPaypalScript(scriptParams, () => {
setPaypalScriptState('loaded')
}, () => {
setPaypalScriptState('failed')
});
}
if (paypalScriptState !== 'loaded') {
return loadingElement;
}
return (
<>
<InspectorControls>
<PanelBody title={ __( 'Settings', 'woocommerce-paypal-payments' ) }>
<SelectControl
label={ __( 'Layout', 'woocommerce-paypal-payments' ) }
options={ [
{ label: __( 'Text', 'woocommerce-paypal-payments' ), value: 'text' },
{ label: __( 'Banner', 'woocommerce-paypal-payments' ), value: 'flex' },
] }
value={ layout }
onChange={ ( value ) => setAttributes( { layout: value } ) }
/>
{ !isFlex && (<SelectControl
label={__('Logo', 'woocommerce-paypal-payments')}
options={[
{ label: __('Primary', 'woocommerce-paypal-payments'), value: 'primary' },
{ label: __('Alternative', 'woocommerce-paypal-payments'), value: 'alternative' },
{ label: __('Inline', 'woocommerce-paypal-payments'), value: 'inline' },
{ label: __('None', 'woocommerce-paypal-payments'), value: 'none' },
]}
value={logo}
onChange={(value) => setAttributes({logo: value})}
/>)}
{ !isFlex && logo === 'primary' && (<SelectControl
label={__('Logo Position', 'woocommerce-paypal-payments')}
options={[
{ label: __( 'Left', 'woocommerce-paypal-payments' ), value: 'left' },
{ label: __( 'Right', 'woocommerce-paypal-payments' ), value: 'right' },
{ label: __( 'Top', 'woocommerce-paypal-payments' ), value: 'top' },
]}
value={position}
onChange={(value) => setAttributes({position: value})}
/>)}
{ !isFlex && (<SelectControl
label={__('Text Color', 'woocommerce-paypal-payments')}
options={[
{ label: __( 'Black', 'woocommerce-paypal-payments' ), value: 'black' },
{ label: __( 'White', 'woocommerce-paypal-payments' ), value: 'white' },
{ label: __( 'Monochrome', 'woocommerce-paypal-payments' ), value: 'monochrome' },
{ label: __( 'Grayscale', 'woocommerce-paypal-payments' ), value: 'grayscale' },
]}
value={color}
onChange={(value) => setAttributes({color: value})}
/>)}
{ isFlex && (<SelectControl
label={__('Color', 'woocommerce-paypal-payments')}
options={[
{ label: __( 'Blue', 'woocommerce-paypal-payments' ), value: 'blue' },
{ label: __( 'Black', 'woocommerce-paypal-payments' ), value: 'black' },
{ label: __( 'White', 'woocommerce-paypal-payments' ), value: 'white' },
{ label: __( 'White no border', 'woocommerce-paypal-payments' ), value: 'white-no-border' },
{ label: __( 'Gray', 'woocommerce-paypal-payments' ), value: 'gray' },
{ label: __( 'Monochrome', 'woocommerce-paypal-payments' ), value: 'monochrome' },
{ label: __( 'Grayscale', 'woocommerce-paypal-payments' ), value: 'grayscale' },
]}
value={flexColor}
onChange={(value) => setAttributes({flexColor: value})}
/>)}
{ isFlex && (<SelectControl
label={__('Ratio', 'woocommerce-paypal-payments')}
options={[
{ label: __( '1x1', 'woocommerce-paypal-payments' ), value: '1x1' },
{ label: __( '1x4', 'woocommerce-paypal-payments' ), value: '1x4' },
{ label: __( '8x1', 'woocommerce-paypal-payments' ), value: '8x1' },
{ label: __( '20x1', 'woocommerce-paypal-payments' ), value: '20x1' },
]}
value={flexRatio}
onChange={(value) => setAttributes({flexRatio: value})}
/>)}
<SelectControl
label={ __( 'Placement page', 'woocommerce-paypal-payments' ) }
help={ __( 'Used for the analytics dashboard in the merchant account.', 'woocommerce-paypal-payments' ) }
options={ [
{ label: __( 'Detect automatically', 'woocommerce-paypal-payments' ), value: 'auto' },
{ label: __( 'Cart', 'woocommerce-paypal-payments' ), value: 'cart' },
{ label: __( 'Payment', 'woocommerce-paypal-payments' ), value: 'payment' },
{ label: __( 'Product', 'woocommerce-paypal-payments' ), value: 'product' },
{ label: __( 'Product list', 'woocommerce-paypal-payments' ), value: 'product-list' },
{ label: __( 'Home', 'woocommerce-paypal-payments' ), value: 'home' },
{ label: __( 'Category', 'woocommerce-paypal-payments' ), value: 'category' },
] }
value={ placement }
onChange={ ( value ) => setAttributes( { placement: value } ) }
/>
</PanelBody>
</InspectorControls>
<div {...props}>
<div className={'ppcp-overlay-child'}>
<PayPalMessages
style={previewStyle}
amount={amount}
onRender={() => setRendered(true)}
/>
</div>
<div className={'ppcp-overlay-child ppcp-unclicable-overlay'}> {/* make the message not clickable */}
{!rendered && (<Spinner/>)}
</div>
</div>
</>
);
}

View file

@ -0,0 +1,24 @@
import { useState, useEffect } from '@wordpress/element';
export const useScriptParams = (requestConfig) => {
const [data, setData] = useState(null);
useEffect(() => {
(async () => {
try {
const response = await fetch(requestConfig.endpoint);
const json = await response.json();
if (json.success && json?.data?.url_params) {
setData(json.data);
} else {
setData(false);
}
} catch (e) {
console.error(e);
setData(false);
}
})();
}, [requestConfig]);
return data;
};

View file

@ -0,0 +1,36 @@
import { registerBlockType } from '@wordpress/blocks';
import Edit from './edit';
import save from './save';
const paypalIcon = (
<svg width="584.798" height="720" viewBox="0 0 154.728 190.5">
<g transform="translate(898.192 276.071)">
<path clipPath="none" d="M-837.663-237.968a5.49 5.49 0 0 0-5.423 4.633l-9.013 57.15-8.281 52.514-.005.044.01-.044 8.281-52.514c.421-2.669 2.719-4.633 5.42-4.633h26.404c26.573 0 49.127-19.387 53.246-45.658.314-1.996.482-3.973.52-5.924v-.003h-.003c-6.753-3.543-14.683-5.565-23.372-5.565z" fill="#001c64"/>
<path clipPath="none" d="M-766.506-232.402c-.037 1.951-.207 3.93-.52 5.926-4.119 26.271-26.673 45.658-53.246 45.658h-26.404c-2.701 0-4.999 1.964-5.42 4.633l-8.281 52.514-5.197 32.947a4.46 4.46 0 0 0 4.405 5.153h28.66a5.49 5.49 0 0 0 5.423-4.633l7.55-47.881c.423-2.669 2.722-4.636 5.423-4.636h16.876c26.573 0 49.124-19.386 53.243-45.655 2.924-18.649-6.46-35.614-22.511-44.026z" fill="#0070e0"/>
<path clipPath="none" d="M-870.225-276.071a5.49 5.49 0 0 0-5.423 4.636l-22.489 142.608a4.46 4.46 0 0 0 4.405 5.156h33.351l8.281-52.514 9.013-57.15a5.49 5.49 0 0 1 5.423-4.633h47.782c8.691 0 16.621 2.025 23.375 5.563.46-23.917-19.275-43.666-46.412-43.666z" fill="#003087"/>
</g>
</svg>
)
const blockId = 'woocommerce-paypal-payments/paylater-messages';
registerBlockType( blockId, {
icon: paypalIcon,
edit: Edit,
save,
} );
document.addEventListener( 'DOMContentLoaded', () => {
const { registerCheckoutFilters } = window.wc.blocksCheckout;
// allow to add this block inside WC cart/checkout blocks
registerCheckoutFilters( blockId, {
additionalCartCheckoutInnerBlockTypes: (
defaultValue
) => {
defaultValue.push( blockId );
return defaultValue;
},
} );
} );

View file

@ -0,0 +1,25 @@
import { useBlockProps } from '@wordpress/block-editor';
export default function save( { attributes } ) {
const { layout, logo, position, color, flexColor, flexRatio, placement, id } = attributes;
const paypalAttributes = layout === 'flex' ? {
'data-pp-style-layout': 'flex',
'data-pp-style-color': flexColor,
'data-pp-style-ratio': flexRatio,
} : {
'data-pp-style-layout': 'text',
'data-pp-style-logo-type': logo,
'data-pp-style-logo-position': position,
'data-pp-style-text-color': color,
};
if (placement && placement !== 'auto') {
paypalAttributes['data-pp-placement'] = placement;
}
const props = {
className: 'ppcp-paylater-message-block',
id,
...paypalAttributes,
};
return <div { ...useBlockProps.save(props) }></div>;
}

View file

@ -0,0 +1,26 @@
<?php
/**
* The Pay Later block module services.
*
* @package WooCommerce\PayPalCommerce\PayLaterBlock
*/
declare(strict_types=1);
namespace WooCommerce\PayPalCommerce\PayLaterBlock;
use WooCommerce\PayPalCommerce\Vendor\Psr\Container\ContainerInterface;
return array(
'paylater-block.url' => static function ( ContainerInterface $container ): string {
/**
* Cannot return false for this path.
*
* @psalm-suppress PossiblyFalseArgument
*/
return plugins_url(
'/modules/ppcp-paylater-block/',
dirname( realpath( __FILE__ ), 3 ) . '/woocommerce-paypal-payments.php'
);
},
);

View file

@ -0,0 +1,102 @@
<?php
/**
* The Pay Later block module.
*
* @package WooCommerce\PayPalCommerce\PayLaterBlock
*/
declare(strict_types=1);
namespace WooCommerce\PayPalCommerce\PayLaterBlock;
use WooCommerce\PayPalCommerce\Button\Endpoint\CartScriptParamsEndpoint;
use WooCommerce\PayPalCommerce\Button\Helper\MessagesApply;
use WooCommerce\PayPalCommerce\Vendor\Dhii\Container\ServiceProvider;
use WooCommerce\PayPalCommerce\Vendor\Dhii\Modular\Module\ModuleInterface;
use WooCommerce\PayPalCommerce\Vendor\Interop\Container\ServiceProviderInterface;
use WooCommerce\PayPalCommerce\Vendor\Psr\Container\ContainerInterface;
use WooCommerce\PayPalCommerce\WcGateway\Settings\Settings;
/**
* Class PayLaterBlockModule
*/
class PayLaterBlockModule implements ModuleInterface {
/**
* Returns whether the block should be loaded.
*/
public static function is_enabled(): bool {
return apply_filters(
// phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
'woocommerce.feature-flags.woocommerce_paypal_payments.paylater_block_enabled',
getenv( 'PCP_PAYLATER_BLOCK' ) !== '0'
);
}
/**
* {@inheritDoc}
*/
public function setup(): ServiceProviderInterface {
return new ServiceProvider(
require __DIR__ . '/../services.php',
require __DIR__ . '/../extensions.php'
);
}
/**
* {@inheritDoc}
*/
public function run( ContainerInterface $c ): void {
$messages_apply = $c->get( 'button.helper.messages-apply' );
assert( $messages_apply instanceof MessagesApply );
if ( ! $messages_apply->for_country() ) {
return;
}
$settings = $c->get( 'wcgateway.settings' );
assert( $settings instanceof Settings );
add_action(
'init',
function () use ( $c, $settings ): void {
$script_handle = 'ppcp-paylater-block';
wp_register_script(
$script_handle,
$c->get( 'paylater-block.url' ) . '/assets/js/paylater-block.js',
array(),
$c->get( 'ppcp.asset-version' ),
true
);
wp_localize_script(
$script_handle,
'PcpPayLaterBlock',
array(
'ajax' => array(
'cart_script_params' => array(
'endpoint' => \WC_AJAX::get_endpoint( CartScriptParamsEndpoint::ENDPOINT ),
),
),
'settingsUrl' => admin_url( 'admin.php?page=wc-settings&tab=checkout&section=ppcp-gateway' ),
'vaultingEnabled' => $settings->has( 'vault_enabled' ) && $settings->get( 'vault_enabled' ),
)
);
/**
* Cannot return false for this path.
*
* @psalm-suppress PossiblyFalseArgument
*/
register_block_type( dirname( realpath( __FILE__ ), 2 ) );
},
20
);
}
/**
* Returns the key for the module.
*
* @return string|void
*/
public function getKey() {
}
}

View file

@ -0,0 +1,39 @@
const path = require('path');
const isProduction = process.env.NODE_ENV === 'production';
const DependencyExtractionWebpackPlugin = require( '@woocommerce/dependency-extraction-webpack-plugin' );
module.exports = {
devtool: isProduction ? 'source-map' : 'eval-source-map',
mode: isProduction ? 'production' : 'development',
target: 'web',
plugins: [ new DependencyExtractionWebpackPlugin() ],
entry: {
'paylater-block': path.resolve('./resources/js/paylater-block.js'),
'edit': path.resolve('./resources/css/edit.scss'),
},
output: {
path: path.resolve(__dirname, 'assets/'),
filename: 'js/[name].js',
},
module: {
rules: [{
test: /\.js?$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
{
test: /\.scss$/,
exclude: /node_modules/,
use: [
{
loader: 'file-loader',
options: {
name: 'css/[name].css',
}
},
{loader:'sass-loader'}
]
}]
}
};

File diff suppressed because it is too large Load diff

View file

@ -33,15 +33,19 @@ class SettingsStatus {
}
/**
* Check whether Pay Later message is enabled either for checkout, cart or product page.
*
* @return bool true if is enabled, otherwise false.
* Checks whether Pay Later messaging is enabled.
*/
public function is_pay_later_messaging_enabled(): bool {
$messaging_enabled = $this->settings->has( 'pay_later_messaging_enabled' ) && $this->settings->get( 'pay_later_messaging_enabled' );
return $this->settings->has( 'pay_later_messaging_enabled' ) && $this->settings->get( 'pay_later_messaging_enabled' );
}
/**
* Check whether any Pay Later messaging location is enabled.
*/
public function has_pay_later_messaging_locations(): bool {
$selected_locations = $this->settings->has( 'pay_later_messaging_locations' ) ? $this->settings->get( 'pay_later_messaging_locations' ) : array();
return $messaging_enabled && ! empty( $selected_locations );
return ! empty( $selected_locations );
}
/**
@ -51,7 +55,9 @@ class SettingsStatus {
* @return bool true if is enabled, otherwise false.
*/
public function is_pay_later_messaging_enabled_for_location( string $location ): bool {
return $this->is_pay_later_messaging_enabled() && $this->is_enabled_for_location( 'pay_later_messaging_locations', $location );
return $this->is_pay_later_messaging_enabled() &&
$this->has_pay_later_messaging_locations() &&
$this->is_enabled_for_location( 'pay_later_messaging_locations', $location );
}
/**
@ -85,6 +91,9 @@ class SettingsStatus {
* @return bool true if is enabled, otherwise false.
*/
public function is_smart_button_enabled_for_location( string $location ): bool {
if ( $location === 'block-editor' ) {
$location = 'checkout-block';
}
return $this->is_enabled_for_location( 'smart_button_locations', $location );
}

View file

@ -533,19 +533,5 @@ $data_rows_html
</tr>
<?php
}
/**
* Checks if vaulting admin message can be displayed.
*
* @return bool Whether the message can be displayed or not.
*/
private function can_display_vaulting_admin_message(): bool {
if ( State::STATE_ONBOARDED !== $this->state->current_state() ) {
return false;
}
return $this->is_paypal_checkout_screen()
&& ( $this->paypal_vaulting_is_enabled() || $this->settings_status->is_pay_later_messaging_enabled() );
}
}