Add PayPal token deletion to WC payment method delete action

This commit is contained in:
emilicastells 2022-11-24 11:26:06 +01:00
parent 9a0e25520c
commit 34798848bc
No known key found for this signature in database
GPG key ID: 1520C07081754570
2 changed files with 57 additions and 2 deletions

View file

@ -208,6 +208,32 @@ class PaymentTokenEndpoint {
return wp_remote_retrieve_response_code( $response ) === 204;
}
public function delete_token_by_id(string $token_id): bool {
$bearer = $this->bearer->bearer();
$url = trailingslashit( $this->host ) . 'v2/vault/payment-tokens/' . $token_id;
$args = array(
'method' => 'DELETE',
'headers' => array(
'Authorization' => 'Bearer ' . $bearer->token(),
'Content-Type' => 'application/json',
),
);
$response = $this->request( $url, $args );
if ( is_wp_error( $response ) ) {
$error = new RuntimeException(
__( 'Could not delete payment token.', 'woocommerce-paypal-payments' )
);
$this->logger->warning($error->getMessage());
throw $error;
}
return wp_remote_retrieve_response_code( $response ) === 204;
}
/**
* Starts the process of PayPal account vaulting (without payment), returns the links for further actions.
*

View file

@ -9,6 +9,7 @@ declare(strict_types=1);
namespace WooCommerce\PayPalCommerce\Vaulting;
use RuntimeException;
use WC_Payment_Tokens;
use WooCommerce\PayPalCommerce\Vendor\Dhii\Container\ServiceProvider;
use WooCommerce\PayPalCommerce\Vendor\Dhii\Modular\Module\ModuleInterface;
@ -19,8 +20,6 @@ use WC_Order;
use WooCommerce\PayPalCommerce\Subscription\Helper\SubscriptionHelper;
use WooCommerce\PayPalCommerce\Vaulting\Endpoint\DeletePaymentTokenEndpoint;
use WooCommerce\PayPalCommerce\WcGateway\Exception\NotFoundException;
use WooCommerce\PayPalCommerce\WcGateway\Settings\Settings;
use function Sodium\add;
/**
* Class StatusReportModule
@ -175,6 +174,36 @@ class VaultingModule implements ModuleInterface {
return $item;
}, 10, 2 );
add_action('wp', function() use ( $container ) {
global $wp;
if ( isset( $wp->query_vars['delete-payment-method'] ) ) {
$token_id = absint( $wp->query_vars['delete-payment-method'] );
$token = WC_Payment_Tokens::get( $token_id );
if(is_null( $token ) || $token->get_type() !== 'PayPal') {
return;
}
if(
$token->get_user_id() !== get_current_user_id()
|| ! isset( $_REQUEST['_wpnonce'] ) || false === wp_verify_nonce( wp_unslash( $_REQUEST['_wpnonce'] ), 'delete-payment-method-' . $token_id )
) {
wc_add_notice( __( 'Invalid payment method.', 'woocommerce' ), 'error' );
wp_safe_redirect( wc_get_account_endpoint_url( 'payment-methods' ) );
exit();
}
try {
$payment_token_endpoint = $container->get('api.endpoint.payment-token');
$payment_token_endpoint->delete_token_by_id($token->get_token());
} catch (RuntimeException $exception) {
wc_add_notice( __( 'Could not delete payment token. ' . $exception->getMessage(), 'woocommerce-paypal-payments' ), 'error' );
return;
}
}
});
}
/**