Init session with handlers

This commit is contained in:
carmenmaymo 2023-09-07 09:56:46 +02:00
parent cffdec846c
commit 7b3f3e8ead
No known key found for this signature in database
GPG key ID: 6023F686B0F3102E
16 changed files with 279 additions and 63 deletions

View file

@ -37,15 +37,20 @@ class ApplepayButton {
this.applePayConfig = config;
const isEligible = this.applePayConfig.isEligible;
if (isEligible) {
this.addButton();
document.querySelector('#btn-appl').addEventListener('click', (evt) => {
evt.preventDefault()
this.onButtonClick()
})
this.fetchTransactionInfo().then(() => {
this.addButton();
document.querySelector('#btn-appl').addEventListener('click', (evt) => {
evt.preventDefault();
this.onButtonClick();
});
});
}
console.log('[ApplePayButton] init done', this.buttonConfig.ajax_url);
}
async fetchTransactionInfo() {
this.transactionInfo = await this.contextHandler.transactionInfo();
}
buildReadyToPayRequest(allowedPaymentMethods, baseRequest) {
return Object.assign({}, baseRequest, {
@ -53,6 +58,7 @@ class ApplepayButton {
});
}
applePaySession(paymentRequest) {
console.log('apple session', paymentRequest)
const session = new ApplePaySession(4, paymentRequest)
session.begin()
const ajaxUrl = this.buttonConfig.ajax_url
@ -109,57 +115,25 @@ class ApplepayButton {
paymentDataRequest() {
const applepayConfig = this.applePayConfig
const buttonConfig = this.buttonConfig
let baseRequest = {
countryCode: applepayConfig.countryCode,
merchantCapabilities: applepayConfig.merchantCapabilities,
supportedNetworks: applepayConfig.supportedNetworks,
requiredShippingContactFields: ["name", "phone",
"email", "postalAddress"],
requiredBillingContactFields: ["name", "phone", "email",
"postalAddress"]
}
console.log('[ApplePayButton] paymentDataRequest', applepayConfig, buttonConfig);
function product_request() {
document.querySelector('input.qty').addEventListener('change', event => {
this.productQuantity = event.currentTarget.value
})
this.productQuantity = parseInt(this.productQuantity)
const amountWithoutTax = this.productQuantity * buttonConfig.product.price
return {
countryCode: applepayConfig.countryCode,
merchantCapabilities: applepayConfig.merchantCapabilities,
supportedNetworks: applepayConfig.supportedNetworks,
currencyCode: buttonConfig.shop.currencyCode,
requiredShippingContactFields: ["name", "phone",
"email", "postalAddress"],
requiredBillingContactFields: ["name", "phone", "email",
"postalAddress"],
total: {
label: buttonConfig.shop.totalLabel,
type: "final",
amount: amountWithoutTax,
}
}
const paymentDataRequest = Object.assign({}, baseRequest);
paymentDataRequest.currencyCode = buttonConfig.shop.currencyCode;
paymentDataRequest.total = {
label: buttonConfig.shop.totalLabel,
type: "final",
amount: this.transactionInfo.totalPrice,
}
function cart_request() {
const priceContent = jQuery('.cart-subtotal .woocommerce-Price-amount bdi').contents()[1]
const priceString = priceContent.nodeValue.trim();
const price = parseFloat(priceString);
return {
countryCode: applepayConfig.countryCode,
merchantCapabilities: applepayConfig.merchantCapabilities,
supportedNetworks: applepayConfig.supportedNetworks,
currencyCode: buttonConfig.shop.currencyCode,
requiredShippingContactFields: ["name", "phone",
"email", "postalAddress"],
requiredBillingContactFields: ["name", "phone", "email",
"postalAddress"],
total: {
label: buttonConfig.shop.totalLabel,
type: "final",
amount: price,
}
}
}
switch (this.context) {
case 'product': return product_request.call(this);
case 'cart':
case 'checkout':
return cart_request.call(this);
}
return paymentDataRequest
}

View file

@ -8,7 +8,7 @@ class ApplepayManager {
this.buttonConfig = buttonConfig;
this.ppcpConfig = ppcpConfig;
this.ApplePayConfig = null;
console.log('Applepay manager', ppcpConfig, buttonConfig)
this.buttons = [];
buttonModuleWatcher.watchContextBootstrap((bootstrap) => {

View file

@ -0,0 +1,73 @@
import ErrorHandler from "../../../../ppcp-button/resources/js/modules/ErrorHandler";
import CartActionHandler
from "../../../../ppcp-button/resources/js/modules/ActionHandler/CartActionHandler";
import onApprove
from "../../../../ppcp-button/resources/js/modules/OnApproveHandler/onApproveForContinue";
class BaseHandler {
constructor(buttonConfig, ppcpConfig) {
this.buttonConfig = buttonConfig;
this.ppcpConfig = ppcpConfig;
}
transactionInfo() {
return new Promise((resolve, reject) => {
fetch(
this.ppcpConfig.ajax.cart_script_params.endpoint,
{
method: 'GET',
credentials: 'same-origin',
}
)
.then(result => result.json())
.then(result => {
if (! result.success) {
return;
}
// handle script reload
const data = result.data;
resolve({
countryCode: data.country_code,
currencyCode: data.currency_code,
totalPriceStatus: 'FINAL',
totalPrice: data.total_str
});
});
});
}
createOrder() {
const errorHandler = new ErrorHandler(
this.ppcpConfig.labels.error.generic,
document.querySelector('.woocommerce-notices-wrapper')
);
const actionHandler = new CartActionHandler(
this.ppcpConfig,
errorHandler,
);
return actionHandler.configuration().createOrder(null, null);
}
approveOrderForContinue(data, actions) {
const errorHandler = new ErrorHandler(
this.ppcpConfig.labels.error.generic,
document.querySelector('.woocommerce-notices-wrapper')
);
let onApproveHandler = onApprove({
config: this.ppcpConfig
}, errorHandler);
return onApproveHandler(data, actions);
}
}
export default BaseHandler;

View file

@ -0,0 +1,7 @@
import BaseHandler from "./BaseHandler";
class CartBlockHandler extends BaseHandler {
}
export default CartBlockHandler;

View file

@ -0,0 +1,7 @@
import BaseHandler from "./BaseHandler";
class CartHandler extends BaseHandler {
}
export default CartHandler;

View file

@ -0,0 +1,7 @@
import BaseHandler from "./BaseHandler";
class CheckoutBlockHandler extends BaseHandler{
}
export default CheckoutBlockHandler;

View file

@ -0,0 +1,28 @@
import Spinner from "../../../../ppcp-button/resources/js/modules/Helper/Spinner";
import CheckoutActionHandler
from "../../../../ppcp-button/resources/js/modules/ActionHandler/CheckoutActionHandler";
import ErrorHandler from "../../../../ppcp-button/resources/js/modules/ErrorHandler";
import BaseHandler from "./BaseHandler";
class CheckoutHandler extends BaseHandler {
createOrder() {
const errorHandler = new ErrorHandler(
this.ppcpConfig.labels.error.generic,
document.querySelector('.woocommerce-notices-wrapper')
);
const spinner = new Spinner();
const actionHandler = new CheckoutActionHandler(
this.ppcpConfig,
errorHandler,
spinner
);
return actionHandler.configuration().createOrder(null, null);
}
}
export default CheckoutHandler;

View file

@ -0,0 +1,29 @@
import SingleProductHandler from "./SingleProductHandler";
import CartHandler from "./CartHandler";
import CheckoutHandler from "./CheckoutHandler";
import CartBlockHandler from "./CartBlockHandler";
import CheckoutBlockHandler from "./CheckoutBlockHandler";
import MiniCartHandler from "./MiniCartHandler";
class ContextHandlerFactory {
static create(context, buttonConfig, ppcpConfig) {
switch (context) {
case 'product':
return new SingleProductHandler(buttonConfig, ppcpConfig);
case 'cart':
return new CartHandler(buttonConfig, ppcpConfig);
case 'checkout':
case 'pay-now': // same as checkout
return new CheckoutHandler(buttonConfig, ppcpConfig);
case 'mini-cart':
return new MiniCartHandler(buttonConfig, ppcpConfig);
case 'cart-block':
return new CartBlockHandler(buttonConfig, ppcpConfig);
case 'checkout-block':
return new CheckoutBlockHandler(buttonConfig, ppcpConfig);
}
}
}
export default ContextHandlerFactory;

View file

@ -0,0 +1,7 @@
import BaseHandler from "./BaseHandler";
class MiniCartHandler extends BaseHandler {
}
export default MiniCartHandler;

View file

@ -0,0 +1,72 @@
import SingleProductActionHandler
from "../../../../ppcp-button/resources/js/modules/ActionHandler/SingleProductActionHandler";
import SimulateCart from "../../../../ppcp-button/resources/js/modules/Helper/SimulateCart";
import ErrorHandler from "../../../../ppcp-button/resources/js/modules/ErrorHandler";
import UpdateCart from "../../../../ppcp-button/resources/js/modules/Helper/UpdateCart";
import BaseHandler from "./BaseHandler";
class SingleProductHandler extends BaseHandler {
transactionInfo() {
const errorHandler = new ErrorHandler(
this.ppcpConfig.labels.error.generic,
document.querySelector('.woocommerce-notices-wrapper')
);
function form() {
return document.querySelector('form.cart');
}
const actionHandler = new SingleProductActionHandler(
null,
null,
form(),
errorHandler,
);
const hasSubscriptions = PayPalCommerceGateway.data_client_id.has_subscriptions
&& PayPalCommerceGateway.data_client_id.paypal_subscriptions_enabled;
const products = hasSubscriptions
? actionHandler.getSubscriptionProducts()
: actionHandler.getProducts();
return new Promise((resolve, reject) => {
(new SimulateCart(
this.ppcpConfig.ajax.simulate_cart.endpoint,
this.ppcpConfig.ajax.simulate_cart.nonce,
)).simulate((data) => {
resolve({
countryCode: data.country_code,
currencyCode: data.currency_code,
totalPriceStatus: 'FINAL',
totalPrice: data.total_str
});
}, products);
});
}
createOrder() {
const errorHandler = new ErrorHandler(
this.ppcpConfig.labels.error.generic,
document.querySelector('.woocommerce-notices-wrapper')
);
const actionHandler = new SingleProductActionHandler(
this.ppcpConfig,
new UpdateCart(
this.ppcpConfig.ajax.change_cart.endpoint,
this.ppcpConfig.ajax.change_cart.nonce,
),
document.querySelector('form.cart'),
errorHandler,
);
return actionHandler.configuration().createOrder();
}
}
export default SingleProductHandler;

View file

@ -24,6 +24,7 @@ import ApplepayManager from "./ApplepayManager";
return;
}
console.log(buttonConfig.button.wrapper)
console.log(jQuery(buttonConfig.button.wrapper).length)
// If button wrapper is not present then there is no need to load the scripts.
if (!jQuery(buttonConfig.button.wrapper).length) {
return;

View file

@ -9,10 +9,12 @@ declare(strict_types=1);
namespace WooCommerce\PayPalCommerce\Applepay;
use Automattic\WooCommerce\Blocks\Payments\PaymentMethodTypeInterface;
use WooCommerce\PayPalCommerce\ApiClient\Helper\Cache;
use WooCommerce\PayPalCommerce\Applepay\Assets\ApplePayButton;
use WooCommerce\PayPalCommerce\Applepay\Assets\AppleProductStatus;
use WooCommerce\PayPalCommerce\Applepay\Assets\DataToAppleButtonScripts;
use WooCommerce\PayPalCommerce\Applepay\Assets\BlocksPaymentMethod;
use WooCommerce\PayPalCommerce\Vendor\Psr\Container\ContainerInterface;
use WooCommerce\PayPalCommerce\WcGateway\Settings\Settings;
@ -32,7 +34,6 @@ return array(
$status = $container->get( 'applepay.apple-product-status' );
assert( $status instanceof AppleProductStatus);
return $status->apple_is_active();
},
'applepay.server_supported' => static function ( ContainerInterface $container ): bool {
return ! empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] !== 'off';
@ -65,4 +66,13 @@ return array(
$container->get( 'wcgateway.settings.status' ),
);
},
'applepay.blocks-payment-method' => static function ( ContainerInterface $container ): PaymentMethodTypeInterface {
return new BlocksPaymentMethod(
'ppcp-applepay',
$container->get( 'applepay.url' ),
$container->get( 'ppcp.asset-version' ),
$container->get( 'applepay.button' ),
$container->get( 'blocks.method' )
);
},
);

View file

@ -9,6 +9,7 @@ declare(strict_types=1);
namespace WooCommerce\PayPalCommerce\Applepay;
use Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry;
use WooCommerce\PayPalCommerce\ApiClient\Helper\Cache;
use WooCommerce\PayPalCommerce\Applepay\Assets\AppleProductStatus;
use WooCommerce\PayPalCommerce\Button\Assets\ButtonInterface;
@ -87,12 +88,12 @@ class ApplepayModule implements ModuleInterface {
$this->render_buttons( $c );
assert( $apple_payment_method instanceof ButtonInterface );
$apple_payment_method->bootstrap_ajax_request();
/*add_action(
add_action(
'woocommerce_blocks_payment_method_type_registration',
function( PaymentMethodRegistry $payment_method_registry ) use ( $c ): void {
$payment_method_registry->register( $c->get( 'googlepay.blocks-payment-method' ) );
$payment_method_registry->register( $c->get( 'applepay.blocks-payment-method' ) );
}
);*/
);
$this->remove_status_cache($c);
}

View file

@ -914,7 +914,7 @@ class ApplePayButton implements ButtonInterface {
add_action(
$render_placeholder,
function () {
echo '<span id="applepay-container-minicart" class="ppcp-button-applepay ppcp-button-minicart"></span>';
echo '<span id="applepay-container" class="ppcp-button-applepay ppcp-button-minicart"></span>';
},
21
);

View file

@ -87,7 +87,7 @@ class AppleProductStatus {
return false;
}
/*if ( $this->cache->has( self::APPLE_STATUS_CACHE_KEY ) ) {
if ( $this->cache->has( self::APPLE_STATUS_CACHE_KEY ) ) {
return $this->cache->get( self::APPLE_STATUS_CACHE_KEY ) === 'true';
}
@ -97,7 +97,7 @@ class AppleProductStatus {
if ( $this->settings->has( 'products_apple_enabled' ) && $this->settings->get( 'products_apple_enabled' ) === true ) {
$this->current_status_cache = true;
return true;
}*/
}
try {
$seller_status = $this->partners_endpoint->seller_status();

View file

@ -116,7 +116,7 @@ class DataToAppleButtonScripts {
'sdk_url' => $this->sdk_url,
'button' => array(
'wrapper' => '#applepay-container',
'mini_cart_wrapper' => '#applepay-container-minicart',
'mini_cart_wrapper' => '#applepay-container',
'type' => $type,
'color' => $color,
'lang' => $lang,
@ -160,7 +160,7 @@ class DataToAppleButtonScripts {
'sdk_url' => $this->sdk_url,
'button' => array(
'wrapper' => '#applepay-container',
'mini_cart_wrapper' => '#applepay-container-minicart',
'mini_cart_wrapper' => '#applepay-container',
),
'product' => array(
'needShipping' => $cart->needs_shipping(),