Skip already handled refunds in webhook

When we add a refund from WC, we still receive a webhook with it. And for some partial refunds the duplicated refund can be added in WC.
This commit is contained in:
Alex P 2022-04-28 16:20:05 +03:00
parent 13e04b009c
commit 35f058870a
5 changed files with 74 additions and 10 deletions

View file

@ -39,6 +39,7 @@ class PayPalGateway extends \WC_Payment_Gateway {
const ORDER_PAYMENT_MODE_META_KEY = '_ppcp_paypal_payment_mode';
const ORDER_PAYMENT_SOURCE_META_KEY = '_ppcp_paypal_payment_source';
const FEES_META_KEY = '_ppcp_paypal_fees';
const REFUNDS_META_KEY = '_ppcp_refunds';
/**
* The Settings Renderer.

View file

@ -0,0 +1,47 @@
<?php
/**
* Operations with refund metadata.
*
* @package WooCommerce\PayPalCommerce\WcGateway\Processor
*/
declare(strict_types=1);
namespace WooCommerce\PayPalCommerce\WcGateway\Processor;
use WC_Order;
use WooCommerce\PayPalCommerce\WcGateway\Gateway\PayPalGateway;
/**
* Trait RefundMetaTrait.
*/
trait RefundMetaTrait {
/**
* Adds a refund ID to the order metadata.
*
* @param WC_Order $wc_order The WC order to which metadata will be added.
* @param string $refund_id The refund ID to be added.
*/
protected function add_refund_to_meta( WC_Order $wc_order, string $refund_id ): void {
$refunds = $this->get_refunds_meta( $wc_order );
$refunds[] = $refund_id;
$wc_order->update_meta_data( PayPalGateway::REFUNDS_META_KEY, $refunds );
$wc_order->save();
}
/**
* Returns refund IDs from the order metadata.
*
* @param WC_Order $wc_order The WC order.
*
* @return string[]
*/
protected function get_refunds_meta( WC_Order $wc_order ): array {
$refunds = $wc_order->get_meta( PayPalGateway::REFUNDS_META_KEY );
if ( ! is_array( $refunds ) ) {
$refunds = array();
}
return $refunds;
}
}

View file

@ -26,6 +26,7 @@ use WooCommerce\PayPalCommerce\WcGateway\Gateway\PayPalGateway;
* Class RefundProcessor
*/
class RefundProcessor {
use RefundMetaTrait;
private const REFUND_MODE_REFUND = 'refund';
private const REFUND_MODE_VOID = 'void';
@ -113,8 +114,8 @@ class RefundProcessor {
throw new RuntimeException( 'No capture.' );
}
$capture = $captures[0];
$refund = new Refund(
$capture = $captures[0];
$refund = new Refund(
$capture,
$capture->invoice_id(),
$reason,
@ -122,7 +123,10 @@ class RefundProcessor {
new Money( $amount, $wc_order->get_currency() )
)
);
$this->payments_endpoint->refund( $refund );
$refund_id = $this->payments_endpoint->refund( $refund );
$this->add_refund_to_meta( $wc_order, $refund_id );
break;
case self::REFUND_MODE_VOID:
$voidable_authorizations = array_filter(