* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * @copyright PayPal */ namespace PaypalAddons\services; use Exception; use PayPal\Api\WebhookEvent; use PaypalAddons\classes\AbstractMethodPaypal; use PaypalAddons\classes\Constants\WebHookType; use PaypalAddons\classes\Exception\RefundCalculationException; use PaypalOrder; use PaypalWebhook; use PrestaShopCollection; class PaymentRefundAmount { /** * @param PaypalOrder $paypalOrder * * @return float */ public function calculateTotalRefunded(PaypalOrder $paypalOrder) { $method = AbstractMethodPaypal::load($paypalOrder->method); $totalRefund = 0; try { $order = $method->getInfo($paypalOrder->id_payment); $payments = $order->getData()->result->purchase_units[0]->payments; if (isset($payments->refunds)) { foreach ($payments->refunds as $refund) { $totalRefund += $refund->amount->value; } } } catch (\Exception $e) { throw new RefundCalculationException($e->getMessage()); } return (float) $totalRefund; } /** * @param PaypalOrder $paypalOrder * * @return float */ public function calculateReceivedWebhookEvent(PaypalOrder $paypalOrder) { $webhookEvents = $this->getWebhookEvents($paypalOrder); $totalRefunded = 0; foreach ($webhookEvents as $webhookEvent) { $webhookEvent = (new WebhookEvent())->fromJson($webhookEvent->data); if ($webhookEvent->event_type != WebHookType::CAPTURE_REFUNDED) { continue; } try { $totalRefunded += $webhookEvent->resource->amount->value; } catch (Exception $e) { } } return (float) $totalRefunded; } /** * @param PaypalOrder $paypalOrder * * @return PaypalWebhook[] */ protected function getWebhookEvents(PaypalOrder $paypalOrder) { try { $collection = (new PrestaShopCollection(PaypalWebhook::class)) ->where('id_paypal_order', '=', (int) $paypalOrder->id); return $collection->getResults(); } catch (\Throwable $e) { return []; } } }