Skip to content

Saleor Core: the high performance, composable, headless commerce API.

[Programmatic payments] payment method delete api (#13660)

Maciej Korycinski38eeda3f7913
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a3565acbe5..2cebff552c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,10 +12,11 @@ in 3.17. Use `PaymentSettingsInput.defaultTransactionFlowStrategy` instead.
in 3.17. Use `PaymentSettings.defaultTransactionFlowStrategy` instead.
### GraphQL API
+- Add `storedPaymentMethodRequestDelete` mutation - #13660 by @korycins
- Add `PaymentSettings` to `Channel` - #13677 by @korycins
### Saleor Apps
-
+- Add `STORED_PAYMENT_METHOD_DELETE_REQUESTED` webhook event - #13660 by @korycins
- Add `NOTIFY_CUSTOMER` flag to `FulfillmentCreated` type - #13620, by @Air-t
- Inform apps if customer should be notified when fulfillment is created.
diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.py
index c851e82829..5382170dc0 100644
--- a/saleor/graphql/core/enums.py
+++ b/saleor/graphql/core/enums.py
@@ -295,6 +295,10 @@ PaymentGatewayInitializeErrorCode = graphene.Enum.from_enum(
)
PaymentGatewayInitializeErrorCode.doc_category = DOC_CATEGORY_PAYMENTS
+StoredPaymentMethodRequestDeleteErrorCode = graphene.Enum.from_enum(
+ payment_error_codes.StoredPaymentMethodRequestDeleteErrorCode
+)
+StoredPaymentMethodRequestDeleteErrorCode.doc_category = DOC_CATEGORY_PAYMENTS
PermissionGroupErrorCode = graphene.Enum.from_enum(
account_error_codes.PermissionGroupErrorCode
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index 784923a2af..22abd30f0f 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -76,6 +76,7 @@ from ..enums import (
ShopErrorCode,
StockBulkUpdateErrorCode,
StockErrorCode,
+ StoredPaymentMethodRequestDeleteErrorCode,
ThumbnailFormatEnum,
TimePeriodTypeEnum,
TransactionCreateErrorCode,
@@ -680,6 +681,15 @@ class PaymentGatewayInitializeError(Error):
doc_category = DOC_CATEGORY_PAYMENTS
+class PaymentMethodRequestDeleteError(Error):
+ code = StoredPaymentMethodRequestDeleteErrorCode(
+ description="The error code.", required=True
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_PAYMENTS
+
+
class GiftCardError(Error):
code = GiftCardErrorCode(description="The error code.", required=True)
tags = NonNullList(
diff --git a/saleor/graphql/payment/mutations/__init__.py b/saleor/graphql/payment/mutations/__init__.py
index a35af7ad13..65a59c1c5e 100644
--- a/saleor/graphql/payment/mutations/__init__.py
+++ b/saleor/graphql/payment/mutations/__init__.py
@@ -2,12 +2,13 @@ from .payment import (
CheckoutPaymentCreate,
PaymentCapture,
PaymentCheckBalance,
- PaymentGatewayInitialize,
PaymentInitialize,
PaymentRefund,
PaymentVoid,
)
+from .stored_payment_methods import StoredPaymentMethodRequestDelete
from .transaction import (
+ PaymentGatewayInitialize,
TransactionCreate,
TransactionEventReport,
TransactionInitialize,
@@ -25,6 +26,7 @@ __all__ = [
"PaymentInitialize",
"PaymentRefund",
"PaymentVoid",
+ "StoredPaymentMethodRequestDelete",
"TransactionCreate",
"TransactionEventReport",
"TransactionInitialize",
diff --git a/saleor/graphql/payment/mutations/payment/__init__.py b/saleor/graphql/payment/mutations/payment/__init__.py
index e1b6d77205..34b718d884 100644
--- a/saleor/graphql/payment/mutations/payment/__init__.py
+++ b/saleor/graphql/payment/mutations/payment/__init__.py
@@ -1,7 +1,6 @@
from .checkout_payment_create import CheckoutPaymentCreate
from .payment_capture import PaymentCapture
from .payment_check_balance import PaymentCheckBalance
-from .payment_gateway_initialize import PaymentGatewayInitialize
from .payment_initialize import PaymentInitialize
from .payment_refund import PaymentRefund
from .payment_void import PaymentVoid
@@ -10,7 +9,6 @@ __all__ = [
"CheckoutPaymentCreate",
"PaymentCapture",
"PaymentCheckBalance",
- "PaymentGatewayInitialize",
"PaymentInitialize",
"PaymentRefund",
"PaymentVoid",
diff --git a/saleor/graphql/payment/mutations/stored_payment_methods/__init__.py b/saleor/graphql/payment/mutations/stored_payment_methods/__init__.py
new file mode 100644
index 0000000000..6b19321604
--- /dev/null
+++ b/saleor/graphql/payment/mutations/stored_payment_methods/__init__.py
@@ -0,0 +1,5 @@
+from .payment_method_request_delete import StoredPaymentMethodRequestDelete
+
+__all__ = [
+ "StoredPaymentMethodRequestDelete",
+]
diff --git a/saleor/graphql/payment/mutations/stored_payment_methods/payment_method_request_delete.py b/saleor/graphql/payment/mutations/stored_payment_methods/payment_method_request_delete.py
new file mode 100644
index 0000000000..5bd0b7a55a
--- /dev/null
+++ b/saleor/graphql/payment/mutations/stored_payment_methods/payment_method_request_delete.py
@@ -0,0 +1,78 @@
+import graphene
+from django.core.exceptions import ValidationError
+
+from .....payment.interface import StoredPaymentMethodRequestDeleteData
+from .....permission.auth_filters import AuthorizationFilters
+from .....webhook.event_types import WebhookEventSyncType
+from ....channel.utils import validate_channel
+from ....core.descriptions import ADDED_IN_316, PREVIEW_FEATURE
+from ....core.doc_category import DOC_CATEGORY_PAYMENTS
+from ....core.enums import StoredPaymentMethodRequestDeleteErrorCode
+from ....core.mutations import BaseMutation
+from ....core.types.common import PaymentMethodRequestDeleteError
+from ....core.utils import WebhookEventInfo
+from ....plugins.dataloaders import get_plugin_manager_promise
+
+
+class StoredPaymentMethodRequestDelete(BaseMutation):
+ success = graphene.Boolean(
+ description="True, if the delete request was processed successfully.",
+ )
+ message = graphene.String(
+ description="A message returned by payment app.",
+ )
+
+ class Arguments:
+ id = graphene.ID(
+ description="The ID of the payment method.",
+ required=True,
+ )
+ channel = graphene.String(
+ description="Slug of a channel related to delete request.", required=True
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_PAYMENTS
+ description = (
+ "Request to delete a stored payment method on payment provider side."
+ + ADDED_IN_316
+ + PREVIEW_FEATURE
+ )
+
+ error_type_class = PaymentMethodRequestDeleteError
+ permissions = (AuthorizationFilters.AUTHENTICATED_USER,)
+ webhook_events_info = [
+ WebhookEventInfo(
+ type=WebhookEventSyncType.STORED_PAYMENT_METHOD_DELETE_REQUESTED,
+ description="The customer requested to delete a payment method.",
+ ),
+ ]
+
+ @classmethod
+ def perform_mutation(cls, root, info, id, channel):
+ user = info.context.user
+ if not user:
+ raise ValidationError(
+ "You need to be authenticated user to delete a payment method.",
+ code=StoredPaymentMethodRequestDeleteErrorCode.INVALID.value,
+ )
+ channel = validate_channel(channel, StoredPaymentMethodRequestDeleteErrorCode)
+
+ manager = get_plugin_manager_promise(info.context).get()
+ is_active = manager.is_event_active_for_any_plugin(
+ "stored_payment_method_request_delete"
+ )
+ if not is_active:
+ raise ValidationError(
+ "No active payment app that could process the delete request.",
+ code=StoredPaymentMethodRequestDeleteErrorCode.NOT_FOUND.value,
+ )
+
+ response = manager.stored_payment_method_request_delete(
+ request_delete_data=StoredPaymentMethodRequestDeleteData(
+ payment_method_id=id,
+ user=user,
+ channel=channel,
+ )
+ )
+ return cls(success=response.success, message=response.message)
diff --git a/saleor/graphql/payment/mutations/transaction/__init__.py b/saleor/graphql/payment/mutations/transaction/__init__.py
index 25469b1a08..847ffa713c 100644
--- a/saleor/graphql/payment/mutations/transaction/__init__.py
+++ b/saleor/graphql/payment/mutations/transaction/__init__.py
@@ -1,3 +1,4 @@
+from .payment_gateway_initialize import PaymentGatewayInitialize
from .transaction_create import TransactionCreate
from .transaction_event_report import TransactionEventReport
from .transaction_initialize import TransactionInitialize
@@ -9,6 +10,7 @@ from .transaction_request_refund_for_granted_refund import (
from .transaction_update import TransactionUpdate
__all__ = [
+ "PaymentGatewayInitialize",
"TransactionCreate",
"TransactionEventReport",
"TransactionInitialize",
diff --git a/saleor/graphql/payment/mutations/payment/payment_gateway_initialize.py b/saleor/graphql/payment/mutations/transaction/payment_gateway_initialize.py
similarity index 100%
rename from saleor/graphql/payment/mutations/payment/payment_gateway_initialize.py
rename to saleor/graphql/payment/mutations/transaction/payment_gateway_initialize.py
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_initialize.py b/saleor/graphql/payment/mutations/transaction/transaction_initialize.py
index 0c94ba1f07..d0fcc5ac00 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_initialize.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_initialize.py
@@ -19,7 +19,7 @@ from ....core.types import common as common_types
from ....plugins.dataloaders import get_plugin_manager_promise
from ...types import TransactionEvent, TransactionItem
from ..base import TransactionSessionBase
-from ..payment.payment_gateway_initialize import PaymentGatewayToInitialize
+from .payment_gateway_initialize import PaymentGatewayToInitialize
class TransactionInitialize(TransactionSessionBase):
diff --git a/saleor/graphql/payment/schema.py b/saleor/graphql/payment/schema.py
index 25f9b0fc31..a939be81e5 100644
--- a/saleor/graphql/payment/schema.py
+++ b/saleor/graphql/payment/schema.py
@@ -15,6 +15,7 @@ from .mutations import (
PaymentInitialize,
PaymentRefund,
PaymentVoid,
+ StoredPaymentMethodRequestDelete,
TransactionCreate,
TransactionEventReport,
TransactionInitialize,
@@ -97,3 +98,5 @@ class PaymentMutations(graphene.ObjectType):
payment_gateway_initialize = PaymentGatewayInitialize.Field()
transaction_initialize = TransactionInitialize.Field()
transaction_process = TransactionProcess.Field()
+
+ stored_payment_method_request_delete = StoredPaymentMethodRequestDelete.Field()
diff --git a/saleor/graphql/payment/tests/mutations/test_stored_payment_method_request_delete.py b/saleor/graphql/payment/tests/mutations/test_stored_payment_method_request_delete.py
new file mode 100644
index 0000000000..4a9a19e79e
--- /dev/null
+++ b/saleor/graphql/payment/tests/mutations/test_stored_payment_method_request_delete.py
@@ -0,0 +1,197 @@
+from unittest.mock import patch
+
+from .....payment.interface import (
+ StoredPaymentMethodRequestDeleteData,
+ StoredPaymentMethodRequestDeleteResponseData,
+)
+from .....plugins.manager import PluginsManager
+from ....core.enums import StoredPaymentMethodRequestDeleteErrorCode
+from ....tests.utils import assert_no_permission, get_graphql_content
+
+STORED_PAYMENT_METHOD_REQUEST_DELETE_MUTATION = """
+mutation storedPaymentMethodRequestDelete($id: ID!, $channel: String!){
+ storedPaymentMethodRequestDelete(id: $id, channel: $channel){
+ success
+ message
+ errors{
+ field
+ code
+ }
+ }
+}
+"""
+
+
[email protected](PluginsManager, "stored_payment_method_request_delete")
[email protected](PluginsManager, "is_event_active_for_any_plugin")
+def test_stored_payment_method_request_delete(
+ mocked_is_event_active_for_any_plugin,
+ mocked_stored_payment_method_request_delete,
+ user_api_client,
+ channel_USD,
+):
+ # given
+ mocked_is_event_active_for_any_plugin.return_value = True
+ mocked_stored_payment_method_request_delete.return_value = (
+ StoredPaymentMethodRequestDeleteResponseData(
+ success=True,
+ message=None,
+ )
+ )
+ expected_id = "test_id"
+
+ # when
+ response = user_api_client.post_graphql(
+ STORED_PAYMENT_METHOD_REQUEST_DELETE_MUTATION,
+ variables={"id": expected_id, "channel": channel_USD.slug},
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["storedPaymentMethodRequestDelete"]["success"] is True
+
+ mocked_is_event_active_for_any_plugin.assert_called_once_with(
+ "stored_payment_method_request_delete"
+ )
+ mocked_stored_payment_method_request_delete.assert_called_once_with(
+ request_delete_data=StoredPaymentMethodRequestDeleteData(
+ payment_method_id=expected_id,
+ user=user_api_client.user,
+ channel=channel_USD,
+ )
+ )
+
+
[email protected](PluginsManager, "stored_payment_method_request_delete")
[email protected](PluginsManager, "is_event_active_for_any_plugin")
+def test_stored_payment_method_request_delete_called_by_app(
+ mocked_is_event_active_for_any_plugin,
+ mocked_stored_payment_method_request_delete,
+ app_api_client,
+ channel_USD,
+):
+ # given
+ mocked_is_event_active_for_any_plugin.return_value = True
+ mocked_stored_payment_method_request_delete.return_value = (
+ StoredPaymentMethodRequestDeleteResponseData(
+ success=True,
+ message="Payment method delete request was processed successfully.",
+ )
+ )
+ expected_id = "test_id"
+
+ # when
+ response = app_api_client.post_graphql(
+ STORED_PAYMENT_METHOD_REQUEST_DELETE_MUTATION,
+ variables={"id": expected_id, "channel": channel_USD.slug},
+ )
+
+ # then
+ assert_no_permission(response)
+
+ assert not mocked_is_event_active_for_any_plugin.called
+ assert not mocked_stored_payment_method_request_delete.called
+
+
[email protected](PluginsManager, "stored_payment_method_request_delete")
[email protected](PluginsManager, "is_event_active_for_any_plugin")
+def test_stored_payment_method_request_delete_called_by_anynoums_user(
+ mocked_is_event_active_for_any_plugin,
+ mocked_stored_payment_method_request_delete,
+ api_client,
+ channel_USD,
+):
+ # given
+ mocked_is_event_active_for_any_plugin.return_value = True
+ mocked_stored_payment_method_request_delete.return_value = (
+ StoredPaymentMethodRequestDeleteResponseData(
+ success=True,
+ message="Payment method delete request was processed successfully.",
+ )
+ )
+ expected_id = "test_id"
+
+ # when
+ response = api_client.post_graphql(
+ STORED_PAYMENT_METHOD_REQUEST_DELETE_MUTATION,
+ variables={"id": expected_id, "channel": channel_USD.slug},
+ )
+
+ # then
+ assert_no_permission(response)
+
+ assert not mocked_is_event_active_for_any_plugin.called
+ assert not mocked_stored_payment_method_request_delete.called
+
+
[email protected](PluginsManager, "stored_payment_method_request_delete")
[email protected](PluginsManager, "is_event_active_for_any_plugin")
+def test_stored_payment_method_request_delete_not_app_or_plugin_subscribed_to_event(
+ mocked_is_event_active_for_any_plugin,
+ mocked_stored_payment_method_request_delete,
+ user_api_client,
+ channel_USD,
+):
+ # given
+ mocked_is_event_active_for_any_plugin.return_value = False
+ mocked_stored_payment_method_request_delete.return_value = (
+ StoredPaymentMethodRequestDeleteResponseData(
+ success=True,
+ message=None,
+ )
+ )
+ expected_id = "test_id"
+
+ # when
+ response = user_api_client.post_graphql(
+ STORED_PAYMENT_METHOD_REQUEST_DELETE_MUTATION,
+ variables={"id": expected_id, "channel": channel_USD.slug},
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert len(content["data"]["storedPaymentMethodRequestDelete"]["errors"]) == 1
+ assert (
+ content["data"]["storedPaymentMethodRequestDelete"]["errors"][0]["code"]
+ == StoredPaymentMethodRequestDeleteErrorCode.NOT_FOUND.name
+ )
+
+ mocked_is_event_active_for_any_plugin.assert_called_once_with(
+ "stored_payment_method_request_delete"
+ )
+ assert not mocked_stored_payment_method_request_delete.called
+
+
[email protected](PluginsManager, "stored_payment_method_request_delete")
[email protected](PluginsManager, "is_event_active_for_any_plugin")
+def test_stored_payment_method_request_delete_incorrect_channel(
+ mocked_is_event_active_for_any_plugin,
+ mocked_stored_payment_method_request_delete,
+ user_api_client,
+):
+ # given
+ mocked_is_event_active_for_any_plugin.return_value = False
+ mocked_stored_payment_method_request_delete.return_value = (
+ StoredPaymentMethodRequestDeleteResponseData(
+ success=True,
+ message=None,
+ )
+ )
+ expected_id = "test_id"
+
+ # when
+ response = user_api_client.post_graphql(
+ STORED_PAYMENT_METHOD_REQUEST_DELETE_MUTATION,
+ variables={"id": expected_id, "channel": "non-exiting-channel"},
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert len(content["data"]["storedPaymentMethodRequestDelete"]["errors"]) == 1
+ assert (
+ content["data"]["storedPaymentMethodRequestDelete"]["errors"][0]["code"]
+ == StoredPaymentMethodRequestDeleteErrorCode.NOT_FOUND.name
+ )
+
+ assert not mocked_is_event_active_for_any_plugin.called
+ assert not mocked_stored_payment_method_request_delete.called
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index ea66941b3c..142c461b75 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -2276,6 +2276,7 @@ enum WebhookEventTypeEnum @doc(category: "Webhooks") {
TRANSACTION_INITIALIZE_SESSION
TRANSACTION_PROCESS_SESSION
LIST_STORED_PAYMENT_METHODS
+ STORED_PAYMENT_METHOD_DELETE_REQUESTED
}
"""Synchronous webhook event."""
@@ -2363,6 +2364,7 @@ enum WebhookEventTypeSyncEnum @doc(category: "Webhooks") {
TRANSACTION_INITIALIZE_SESSION
TRANSACTION_PROCESS_SESSION
LIST_STORED_PAYMENT_METHODS
+ STORED_PAYMENT_METHOD_DELETE_REQUESTED
}
"""Asynchronous webhook event."""
@@ -15590,6 +15592,26 @@ type Mutation {
id: ID!
): TransactionProcess @doc(category: "Payments")
+ """
+ Request to delete a stored payment method on payment provider side.
+
+ Added in Saleor 3.16.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+
+ Requires one of the following permissions: AUTHENTICATED_USER.
+
+ Triggers the following webhook events:
+ - STORED_PAYMENT_METHOD_DELETE_REQUESTED (sync): The customer requested to delete a payment method.
+ """
+ storedPaymentMethodRequestDelete(
+ """Slug of a channel related to delete request."""
+ channel: String!
+
+ """The ID of the payment method."""
+ id: ID!
+ ): StoredPaymentMethodRequestDelete @doc(category: "Payments") @webhookEventsInfo(asyncEvents: [], syncEvents: [STORED_PAYMENT_METHOD_DELETE_REQUESTED])
+
"""
Creates a new page.
@@ -23162,6 +23184,48 @@ enum TransactionProcessErrorCode @doc(category: "Payments") {
MISSING_PAYMENT_APP
}
+"""
+Request to delete a stored payment method on payment provider side.
+
+Added in Saleor 3.16.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+
+Requires one of the following permissions: AUTHENTICATED_USER.
+
+Triggers the following webhook events:
+- STORED_PAYMENT_METHOD_DELETE_REQUESTED (sync): The customer requested to delete a payment method.
+"""
+type StoredPaymentMethodRequestDelete @doc(category: "Payments") @webhookEventsInfo(asyncEvents: [], syncEvents: [STORED_PAYMENT_METHOD_DELETE_REQUESTED]) {
+ """True, if the delete request was processed successfully."""
+ success: Boolean
+
+ """A message returned by payment app."""
+ message: String
+ errors: [PaymentMethodRequestDeleteError!]!
+}
+
+type PaymentMethodRequestDeleteError @doc(category: "Payments") {
+ """
+ Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field.
+ """
+ field: String
+
+ """The error message."""
+ message: String
+
+ """The error code."""
+ code: StoredPaymentMethodRequestDeleteErrorCode!
+}
+
+"""An enumeration."""
+enum StoredPaymentMethodRequestDeleteErrorCode @doc(category: "Payments") {
+ GRAPHQL_ERROR
+ INVALID
+ NOT_FOUND
+ CHANNEL_INACTIVE
+}
+
"""
Creates a new page.
@@ -33122,6 +33186,40 @@ type ListStoredPaymentMethods implements Event @doc(category: "Payments") {
channel: Channel!
}
+"""
+Event sent when user requests to delete a payment method.
+
+Added in Saleor 3.16.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+type StoredPaymentMethodDeleteRequested implements Event @doc(category: "Payments") {
+ """Time of the event."""
+ issuedAt: DateTime
+
+ """Saleor version that triggered the event."""
+ version: String
+
+ """The user or application that triggered the event."""
+ issuingPrincipal: IssuingPrincipal
+
+ """The application receiving the webhook."""
+ recipient: App
+
+ """
+ The user for which the app should proceed with payment method delete request.
+ """
+ user: User!
+
+ """
+ The ID of the payment method that should be deleted by the payment gateway.
+ """
+ paymentMethodId: String!
+
+ """Channel related to the requested delete action."""
+ channel: Channel!
+}
+
"""_Any value scalar as defined by Federation spec."""
scalar _Any
diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.py
index c6bae03da0..e1412c9fe6 100644
--- a/saleor/graphql/webhook/subscription_types.py
+++ b/saleor/graphql/webhook/subscription_types.py
@@ -15,6 +15,7 @@ from ...order.utils import get_all_shipping_methods_for_order
from ...page.models import PageTranslation
from ...payment.interface import (
ListStoredPaymentMethodsRequestData,
+ StoredPaymentMethodRequestDeleteData,
TransactionActionData,
TransactionSessionData,
)
@@ -1886,6 +1887,63 @@ class TransactionItemMetadataUpdated(SubscriptionObjectType):
return transaction_item
+class StoredPaymentMethodDeleteRequested(SubscriptionObjectType):
+ user = graphene.Field(
+ UserType,
+ description=(
+ "The user for which the app should proceed with payment method delete "
+ "request."
+ ),
+ required=True,
+ )
+ payment_method_id = graphene.Field(
+ graphene.String,
+ description=(
+ "The ID of the payment method that should be deleted by the payment "
+ "gateway."
+ ),
+ required=True,
+ )
+
+ channel = graphene.Field(
+ "saleor.graphql.channel.types.Channel",
+ description="Channel related to the requested delete action.",
+ required=True,
+ )
+
+ class Meta:
+ root_type = None
+ enable_dry_run = False
+ interfaces = (Event,)
+ description = (
+ "Event sent when user requests to delete a payment method."
+ + ADDED_IN_316
+ + PREVIEW_FEATURE
+ )
+ doc_category = DOC_CATEGORY_PAYMENTS
+
+ @classmethod
+ def resolve_user(
+ cls, root: tuple[str, StoredPaymentMethodRequestDeleteData], _info: ResolveInfo
+ ):
+ _, payment_method_data = root
+ return payment_method_data.user
+
+ @classmethod
+ def resolve_payment_method_id(
+ cls, root: tuple[str, StoredPaymentMethodRequestDeleteData], _info: ResolveInfo
+ ):
+ _, payment_method_data = root
+ return payment_method_data.payment_method_id
+
+ @classmethod
+ def resolve_channel(
+ cls, root: tuple[str, StoredPaymentMethodRequestDeleteData], _info: ResolveInfo
+ ):
+ _, payment_method_data = root
+ return payment_method_data.channel
+
+
class TranslationTypes(Union):
class Meta:
types = tuple(TRANSLATIONS_TYPES_MAP.values())
@@ -2389,7 +2447,7 @@ WEBHOOK_TYPES_MAP = {
),
WebhookEventSyncType.TRANSACTION_CHARGE_REQUESTED: TransactionChargeRequested,
WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED: TransactionRefundRequested,
- WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS: (OrderFilterShippingMethods),
+ WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS: OrderFilterShippingMethods,
WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS: (
CheckoutFilterShippingMethods
),
@@ -2405,4 +2463,7 @@ WEBHOOK_TYPES_MAP = {
WebhookEventSyncType.TRANSACTION_PROCESS_SESSION: TransactionProcessSession,
WebhookEventAsyncType.SHOP_METADATA_UPDATED: ShopMetadataUpdated,
WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS: ListStoredPaymentMethods,
+ WebhookEventSyncType.STORED_PAYMENT_METHOD_DELETE_REQUESTED: (
+ StoredPaymentMethodDeleteRequested
+ ),
}
diff --git a/saleor/payment/error_codes.py b/saleor/payment/error_codes.py
index bcd2a04d5e..d219374bb5 100644
--- a/saleor/payment/error_codes.py
+++ b/saleor/payment/error_codes.py
@@ -90,3 +90,10 @@ class TransactionProcessErrorCode(Enum):
TRANSACTION_ALREADY_PROCESSED = "transaction_already_processed"
MISSING_PAYMENT_APP_RELATION = "missing_payment_app_relation"
MISSING_PAYMENT_APP = "missing_payment_app"
+
+
+class StoredPaymentMethodRequestDeleteErrorCode(Enum):
+ GRAPHQL_ERROR = "graphql_error"
+ INVALID = "invalid"
+ NOT_FOUND = "not_found"
+ CHANNEL_INACTIVE = "channel_inactive"
diff --git a/saleor/payment/interface.py b/saleor/payment/interface.py
index b4bf2db0d7..630c2d0f9b 100644
--- a/saleor/payment/interface.py
+++ b/saleor/payment/interface.py
@@ -20,6 +20,23 @@ JSONValue = Union[str, int, float, bool, None, Dict[str, Any], List[Any]]
JSONType = Union[Dict[str, JSONValue], List[JSONValue]]
+@dataclass
+class StoredPaymentMethodRequestDeleteResponseData:
+ """Dataclass for storing the response information from payment app."""
+
+ success: bool
+ message: Optional[str] = None
+
+
+@dataclass
+class StoredPaymentMethodRequestDeleteData:
+ """Dataclass for storing the request information for payment app."""
+
+ payment_method_id: str
+ user: "User"
+ channel: "Channel"
+
+
@dataclass
class PaymentGateway:
"""Dataclass for storing information about a payment gateway."""
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index f0b9d2096c..357d60d779 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -33,6 +33,8 @@ from ..payment.interface import (
PaymentData,
PaymentGateway,
PaymentMethodData,
+ StoredPaymentMethodRequestDeleteData,
+ StoredPaymentMethodRequestDeleteResponseData,
TransactionActionData,
TransactionSessionResult,
)
@@ -688,6 +690,14 @@ class BasePlugin:
list["PaymentMethodData"],
]
+ stored_payment_method_request_delete: Callable[
+ [
+ "StoredPaymentMethodRequestDeleteData",
+ "StoredPaymentMethodRequestDeleteResponseData",
+ ],
+ "StoredPaymentMethodRequestDeleteResponseData",
+ ]
+
# Trigger when menu is created.
#
# Overwrite this method if you need to trigger specific logic after a menu is
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 90b1544ebe..cd92e19aeb 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -32,6 +32,22 @@ from ..core.taxes import TaxData, TaxType, zero_money, zero_taxed_money
from ..graphql.core import ResolveInfo, SaleorContext
from ..order import base_calculations as base_order_calculations
from ..order.interface import OrderTaxedPricesData
+from ..payment.interface import (
+ CustomerSource,
+ GatewayResponse,
+ InitializedPaymentResponse,
+ ListStoredPaymentMethodsRequestData,
+ PaymentData,
+ PaymentGateway,
+ PaymentGatewayData,
+ PaymentMethodData,
+ StoredPaymentMethodRequestDeleteData,
+ StoredPaymentMethodRequestDeleteResponseData,
+ TokenConfig,
+ TransactionActionData,
+ TransactionSessionData,
+ TransactionSessionResult,
+)
from ..tax.utils import calculate_tax_rate
from .base_plugin import ExcludedShippingMethod, ExternalAccessTokens
from .models import PluginConfiguration
@@ -49,20 +65,6 @@ if TYPE_CHECKING:
from ..menu.models import Menu, MenuItem
from ..order.models import Fulfillment, Order, OrderLine
from ..page.models import Page, PageType
- from ..payment.interface import (
- CustomerSource,
- GatewayResponse,
- InitializedPaymentResponse,
- ListStoredPaymentMethodsRequestData,
- PaymentData,
- PaymentGateway,
- PaymentGatewayData,
- PaymentMethodData,
- TokenConfig,
- TransactionActionData,
- TransactionSessionData,
- TransactionSessionResult,
- )
from ..payment.models import TransactionItem
from ..product.models import (
Category,
@@ -1541,6 +1543,20 @@ class PluginsManager(PaymentInterface):
list_stored_payment_methods_data,
)
+ def stored_payment_method_request_delete(
+ self,
+ request_delete_data: "StoredPaymentMethodRequestDeleteData",
+ ) -> "StoredPaymentMethodRequestDeleteResponseData":
+ default_response = StoredPaymentMethodRequestDeleteResponseData(
+ success=False, message="Payment method request delete failed to deliver."
+ )
+ response = self.__run_method_on_plugins(
+ "stored_payment_method_request_delete",
+ default_response,
+ request_delete_data,
+ )
+ return response
+
def translation_created(self, translation: "Translation"):
default_value = None
return self.__run_method_on_plugins(
diff --git a/saleor/plugins/tests/sample_plugins.py b/saleor/plugins/tests/sample_plugins.py
index 0023281a5f..b1ecfb9144 100644
--- a/saleor/plugins/tests/sample_plugins.py
+++ b/saleor/plugins/tests/sample_plugins.py
@@ -353,6 +353,9 @@ class PluginSample(BasePlugin):
):
return []
+ def stored_payment_method_request_delete(self, request_delete_data, previous_value):
+ return previous_value
+
class ChannelPluginSample(PluginSample):
PLUGIN_ID = "channel.plugin.sample"
diff --git a/saleor/plugins/tests/test_manager.py b/saleor/plugins/tests/test_manager.py
index 22bf4cdf0e..e2e147aedd 100644
--- a/saleor/plugins/tests/test_manager.py
+++ b/saleor/plugins/tests/test_manager.py
@@ -21,6 +21,8 @@ from ...payment.interface import (
ListStoredPaymentMethodsRequestData,
PaymentGateway,
PaymentGatewayData,
+ StoredPaymentMethodRequestDeleteData,
+ StoredPaymentMethodRequestDeleteResponseData,
TransactionProcessActionData,
TransactionSessionData,
TransactionSessionResult,
@@ -1356,3 +1358,33 @@ def test_list_stored_payment_methods(
# then
mocked_list_stored_payment_methods.assert_called_once()
+
+
+@patch(
+ "saleor.plugins.tests.sample_plugins.PluginSample.stored_payment_method_request_delete"
+)
+def test_stored_payment_method_request_delete(
+ mocked_stored_payment_method_request_delete, customer_user, channel_USD
+):
+ # given
+ plugins = [
+ "saleor.plugins.tests.sample_plugins.PluginSample",
+ "saleor.plugins.tests.sample_plugins.PluginInactive",
+ ]
+ manager = PluginsManager(plugins=plugins)
+ request_delete_data = StoredPaymentMethodRequestDeleteData(
+ user=customer_user, payment_method_id="123", channel=channel_USD
+ )
+ previous_response = StoredPaymentMethodRequestDeleteResponseData(
+ success=False, message="Payment method request delete failed to deliver."
+ )
+
+ # when
+ manager.stored_payment_method_request_delete(
+ request_delete_data=request_delete_data
+ )
+
+ # then
+ mocked_stored_payment_method_request_delete.assert_called_once_with(
+ request_delete_data, previous_value=previous_response
+ )
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 34eb6bec79..c09c1cb656 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -22,6 +22,8 @@ from ...payment.interface import (
PaymentGateway,
PaymentGatewayData,
PaymentMethodData,
+ StoredPaymentMethodRequestDeleteData,
+ StoredPaymentMethodRequestDeleteResponseData,
TransactionActionData,
TransactionSessionData,
TransactionSessionResult,
@@ -61,12 +63,17 @@ from ...webhook.payloads import (
from ...webhook.utils import get_webhooks_for_event
from ..base_plugin import BasePlugin, ExcludedShippingMethod
from .const import CACHE_EXCLUDED_SHIPPING_KEY, WEBHOOK_CACHE_DEFAULT_TIMEOUT
-from .list_stored_payment_methods import get_list_stored_payment_methods_from_response
from .shipping import (
get_cache_data_for_shipping_list_methods_for_checkout,
get_excluded_shipping_data,
parse_list_shipping_methods_response,
)
+from .stored_payment_methods import (
+ get_list_stored_payment_methods_data_dict,
+ get_list_stored_payment_methods_from_response,
+ get_response_for_stored_payment_method_request_delete,
+ invalidate_cache_for_stored_payment_methods,
+)
from .tasks import (
send_webhook_request_async,
trigger_all_webhooks_sync,
@@ -1649,6 +1656,56 @@ class WebhookPlugin(BasePlugin):
delivery_update(delivery, status=EventDeliveryStatus.PENDING)
send_webhook_request_async.delay(delivery.pk)
+ def stored_payment_method_request_delete(
+ self,
+ request_delete_data: "StoredPaymentMethodRequestDeleteData",
+ previous_value: "StoredPaymentMethodRequestDeleteResponseData",
+ ) -> "StoredPaymentMethodRequestDeleteResponseData":
+ if not self.active:
+ return previous_value
+
+ app_data = from_payment_app_id(request_delete_data.payment_method_id)
+ if not app_data or not app_data.app_identifier:
+ return previous_value
+
+ event_type = WebhookEventSyncType.STORED_PAYMENT_METHOD_DELETE_REQUESTED
+ webhook = get_webhooks_for_event(
+ event_type, apps_identifier=[app_data.app_identifier]
+ ).first()
+
+ if not webhook:
+ return previous_value
+
+ payload = self._serialize_payload(
+ {
+ "payment_method_id": app_data.name,
+ "user_id": graphene.Node.to_global_id(
+ "User", request_delete_data.user.id
+ ),
+ "channel_slug": request_delete_data.channel.slug,
+ }
+ )
+
+ response_data = trigger_webhook_sync(
+ event_type,
+ payload,
+ webhook,
+ subscribable_object=StoredPaymentMethodRequestDeleteData(
+ payment_method_id=app_data.name,
+ user=request_delete_data.user,
+ channel=request_delete_data.channel,
+ ),
+ timeout=WEBHOOK_SYNC_TIMEOUT,
+ )
+ if response_data:
+ invalidate_cache_for_stored_payment_methods(
+ request_delete_data.user.id,
+ request_delete_data.channel.slug,
+ app_data.app_identifier,
+ )
+
+ return get_response_for_stored_payment_method_request_delete(response_data)
+
def list_stored_payment_methods(
self,
list_payment_method_data: "ListStoredPaymentMethodsRequestData",
@@ -1660,12 +1717,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS
if webhooks := get_webhooks_for_event(event_type):
- payload_dict = {
- "user_id": graphene.Node.to_global_id(
- "User", list_payment_method_data.user.id
- ),
- "channel_slug": list_payment_method_data.channel.slug,
- }
+ payload_dict = get_list_stored_payment_methods_data_dict(
+ list_payment_method_data.user.id, list_payment_method_data.channel.slug
+ )
payload = self._serialize_payload(payload_dict)
for webhook in webhooks:
if not webhook.app.identifier:
@@ -2217,6 +2271,9 @@ class WebhookPlugin(BasePlugin):
def is_event_active(self, event: str, channel=Optional[str]):
map_event = {
"invoice_request": WebhookEventAsyncType.INVOICE_REQUESTED,
+ "stored_payment_method_request_delete": (
+ WebhookEventSyncType.STORED_PAYMENT_METHOD_DELETE_REQUESTED
+ ),
}
if event in map_event:
diff --git a/saleor/plugins/webhook/stored_payment_methods.py b/saleor/plugins/webhook/stored_payment_methods.py
new file mode 100644
index 0000000000..d02a0b7511
--- /dev/null
+++ b/saleor/plugins/webhook/stored_payment_methods.py
@@ -0,0 +1,175 @@
+import logging
+from typing import Optional, cast
+
+import graphene
+from django.core.cache import cache
+
+from ...app.models import App
+from ...payment import TokenizedPaymentFlow
+from ...payment.interface import (
+ PaymentGateway,
+ PaymentMethodCreditCardInfo,
+ PaymentMethodData,
+ StoredPaymentMethodRequestDeleteResponseData,
+)
+from ...webhook.event_types import WebhookEventSyncType
+from ...webhook.utils import get_webhooks_for_event
+from .utils import generate_cache_key_for_webhook, to_payment_app_id
+
+logger = logging.getLogger(__name__)
+
+
+def get_credit_card_info(
+ app: App, credit_card_info: dict
+) -> Optional[PaymentMethodCreditCardInfo]:
+ required_fields = [
+ "brand",
+ "lastDigits",
+ "expYear",
+ "expMonth",
+ ]
+ brand = credit_card_info.get("brand")
+ last_digits = credit_card_info.get("lastDigits")
+ exp_year = credit_card_info.get("expYear")
+ exp_month = credit_card_info.get("expMonth")
+ first_digits = credit_card_info.get("firstDigits")
+ if not all(field in credit_card_info for field in required_fields):
+ logger.warning(
+ "Skipping stored payment method. Missing required fields for credit card "
+ "info. Required fields: %s, received fields: %s from app %s.",
+ required_fields,
+ credit_card_info.keys(),
+ app.id,
+ )
+ return None
+ if not all([brand, last_digits, exp_year, exp_month]):
+ logger.warning("Skipping stored credit card info without required fields")
+ return None
+ if not isinstance(exp_year, int):
+ if isinstance(exp_year, str) and exp_year.isdigit():
+ exp_year = int(exp_year)
+ else:
+ logger.warning(
+ "Skipping stored payment method with invalid expYear, "
+ "received from app %s",
+ app.id,
+ )
+ return None
+
+ if not isinstance(exp_month, int):
+ if isinstance(exp_month, str) and exp_month.isdigit():
+ exp_month = int(exp_month)
+ else:
+ logger.warning(
+ "Skipping stored payment method with invalid expMonth, "
+ "received from app %s",
+ app.id,
+ )
+ return None
+
+ return PaymentMethodCreditCardInfo(
+ brand=str(brand),
+ last_digits=str(last_digits),
+ exp_year=exp_year,
+ exp_month=exp_month,
+ first_digits=str(first_digits) if first_digits else None,
+ )
+
+
+def get_payment_method_from_response(
+ app: "App", payment_method: dict, currency: str
+) -> Optional[PaymentMethodData]:
+ payment_method_external_id = payment_method.get("id")
+ if not payment_method_external_id:
+ logger.warning(
+ "Skipping stored payment method without id, received from app %s", app.id
+ )
+ return None
+ payment_method_type = payment_method.get("type")
+ if not payment_method_type:
+ logger.warning(
+ "Skipping stored payment method without type, received from app %s",
+ app.id,
+ )
+ return None
+
+ supported_payment_flows = payment_method.get("supportedPaymentFlows")
+ if not supported_payment_flows or not isinstance(supported_payment_flows, list):
+ logger.warning(
+ "Skipping stored payment method with incorrect `supportedPaymentFlows`, "
+ "received from app %s",
+ app.id,
+ )
+ return None
+ payment_flow_choices = {
+ flow[0].upper(): flow[0] for flow in TokenizedPaymentFlow.CHOICES
+ }
+ if set(supported_payment_flows).difference(payment_flow_choices.keys()):
+ logger.warning(
+ "Skipping stored payment method with unsupported payment flows, "
+ "received from app %s",
+ app.id,
+ )
+ return None
+ app_identifier = cast(str, app.identifier)
+ credit_card_info = payment_method.get("creditCardInfo")
+ name = payment_method.get("name")
+ return PaymentMethodData(
+ id=to_payment_app_id(app, payment_method_external_id),
+ external_id=payment_method_external_id,
+ supported_payment_flows=[
+ payment_flow_choices[flow] for flow in supported_payment_flows
+ ],
+ type=payment_method_type,
+ credit_card_info=get_credit_card_info(app, credit_card_info)
+ if credit_card_info
+ else None,
+ name=name if name else None,
+ data=payment_method.get("data"),
+ gateway=PaymentGateway(
+ id=app_identifier, name=app.name, currencies=[currency], config=[]
+ ),
+ )
+
+
+def get_list_stored_payment_methods_from_response(
+ app: "App", response_data: dict, currency: str
+) -> list["PaymentMethodData"]:
+ payment_methods_response = response_data.get("paymentMethods", [])
+ payment_methods = []
+ for payment_method in payment_methods_response:
+ if parsed_payment_method := get_payment_method_from_response(
+ app, payment_method, currency
+ ):
+ payment_methods.append(parsed_payment_method)
+ return payment_methods
+
+
+def get_response_for_stored_payment_method_request_delete(
+ response_data: Optional[dict],
+) -> "StoredPaymentMethodRequestDeleteResponseData":
+ response_data = response_data or {"message": "Failed to delivery request."}
+ return StoredPaymentMethodRequestDeleteResponseData(
+ success=response_data.get("success", False),
+ message=response_data.get("message", None),
+ )
+
+
+def get_list_stored_payment_methods_data_dict(user_id: int, channel_slug: str):
+ return {
+ "user_id": graphene.Node.to_global_id("User", user_id),
+ "channel_slug": channel_slug,
+ }
+
+
+def invalidate_cache_for_stored_payment_methods(
+ user_id: int, channel_slug: str, app_identifier: str
+):
+ event_type = WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS
+ cache_data = get_list_stored_payment_methods_data_dict(user_id, channel_slug)
+ webhooks = get_webhooks_for_event(event_type, apps_identifier=[app_identifier])
+ for webhook in webhooks:
+ cache_key = generate_cache_key_for_webhook(
+ cache_data, webhook.target_url, event_type, webhook.app_id
+ )
+ cache.delete(cache_key)
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_method_request_delete.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_method_request_delete.py
new file mode 100644
index 0000000000..e4ffbedc32
--- /dev/null
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_method_request_delete.py
@@ -0,0 +1,54 @@
+import json
+
+import graphene
+
+from .....payment.interface import StoredPaymentMethodRequestDeleteData
+from .....webhook.event_types import WebhookEventSyncType
+from ...tasks import create_deliveries_for_subscriptions
+
+STORED_PAYMENT_METHOD_DELETE_REQUESTED = """
+subscription {
+ event {
+ ... on StoredPaymentMethodDeleteRequested{
+ user{
+ id
+ }
+ paymentMethodId
+ channel{
+ id
+ }
+ }
+ }
+}
+"""
+
+
+def test_stored_payment_method_request_delete(
+ stored_payment_method_request_delete_app, customer_user, channel_USD
+):
+ # given
+ webhook = stored_payment_method_request_delete_app.webhooks.first()
+ webhook.subscription_query = STORED_PAYMENT_METHOD_DELETE_REQUESTED
+ webhook.save()
+
+ payment_method_id = "123"
+
+ request_delete_data = StoredPaymentMethodRequestDeleteData(
+ user=customer_user, payment_method_id=payment_method_id, channel=channel_USD
+ )
+
+ event_type = WebhookEventSyncType.STORED_PAYMENT_METHOD_DELETE_REQUESTED
+
+ # when
+ delivery = create_deliveries_for_subscriptions(
+ event_type, request_delete_data, [webhook]
+ )[0]
+
+ # then
+ assert delivery.payload
+ assert delivery.payload.payload
+ assert json.loads(delivery.payload.payload) == {
+ "paymentMethodId": payment_method_id,
+ "user": {"id": graphene.Node.to_global_id("User", customer_user.pk)},
+ "channel": {"id": graphene.Node.to_global_id("Channel", channel_USD.pk)},
+ }
diff --git a/saleor/plugins/webhook/tests/test_list_stored_payment_methods_webhook.py b/saleor/plugins/webhook/tests/test_list_stored_payment_methods_webhook.py
index 0874f955e1..576addd6ab 100644
--- a/saleor/plugins/webhook/tests/test_list_stored_payment_methods_webhook.py
+++ b/saleor/plugins/webhook/tests/test_list_stored_payment_methods_webhook.py
@@ -6,7 +6,7 @@ from ....payment.interface import ListStoredPaymentMethodsRequestData
from ....settings import WEBHOOK_SYNC_TIMEOUT
from ....webhook.event_types import WebhookEventSyncType
from ..const import WEBHOOK_CACHE_DEFAULT_TIMEOUT
-from ..list_stored_payment_methods import get_list_stored_payment_methods_from_response
+from ..stored_payment_methods import get_list_stored_payment_methods_from_response
from ..utils import generate_cache_key_for_webhook
LIST_STORED_PAYMENT_METHODS = """
diff --git a/saleor/plugins/webhook/tests/test_stored_payment_method_request_delete.py b/saleor/plugins/webhook/tests/test_stored_payment_method_request_delete.py
new file mode 100644
index 0000000000..8d5c0c9ee7
--- /dev/null
+++ b/saleor/plugins/webhook/tests/test_stored_payment_method_request_delete.py
@@ -0,0 +1,295 @@
+import json
+
+import graphene
+import mock
+import pytest
+
+from ....core.models import EventDelivery
+from ....payment.interface import (
+ ListStoredPaymentMethodsRequestData,
+ StoredPaymentMethodRequestDeleteData,
+ StoredPaymentMethodRequestDeleteResponseData,
+)
+from ....settings import WEBHOOK_SYNC_TIMEOUT
+from ....webhook.event_types import WebhookEventSyncType
+from ....webhook.models import Webhook
+from ..const import WEBHOOK_CACHE_DEFAULT_TIMEOUT
+from ..utils import generate_cache_key_for_webhook, to_payment_app_id
+
+STORED_PAYMENT_METHOD_DELETE_REQUESTED = """
+subscription {
+ event {
+ ... on StoredPaymentMethodDeleteRequested{
+ user{
+ id
+ }
+ paymentMethodId
+ channel{
+ id
+ }
+ }
+ }
+}
+"""
+
+
+def webhook_stored_payment_method_request_delete_response():
+ return {"success": True, "message": "Payment method deleted successfully"}
+
+
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_stored_payment_method_request_delete_with_static_payload(
+ mock_request,
+ customer_user,
+ webhook_plugin,
+ stored_payment_method_request_delete_app,
+ webhook_stored_payment_method_request_delete_response,
+ channel_USD,
+):
+ # given
+ mock_request.return_value = webhook_stored_payment_method_request_delete_response
+
+ plugin = webhook_plugin()
+
+ payment_method_id = "123"
+
+ request_delete_data = StoredPaymentMethodRequestDeleteData(
+ user=customer_user,
+ payment_method_id=to_payment_app_id(
+ stored_payment_method_request_delete_app, payment_method_id
+ ),
+ channel=channel_USD,
+ )
+
+ previous_value = StoredPaymentMethodRequestDeleteResponseData(
+ success=False, message="Payment method request delete failed to deliver."
+ )
+
+ # when
+ response = plugin.stored_payment_method_request_delete(
+ request_delete_data, previous_value
+ )
+
+ # then
+ delivery = EventDelivery.objects.get()
+ assert delivery.payload.payload == json.dumps(
+ {
+ "payment_method_id": payment_method_id,
+ "user_id": graphene.Node.to_global_id("User", customer_user.pk),
+ "channel_slug": channel_USD.slug,
+ }
+ )
+ mock_request.assert_called_once_with(delivery, timeout=WEBHOOK_SYNC_TIMEOUT)
+
+ assert response == StoredPaymentMethodRequestDeleteResponseData(
+ success=True,
+ message=webhook_stored_payment_method_request_delete_response["message"],
+ )
+
+
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_stored_payment_method_request_delete_with_subscription_payload(
+ mock_request,
+ customer_user,
+ webhook_plugin,
+ stored_payment_method_request_delete_app,
+ webhook_stored_payment_method_request_delete_response,
+ channel_USD,
+):
+ # given
+ mock_request.return_value = webhook_stored_payment_method_request_delete_response
+
+ webhook = stored_payment_method_request_delete_app.webhooks.first()
+ webhook.subscription_query = STORED_PAYMENT_METHOD_DELETE_REQUESTED
+ webhook.save()
+
+ plugin = webhook_plugin()
+
+ payment_method_id = "123"
+
+ request_delete_data = StoredPaymentMethodRequestDeleteData(
+ user=customer_user,
+ payment_method_id=to_payment_app_id(
+ stored_payment_method_request_delete_app, payment_method_id
+ ),
+ channel=channel_USD,
+ )
+
+ previous_value = StoredPaymentMethodRequestDeleteResponseData(
+ success=False, message="Payment method request delete failed to deliver."
+ )
+
+ # when
+ response = plugin.stored_payment_method_request_delete(
+ request_delete_data, previous_value
+ )
+
+ # then
+ delivery = EventDelivery.objects.get()
+ assert delivery.payload.payload == json.dumps(
+ {
+ "user": {"id": graphene.Node.to_global_id("User", customer_user.pk)},
+ "paymentMethodId": payment_method_id,
+ "channel": {"id": graphene.Node.to_global_id("Channel", channel_USD.pk)},
+ }
+ )
+ mock_request.assert_called_once_with(delivery, timeout=WEBHOOK_SYNC_TIMEOUT)
+
+ assert response == StoredPaymentMethodRequestDeleteResponseData(
+ success=True,
+ message=webhook_stored_payment_method_request_delete_response["message"],
+ )
+
+
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_stored_payment_method_request_delete_missing_correct_response_from_webhook(
+ mock_request,
+ customer_user,
+ webhook_plugin,
+ stored_payment_method_request_delete_app,
+ webhook_stored_payment_method_request_delete_response,
+ channel_USD,
+):
+ # given
+ mock_request.return_value = None
+
+ webhook = stored_payment_method_request_delete_app.webhooks.first()
+ webhook.subscription_query = STORED_PAYMENT_METHOD_DELETE_REQUESTED
+ webhook.save()
+
+ plugin = webhook_plugin()
+
+ payment_method_id = "123"
+
+ request_delete_data = StoredPaymentMethodRequestDeleteData(
+ user=customer_user,
+ payment_method_id=to_payment_app_id(
+ stored_payment_method_request_delete_app, payment_method_id
+ ),
+ channel=channel_USD,
+ )
+
+ previous_value = StoredPaymentMethodRequestDeleteResponseData(
+ success=False, message="Payment method request delete failed to deliver."
+ )
+
+ # when
+ response = plugin.stored_payment_method_request_delete(
+ request_delete_data, previous_value
+ )
+
+ # then
+ delivery = EventDelivery.objects.get()
+
+ mock_request.assert_called_once_with(delivery, timeout=WEBHOOK_SYNC_TIMEOUT)
+
+ assert response == StoredPaymentMethodRequestDeleteResponseData(
+ success=False, message="Failed to delivery request."
+ )
+
+
[email protected]("saleor.plugins.webhook.tasks.cache.delete")
[email protected]("saleor.plugins.webhook.tasks.cache.set")
[email protected]("saleor.plugins.webhook.tasks.cache.get")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_stored_payment_method_request_delete_invalidates_cache_for_app(
+ mocked_request,
+ mocked_cache_get,
+ mocked_cache_set,
+ mocked_cache_delete,
+ customer_user,
+ webhook_plugin,
+ stored_payment_method_request_delete_app,
+ webhook_stored_payment_method_request_delete_response,
+ channel_USD,
+):
+ # given
+ mocked_cache_get.return_value = None
+
+ webhook = Webhook.objects.create(
+ name="list_stored_payment_methods",
+ app=stored_payment_method_request_delete_app,
+ target_url="http://localhost:8000/endpoint/",
+ )
+ webhook.events.create(
+ event_type=WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS,
+ )
+ list_stored_payment_methods_response = {"paymentMethods": []}
+ mocked_request.side_effect = [
+ list_stored_payment_methods_response,
+ webhook_stored_payment_method_request_delete_response,
+ ]
+
+ webhook = stored_payment_method_request_delete_app.webhooks.first()
+ webhook.subscription_query = STORED_PAYMENT_METHOD_DELETE_REQUESTED
+ webhook.save()
+
+ plugin = webhook_plugin()
+
+ payment_method_id = "123"
+
+ request_delete_data = StoredPaymentMethodRequestDeleteData(
+ user=customer_user,
+ payment_method_id=to_payment_app_id(
+ stored_payment_method_request_delete_app, payment_method_id
+ ),
+ channel=channel_USD,
+ )
+
+ previous_value = StoredPaymentMethodRequestDeleteResponseData(
+ success=False, message="Payment method request delete failed to deliver."
+ )
+
+ data = ListStoredPaymentMethodsRequestData(
+ channel=channel_USD,
+ user=customer_user,
+ )
+ expected_payload = {
+ "user_id": graphene.Node.to_global_id("User", customer_user.pk),
+ "channel_slug": channel_USD.slug,
+ }
+ expected_cache_key = generate_cache_key_for_webhook(
+ expected_payload,
+ webhook.target_url,
+ WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS,
+ stored_payment_method_request_delete_app.id,
+ )
+
+ # call mocked list_stored_payment_methods to call mocked cache logic
+ # this will make sure that we're deleting the same cache key as the one created
+ # in list_stored_payment_methods
+ plugin.list_stored_payment_methods(data, [])
+
+ mocked_cache_get.assert_called_once_with(expected_cache_key)
+ mocked_cache_set.assert_called_once_with(
+ expected_cache_key,
+ list_stored_payment_methods_response,
+ timeout=WEBHOOK_CACHE_DEFAULT_TIMEOUT,
+ )
+
+ # when
+ response = plugin.stored_payment_method_request_delete(
+ request_delete_data, previous_value
+ )
+
+ # then
+ delivery = EventDelivery.objects.filter(
+ event_type=WebhookEventSyncType.STORED_PAYMENT_METHOD_DELETE_REQUESTED
+ ).first()
+ assert delivery.payload.payload == json.dumps(
+ {
+ "user": {"id": graphene.Node.to_global_id("User", customer_user.pk)},
+ "paymentMethodId": payment_method_id,
+ "channel": {"id": graphene.Node.to_global_id("Channel", channel_USD.pk)},
+ }
+ )
+ # delete the same cache key as created when fetching stored payment methods
+ mocked_cache_delete.assert_called_once_with(expected_cache_key)
+
+ mocked_request.assert_called_with(delivery, timeout=WEBHOOK_SYNC_TIMEOUT)
+
+ assert response == StoredPaymentMethodRequestDeleteResponseData(
+ success=True,
+ message=webhook_stored_payment_method_request_delete_response["message"],
+ )
diff --git a/saleor/plugins/webhook/tests/test_utils.py b/saleor/plugins/webhook/tests/test_utils.py
index a7227b932f..ee9d3cce73 100644
--- a/saleor/plugins/webhook/tests/test_utils.py
+++ b/saleor/plugins/webhook/tests/test_utils.py
@@ -4,7 +4,7 @@ import pytest
from ....payment.interface import PaymentGateway
from ....webhook.event_types import WebhookEventSyncType
-from ..list_stored_payment_methods import (
+from ..stored_payment_methods import (
get_credit_card_info,
get_list_stored_payment_methods_from_response,
get_payment_method_from_response,
diff --git a/saleor/plugins/webhook/utils.py b/saleor/plugins/webhook/utils.py
index ff19c51b7a..728298d114 100644
--- a/saleor/plugins/webhook/utils.py
+++ b/saleor/plugins/webhook/utils.py
@@ -41,7 +41,7 @@ def to_payment_app_id(app: "App", external_id: str) -> "str":
def from_payment_app_id(app_gateway_id: str) -> Optional["PaymentAppData"]:
- splitted_id = app_gateway_id.split(":")
+ splitted_id = app_gateway_id.split(":", maxsplit=2)
if len(splitted_id) == 3 and splitted_id[0] == APP_ID_PREFIX and all(splitted_id):
try:
app_pk = int(splitted_id[1])
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 9209c1808b..b46beb766e 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -6502,6 +6502,27 @@ def list_stored_payment_methods_app(db, permission_manage_payments):
return app
+def stored_payment_method_request_delete_app(db, permission_manage_payments):
+ app = App.objects.create(
+ name="Payment method request delete",
+ is_active=True,
+ identifier="saleor.payment.app.payment.method.request.delete",
+ )
+ app.tokens.create(name="Default")
+ app.permissions.add(permission_manage_payments)
+
+ webhook = Webhook.objects.create(
+ name="stored_payment_method_request_delete",
+ app=app,
+ target_url="http://localhost:8000/endpoint/",
+ )
+ webhook.events.create(
+ event_type=WebhookEventSyncType.STORED_PAYMENT_METHOD_DELETE_REQUESTED,
+ )
+ return app
+
+
@pytest.fixture
def tax_app(db, permission_handle_taxes):
app = App.objects.create(name="Tax App", is_active=True)
diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.py
index f8073d39ab..5a4b32a57b 100644
--- a/saleor/webhook/event_types.py
+++ b/saleor/webhook/event_types.py
@@ -733,6 +733,7 @@ class WebhookEventSyncType:
TRANSACTION_PROCESS_SESSION = "transaction_process_session"
LIST_STORED_PAYMENT_METHODS = "list_stored_payment_methods"
+ STORED_PAYMENT_METHOD_DELETE_REQUESTED = "stored_payment_method_delete_requested"
EVENT_MAP: dict[str, dict[str, Any]] = {
PAYMENT_LIST_GATEWAYS: {
@@ -811,6 +812,10 @@ class WebhookEventSyncType:
"name": "List tokenized payment methods that can be used by the customer.",
"permission": PaymentPermissions.HANDLE_PAYMENTS,
},
+ STORED_PAYMENT_METHOD_DELETE_REQUESTED: {
+ "name": "Request deletion of a tokenized payment method.",
+ "permission": PaymentPermissions.HANDLE_PAYMENTS,
+ },
}
CHOICES = [