Skip to content

Commit

Permalink
Add decorators and strategies for request
Browse files Browse the repository at this point in the history
  • Loading branch information
mmaymo committed Dec 16, 2024
1 parent 867b71a commit 6960bdf
Show file tree
Hide file tree
Showing 15 changed files with 538 additions and 243 deletions.
33 changes: 13 additions & 20 deletions src/Payment/MollieObject.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Mollie\Api\Resources\Order;
use Mollie\Api\Resources\Payment;
use Mollie\WooCommerce\Gateway\MolliePaymentGatewayHandler;
use Mollie\WooCommerce\Payment\Request\RequestFactory;
use Mollie\WooCommerce\PaymentMethods\Voucher;
use Mollie\WooCommerce\SDK\Api;
use Mollie\WooCommerce\Settings\Settings;
Expand Down Expand Up @@ -55,8 +56,17 @@ class MollieObject
* @var null
*/
private $paymentMethod;

public function __construct($data, Logger $logger, PaymentFactory $paymentFactory, Api $apiHelper, Settings $settingsHelper, string $pluginId)
protected RequestFactory $requestFactory;

public function __construct(
$data,
Logger $logger,
PaymentFactory $paymentFactory,
Api $apiHelper,
Settings $settingsHelper,
string $pluginId,
RequestFactory $requestFactory
)
{
$this->data = $data;
$this->logger = $logger;
Expand All @@ -67,6 +77,7 @@ public function __construct($data, Logger $logger, PaymentFactory $paymentFactor
$base_location = wc_get_base_location();
static::$shop_country = $base_location['country'];
$this->paymentMethod = null;
$this->requestFactory = $requestFactory;
}

public function data()
Expand Down Expand Up @@ -657,24 +668,6 @@ protected function addMandateIdMetaToFirstPaymentSubscriptionOrder(
}
}
}

protected function addSequenceTypeForSubscriptionsFirstPayments($orderId, $gateway, $paymentRequestData): array
{
if ($this->dataHelper->isSubscription($orderId) || $this->dataHelper->isWcSubscription($orderId)) {
$disable_automatic_payments = apply_filters($this->pluginId . '_is_automatic_payment_disabled', false);
$supports_subscriptions = $gateway->supports('subscriptions');

if ($supports_subscriptions == true && $disable_automatic_payments == false) {
$paymentRequestData = $this->addSequenceTypeFirst($paymentRequestData);
}
}
return $paymentRequestData;
}

public function addSequenceTypeFirst($paymentRequestData)
{
}

