woocommerce-paypal-payments/modules.local/ppcp-webhooks/src/Handler/PaymentCaptureRefunded.php

104 lines
3.3 KiB
PHP
Raw Normal View History

2020-07-09 10:25:46 +03:00
<?php
declare(strict_types=1);
namespace Inpsyde\PayPalCommerce\Webhooks\Handler;
use Psr\Log\LoggerInterface;
class PaymentCaptureRefunded implements RequestHandler
{
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
2020-07-10 13:21:43 +03:00
public function eventTypes(): array
2020-07-09 10:25:46 +03:00
{
2020-07-10 13:21:43 +03:00
return ['PAYMENT.CAPTURE.REFUNDED'];
2020-07-09 10:25:46 +03:00
}
public function responsibleForRequest(\WP_REST_Request $request): bool
{
2020-07-10 13:21:43 +03:00
return in_array($request['event_type'], $this->eventTypes(), true);
2020-07-09 10:25:46 +03:00
}
public function handleRequest(\WP_REST_Request $request): \WP_REST_Response
{
$response = ['success' => false];
$orderId = isset($request['resource']['custom_id']) ? (int) $request['resource']['custom_id'] : 0;
2020-07-09 10:25:46 +03:00
if (! $orderId) {
$message = sprintf(
// translators: %s is the PayPal webhook Id.
__('No order for webhook event %s was found.', 'woocommerce-paypal-commerce-gateway'),
isset($request['id']) ? $request['id'] : ''
);
$this->logger->log(
'warning',
$message,
[
'request' => $request,
]
);
$response['message'] = $message;
return rest_ensure_response($response);
}
2020-07-09 12:05:57 +03:00
$wcOrder = wc_get_order($orderId);
if (! is_a($wcOrder, \WC_Order::class)) {
2020-07-09 10:25:46 +03:00
$message = sprintf(
// translators: %s is the PayPal refund Id.
__('Order for PayPal refund %s not found.', 'woocommerce-paypal-commerce-gateway'),
isset($request['resource']['id']) ? $request['resource']['id'] : ''
);
$this->logger->log(
'warning',
$message,
[
'request' => $request,
]
);
$response['message'] = $message;
return rest_ensure_response($response);
}
2020-07-09 12:05:57 +03:00
/**
* @var \WC_Order $wcOrder
*/
$refund = wc_create_refund([
'order_id' => $wcOrder->get_id(),
'amount' => $request['resource']['amount']['value']
]);
if (is_wp_error($refund)) {
$this->logger->log(
'warning',
2020-07-10 08:51:02 +03:00
__('Order ' . $wcOrder->get_id() . ' could not be refunded' , 'woocommerce-paypal-commerce-gateway'),
[
'request' => $request,
'error' => $refund,
]
);
$response['message'] = $refund->get_error_message();
return rest_ensure_response($response);
}
2020-07-09 12:05:57 +03:00
$this->logger->log(
'info',
sprintf(
//translators: %1$s is the order id %2$s is the amount which has been refunded.
2020-07-10 08:51:02 +03:00
__('Order %1$s has been refunded with %2$s through PayPal' , 'woocommerce-paypal-commerce-gateway'),
(string) $wcOrder->get_id(),
(string) $refund->get_amount()
),
2020-07-09 12:05:57 +03:00
[
'request' => $request,
'order' => $wcOrder,
]
);
2020-07-09 10:25:46 +03:00
$response['success'] = true;
return rest_ensure_response($response);
}
}