woocommerce-paypal-payments/modules.local/ppcp-button/src/Assets/SmartButton.php

115 lines
3 KiB
PHP
Raw Normal View History

2020-04-02 08:38:00 +03:00
<?php
declare(strict_types=1);
namespace Inpsyde\PayPalCommerce\Button\Assets;
use Inpsyde\PayPalCommerce\Button\Endpoint\ChangeCartEndpoint;
use Inpsyde\PayPalCommerce\Button\Endpoint\CreateOrderEndpoint;
class SmartButton
{
private $moduleUrl;
private $isSandbox;
public function __construct(
string $moduleUrl,
bool $isSandbox
) {
2020-04-06 11:16:18 +03:00
2020-04-02 08:38:00 +03:00
$this->moduleUrl = $moduleUrl;
$this->isSandbox = $isSandbox;
}
public function renderWrapper() : bool
{
2020-04-06 11:16:18 +03:00
$renderer = function () {
2020-04-02 08:38:00 +03:00
echo '<div id="ppc-button"></div>';
};
2020-04-08 12:33:34 +03:00
if (is_cart()) {
add_action(
'woocommerce_after_cart_totals',
$renderer,
20
);
}
2020-04-02 08:38:00 +03:00
if (is_product()) {
add_action(
'woocommerce_single_product_summary',
$renderer,
31
);
}
if (is_checkout()) {
add_action(
'wp_footer',
$renderer,
31
);
}
2020-04-08 12:33:34 +03:00
add_action(
'woocommerce_widget_shopping_cart_buttons',
function () {
2020-04-08 12:33:34 +03:00
echo '<span id="ppc-button-minicart"></span>';
},
30
);
return true;
2020-04-02 08:38:00 +03:00
}
public function enqueue() : bool
{
wp_enqueue_script(
'paypal-smart-button',
$this->moduleUrl . '/assets/js/button.js'
);
$params = [
'client-id' => 'AcVzowpNCpTxFzLG7onQI4JD0sVcA0BkZv-D42qRZPv_gZ8cNfX9zGL_8bXmSu7cbJ5B2DH7sot8vDpw',
2020-04-06 10:51:56 +03:00
'currency' => get_woocommerce_currency(),
2020-04-02 08:38:00 +03:00
];
$smartButtonUrl = add_query_arg($params, 'https://www.paypal.com/sdk/js');
$localize = [
'redirect' => wc_get_checkout_url(),
'context' => $this->context(),
'ajax' => [
'change_cart' => [
2020-04-06 11:16:18 +03:00
'endpoint' => home_url(\WC_AJAX::get_endpoint(ChangeCartEndpoint::ENDPOINT)),
2020-04-02 08:38:00 +03:00
'nonce' => wp_create_nonce(ChangeCartEndpoint::nonce()),
],
'create_order' => [
2020-04-06 11:16:18 +03:00
'endpoint' => home_url(\WC_AJAX::get_endpoint(CreateOrderEndpoint::ENDPOINT)),
2020-04-02 08:38:00 +03:00
'nonce' => wp_create_nonce(CreateOrderEndpoint::nonce()),
],
],
'button' => [
'wrapper' => '#ppc-button',
2020-04-08 12:33:34 +03:00
'mini_cart_wrapper' => '#ppc-button-minicart',
2020-04-02 08:38:00 +03:00
'url' =>$smartButtonUrl,
2020-04-06 11:16:18 +03:00
],
2020-04-02 08:38:00 +03:00
];
wp_localize_script(
'paypal-smart-button',
'PayPalCommerceGateway',
$localize
);
return true;
}
2020-04-06 11:16:18 +03:00
private function context() : string
{
2020-04-02 08:38:00 +03:00
$context = 'mini-cart';
if (is_product()) {
$context = 'product';
}
if (is_cart()) {
$context = 'cart';
}
if (is_checkout()) {
$context = 'checkout';
}
return $context;
}
2020-04-06 11:16:18 +03:00
}