/**
* @param $order
*/
Expand Down
122 changes: 2 additions & 120 deletions src/Payment/MollieOrder.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,95 +90,10 @@ public function getPaymentObject($paymentId, $testMode = false, $useCache = true
*/
public function getPaymentRequestData($order, $customerId, $voucherDefaultCategory = Voucher::NO_CATEGORY)
{
$settingsHelper = $this->settingsHelper;
$paymentLocale = $settingsHelper->getPaymentLocale();
$storeCustomer = $settingsHelper->shouldStoreCustomer();

$gateway = wc_get_payment_gateway_by_order($order);

if (! $gateway || ! ( $gateway instanceof PaymentGateway )) {
return [ 'result' => 'failure' ];
}

$gatewayId = $gateway->id;
$selectedIssuer = $this->getSelectedIssuer($gatewayId);
$returnUrl = $gateway->get_return_url($order);
$returnUrl = $this->getReturnUrl($order, $returnUrl);
$webhookUrl = $this->getWebhookUrl($order, $gatewayId);
$isPayPalExpressOrder = $order->get_meta('_mollie_payment_method_button') === 'PayPalButton';
$billingAddress = null;
if (!$isPayPalExpressOrder) {
$billingAddress = $this->createBillingAddress($order);
$shippingAddress = $this->createShippingAddress($order);
}

// Generate order lines for Mollie Orders
$orderLinesHelper = $this->orderLines;
$orderLines = $orderLinesHelper->order_lines($order, $voucherDefaultCategory);
$methodId = substr($gateway->id, strrpos($gateway->id, '_') + 1);

// Build the Mollie order data
$paymentRequestData = [
'amount' => [
'currency' => $this->dataHelper->getOrderCurrency($order),
'value' => $this->dataHelper->formatCurrencyValue(
$order->get_total(),
$this->dataHelper->getOrderCurrency($order)
),
],
'redirectUrl' => $returnUrl,
'webhookUrl' => $webhookUrl,
'method' => $methodId,
'payment' => [
'issuer' => $selectedIssuer,
],
'locale' => $paymentLocale,
'billingAddress' => $billingAddress,
'metadata' => apply_filters(
$this->pluginId . '_payment_object_metadata',
[
'order_id' => $order->get_id(),
'order_number' => $order->get_order_number(),
]
),
'lines' => $orderLines['lines'],
'orderNumber' => $order->get_order_number(),
];

$paymentRequestData = $this->addSequenceTypeForSubscriptionsFirstPayments($order->get_id(), $gateway, $paymentRequestData);

// Only add shippingAddress if all required fields are set
if (
!empty($shippingAddress->streetAndNumber)
&& !empty($shippingAddress->postalCode)
&& !empty($shippingAddress->city)
&& !empty($shippingAddress->country)
) {
$paymentRequestData['shippingAddress'] = $shippingAddress;
}

// Only store customer at Mollie if setting is enabled
if ($storeCustomer) {
$paymentRequestData['payment']['customerId'] = $customerId;
}

$cardToken = mollieWooCommerceCardToken();
if ($cardToken && isset($paymentRequestData['payment'])) {
$paymentRequestData['payment']['cardToken'] = $cardToken;
}
//phpcs:ignore WordPress.Security.NonceVerification, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$applePayToken = wc_clean(wp_unslash($_POST["token"] ?? ''));
if ($applePayToken && isset($paymentRequestData['payment'])) {
$encodedApplePayToken = wp_json_encode($applePayToken);
$paymentRequestData['payment']['applePayPaymentToken'] = $encodedApplePayToken;
}
$customerBirthdate = $this->getCustomerBirthdate($order);
if ($customerBirthdate) {
$paymentRequestData['consumerDateOfBirth'] = $customerBirthdate;
}
return $paymentRequestData;
return $this->requestFactory->createRequest('order', $order, $customerId);
}


public function setActiveMolliePayment($orderId)
{
self::$paymentId = $this->getMolliePaymentIdFromPaymentObject();
Expand Down Expand Up @@ -248,12 +163,6 @@ public function getMollieCustomerIbanDetailsFromPaymentObject($payment = null)
return $ibanDetails;
}

public function addSequenceTypeFirst($paymentRequestData)
{
$paymentRequestData['payment']['sequenceType'] = 'first';
return $paymentRequestData;
}

/**
* @param WC_Order $order
* @param Order $payment
Expand Down Expand Up @@ -1005,31 +914,4 @@ protected function processOrderItemsRefund(
// drop item from array
unset($items[$item->get_id()]);
}

protected function getCustomerBirthdate($order)
{
$gateway = wc_get_payment_gateway_by_order($order);
if (!$gateway || !isset($gateway->id)) {
return null;
}
if (strpos($gateway->id, 'mollie_wc_gateway_') === false) {
return null;
}
$additionalFields = $this->paymentMethod->getProperty('additionalFields');
$methodId = $additionalFields && in_array('birthdate', $additionalFields, true);
if ($methodId) {
$optionName = 'billing_birthdate_' . $this->paymentMethod->getProperty('id');
//phpcs:ignore WordPress.Security.NonceVerification, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$fieldPosted = wc_clean(wp_unslash($_POST[$optionName] ?? ''));
if ($fieldPosted === '' || !is_string($fieldPosted)) {
return null;
}

$order->update_meta_data($optionName, $fieldPosted);
$order->save();
$format = "Y-m-d";
return gmdate($format, (int) strtotime($fieldPosted));
}
return null;
}
}
70 changes: 1 addition & 69 deletions src/Payment/MolliePayment.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,76 +67,8 @@ public function getPaymentObject($paymentId, $testMode = false, $useCache = true
*/
public function getPaymentRequestData($order, $customerId, $voucherDefaultCategory = Voucher::NO_CATEGORY)
{
$settingsHelper = $this->settingsHelper;
$optionName = $this->pluginId . '_' . 'api_payment_description';
$option = get_option($optionName);
$paymentDescription = $this->getPaymentDescription($order, $option);
$paymentLocale = $settingsHelper->getPaymentLocale();
$storeCustomer = $settingsHelper->shouldStoreCustomer();

$gateway = wc_get_payment_gateway_by_order($order);

if (!$gateway || !($gateway instanceof PaymentGateway)) {
return ['result' => 'failure'];
}

$gatewayId = $gateway->id;
$selectedIssuer = $this->getSelectedIssuer($gatewayId);
$returnUrl = $gateway->get_return_url($order);
$returnUrl = $this->getReturnUrl($order, $returnUrl);
$webhookUrl = $this->getWebhookUrl($order, $gatewayId);
$orderId = $order->get_id();

$paymentRequestData = [
'amount' => [
'currency' => $this->dataHelper
->getOrderCurrency($order),
'value' => $this->dataHelper
->formatCurrencyValue(
$order->get_total(),
$this->dataHelper->getOrderCurrency(
$order
)
),
],
'description' => $paymentDescription,
'redirectUrl' => $returnUrl,
'webhookUrl' => $webhookUrl,
'method' => $this->paymentMethod->getProperty('id'),
'issuer' => $selectedIssuer,
'locale' => $paymentLocale,
'metadata' => apply_filters(
$this->pluginId . '_payment_object_metadata',
[
'order_id' => $order->get_id(),
]
),
];

$paymentRequestData = $this->addSequenceTypeForSubscriptionsFirstPayments($order->get_id(), $gateway, $paymentRequestData);

if ($storeCustomer) {
$paymentRequestData['customerId'] = $customerId;
}

$cardToken = mollieWooCommerceCardToken();
if ($cardToken) {
$paymentRequestData['cardToken'] = $cardToken;
}
//phpcs:ignore WordPress.Security.NonceVerification, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$applePayToken = wc_clean(wp_unslash($_POST["token"] ?? ''));
if ($applePayToken) {
$encodedApplePayToken = wp_json_encode($applePayToken);
$paymentRequestData['applePayPaymentToken'] = $encodedApplePayToken;
}
$paymentRequestData = $this->addCustomRequestFields($order, $paymentRequestData);
return $paymentRequestData;
}
return $this->requestFactory->createRequest('payment', $order, $customerId);

public function addSequenceTypeFirst($paymentRequestData)
{
$paymentRequestData['sequenceType'] = 'first';
return $paymentRequestData;
}

/**
Expand Down
42 changes: 8 additions & 34 deletions src/Payment/PaymentModule.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,40 +50,14 @@ class PaymentModule implements ServiceModule, ExecutableModule

public function services(): array
{
return [
OrderLines::class => static function (ContainerInterface $container): OrderLines {
$data = $container->get('settings.data_helper');
$pluginId = $container->get('shared.plugin_id');
return new OrderLines($data, $pluginId);
},
PaymentFactory::class => static function (ContainerInterface $container): PaymentFactory {
$settingsHelper = $container->get('settings.settings_helper');
assert($settingsHelper instanceof Settings);
$apiHelper = $container->get('SDK.api_helper');
assert($apiHelper instanceof Api);
$data = $container->get('settings.data_helper');
assert($data instanceof Data);
$pluginId = $container->get('shared.plugin_id');
$logger = $container->get(Logger::class);
assert($logger instanceof Logger);
$orderLines = $container->get(OrderLines::class);
return new PaymentFactory($data, $apiHelper, $settingsHelper, $pluginId, $logger, $orderLines);
},
MollieObject::class => static function (ContainerInterface $container): MollieObject {
$logger = $container->get(Logger::class);
assert($logger instanceof Logger);
$data = $container->get('settings.data_helper');
assert($data instanceof Data);
$apiHelper = $container->get('SDK.api_helper');
assert($apiHelper instanceof Api);
$pluginId = $container->get('shared.plugin_id');
$paymentFactory = $container->get(PaymentFactory::class);
assert($paymentFactory instanceof PaymentFactory);
$settingsHelper = $container->get('settings.settings_helper');
assert($settingsHelper instanceof Settings);
return new MollieObject($data, $logger, $paymentFactory, $apiHelper, $settingsHelper, $pluginId);
},
];
static $services;

if ($services === null) {

$services = require_once __DIR__ . '/inc/services.php';
}

return $services();
}

public function run(ContainerInterface $container): bool
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

declare(strict_types=1);

namespace Mollie\WooCommerce\Payment\Decorator;

use Mollie\WooCommerce\Payment\Request\Decorators\RequestDecoratorInterface;
use Mollie\WooCommerce\Shared\Data;
use WC_Order;

class AddSequenceTypeForSubscriptionsDecorator implements RequestDecoratorInterface
{
private Data $dataHelper;
private String $pluginId;

public function __construct($dataHelper, $pluginId)
{
$this->dataHelper = $dataHelper;
$this->pluginId = $pluginId;
}

public function decorate(array $requestData, WC_Order $order, $context): array
{
$gateway = wc_get_payment_gateway_by_order($order);
if ($gateway) {
$requestData = $this->addSequenceTypeForSubscriptionsFirstPayments($order->get_id(), $gateway, $requestData, $context);
}
return $requestData;
}

private function addSequenceTypeForSubscriptionsFirstPayments($orderId, $gateway, $requestData, $context): array
{
if ($this->dataHelper->isSubscription($orderId) || $this->dataHelper->isWcSubscription($orderId)) {
$disable_automatic_payments = apply_filters($this->pluginId . '_is_automatic_payment_disabled', false);
$supports_subscriptions = $gateway->supports('subscriptions');

if ($supports_subscriptions == true && $disable_automatic_payments == false) {
$requestData = $this->addSequenceTypeFirst($requestData, $context);
}
}
return $requestData;
}

private function addSequenceTypeFirst($requestData, $context)
{
if($context === 'order') {
$requestData['payment']['sequenceType'] = 'first';
} elseif ($context === 'payment') {
$requestData['sequenceType'] = 'first';
}
return $requestData;
}
}
Loading

0 comments on commit 6960bdf

Please sign in to comment.