Skip to content

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

[Programmatic payments] tokenize payment method API (#13879)

Maciej Korycinski12c064ad768f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 605bc0a6ca..107c9f80ea 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -29,6 +29,9 @@ All notable, unreleased changes to this project will be documented in this file.
- Add `externalReference` to `updateWarehouse`. It will allow update warehouse by
external reference. - #13342 by @Smit-Parmar
- Add Filter warehouses by metadata - #13345 by @Smit-Parmar
+- Add API for tokenizing payment methods - #13879 by @korycins
+
+
- Deprecate the `NOTIFY_USER` webhook and the `externalNotificationTrigger` mutation - #13881 by @maarcingebala
- See the docs for more details about migrating from the `NOTIFY_USER` webhook to other events: https://docs.saleor.io/docs/next/upgrade-guides/notify-user-deprecation
@@ -46,6 +49,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Event sent when CSV export for products is completed.
- Add `FULFILLMENT_TRACKING_NUMBER_UPDATED` webhook - #13708, by @Air-t
- Called after `fulfillmentUpdateTracking` or `orderFulfill` mutation if tracking number is updated.
+- Add support for tokenizing payment methods via sync webhooks - #13879 by @korycins
- Add missing `FULFILLMENT_CREATED` event call to `automatically_fulfill_digital_lines_with_fulfillment_created` action. - #13823, by @Air-t
### Other changes
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index afa54b7b12..7de3288e33 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -14,6 +14,7 @@ from ...checkout.utils import get_valid_collection_points_for_checkout
from ...core.taxes import zero_money, zero_taxed_money
from ...core.utils.lazyobjects import unwrap_lazy
from ...payment.interface import ListStoredPaymentMethodsRequestData
+from ...permission.auth_filters import AuthorizationFilters
from ...permission.enums import (
AccountPermissions,
CheckoutPermissions,
@@ -477,7 +478,13 @@ class Checkout(ModelObjectType[models.Checkout]):
)
user = graphene.Field(
"saleor.graphql.account.types.User",
- description="The user assigned to the checkout.",
+ description=(
+ "The user assigned to the checkout. Requires one of the following "
+ "permissions: "
+ f"{AccountPermissions.MANAGE_USERS.name}, "
+ f"{PaymentPermissions.HANDLE_PAYMENTS.name}, "
+ f"{AuthorizationFilters.OWNER.name}."
+ ),
)
channel = graphene.Field(
Channel,
@@ -803,7 +810,10 @@ class Checkout(ModelObjectType[models.Checkout]):
return None
requestor = get_user_or_app_from_context(info.context)
check_is_owner_or_has_one_of_perms(
- requestor, root.user, AccountPermissions.MANAGE_USERS
+ requestor,
+ root.user,
+ AccountPermissions.MANAGE_USERS,
+ PaymentPermissions.HANDLE_PAYMENTS,
)
return root.user
diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.py
index 5382170dc0..2a07dc31df 100644
--- a/saleor/graphql/core/enums.py
+++ b/saleor/graphql/core/enums.py
@@ -300,6 +300,21 @@ StoredPaymentMethodRequestDeleteErrorCode = graphene.Enum.from_enum(
)
StoredPaymentMethodRequestDeleteErrorCode.doc_category = DOC_CATEGORY_PAYMENTS
+PaymentGatewayInitializeTokenizationErrorCode = graphene.Enum.from_enum(
+ payment_error_codes.PaymentGatewayInitializeTokenizationErrorCode
+)
+PaymentGatewayInitializeTokenizationErrorCode.doc_category = DOC_CATEGORY_PAYMENTS
+
+PaymentMethodInitializeTokenizationErrorCode = graphene.Enum.from_enum(
+ payment_error_codes.PaymentMethodInitializeTokenizationErrorCode
+)
+PaymentMethodInitializeTokenizationErrorCode.doc_category = DOC_CATEGORY_PAYMENTS
+
+PaymentMethodProcessTokenizationErrorCode = graphene.Enum.from_enum(
+ payment_error_codes.PaymentMethodProcessTokenizationErrorCode
+)
+PaymentMethodProcessTokenizationErrorCode.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 22abd30f0f..71935a070e 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -63,6 +63,9 @@ from ..enums import (
PaymentErrorCode,
PaymentGatewayConfigErrorCode,
PaymentGatewayInitializeErrorCode,
+ PaymentGatewayInitializeTokenizationErrorCode,
+ PaymentMethodInitializeTokenizationErrorCode,
+ PaymentMethodProcessTokenizationErrorCode,
PermissionEnum,
PermissionGroupErrorCode,
PluginErrorCode,
@@ -690,6 +693,33 @@ class PaymentMethodRequestDeleteError(Error):
doc_category = DOC_CATEGORY_PAYMENTS
+class PaymentGatewayInitializeTokenizationError(Error):
+ code = PaymentGatewayInitializeTokenizationErrorCode(
+ description="The error code.", required=True
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_PAYMENTS
+
+
+class PaymentMethodInitializeTokenizationError(Error):
+ code = PaymentMethodInitializeTokenizationErrorCode(
+ description="The error code.", required=True
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_PAYMENTS
+
+
+class PaymentMethodProcessTokenizationError(Error):
+ code = PaymentMethodProcessTokenizationErrorCode(
+ 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/order/types.py b/saleor/graphql/order/types.py
index 574aa1fcf3..a1ae4fa1aa 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -995,6 +995,7 @@ class Order(ModelObjectType[models.Order]):
"and later, for other orders requires one of the following permissions: "
f"{AccountPermissions.MANAGE_USERS.name}, "
f"{OrderPermissions.MANAGE_ORDERS.name}, "
+ f"{PaymentPermissions.HANDLE_PAYMENTS.name}, "
f"{AuthorizationFilters.OWNER.name}."
),
)
@@ -1792,6 +1793,7 @@ class Order(ModelObjectType[models.Order]):
user,
AccountPermissions.MANAGE_USERS,
OrderPermissions.MANAGE_ORDERS,
+ PaymentPermissions.HANDLE_PAYMENTS,
)
return user
diff --git a/saleor/graphql/payment/enums.py b/saleor/graphql/payment/enums.py
index a26a96a459..4bb5fe66fe 100644
--- a/saleor/graphql/payment/enums.py
+++ b/saleor/graphql/payment/enums.py
@@ -8,7 +8,11 @@ from ...payment import (
TransactionEventType,
TransactionKind,
)
-from ...payment.interface import StoredPaymentMethodRequestDeleteResult
+from ...payment.interface import (
+ PaymentGatewayInitializeTokenizationResult,
+ PaymentMethodTokenizationResult,
+ StoredPaymentMethodRequestDeleteResult,
+)
from ..core.doc_category import DOC_CATEGORY_PAYMENTS
from ..core.enums import to_enum
from ..core.types import BaseEnum
@@ -85,6 +89,16 @@ TokenizedPaymentFlowEnum = to_enum(
)
TokenizedPaymentFlowEnum.doc_category = DOC_CATEGORY_PAYMENTS
+PaymentGatewayInitializeTokenizationResultEnum = graphene.Enum.from_enum(
+ PaymentGatewayInitializeTokenizationResult,
+)
+PaymentGatewayInitializeTokenizationResultEnum.doc_category = DOC_CATEGORY_PAYMENTS
+
+PaymentMethodTokenizationResultEnum = graphene.Enum.from_enum(
+ PaymentMethodTokenizationResult
+)
+PaymentMethodTokenizationResultEnum.doc_category = DOC_CATEGORY_PAYMENTS
+
StoredPaymentMethodRequestDeleteResultEnum = graphene.Enum.from_enum(
StoredPaymentMethodRequestDeleteResult,
)
diff --git a/saleor/graphql/payment/mutations/__init__.py b/saleor/graphql/payment/mutations/__init__.py
index 65a59c1c5e..5f00a9f4bb 100644
--- a/saleor/graphql/payment/mutations/__init__.py
+++ b/saleor/graphql/payment/mutations/__init__.py
@@ -6,7 +6,12 @@ from .payment import (
PaymentRefund,
PaymentVoid,
)
-from .stored_payment_methods import StoredPaymentMethodRequestDelete
+from .stored_payment_methods import (
+ PaymentGatewayInitializeTokenization,
+ PaymentMethodInitializeTokenization,
+ PaymentMethodProcessTokenization,
+ StoredPaymentMethodRequestDelete,
+)
from .transaction import (
PaymentGatewayInitialize,
TransactionCreate,
@@ -26,7 +31,10 @@ __all__ = [
"PaymentInitialize",
"PaymentRefund",
"PaymentVoid",
+ "PaymentGatewayInitializeTokenization",
+ "PaymentMethodProcessTokenization",
"StoredPaymentMethodRequestDelete",
+ "PaymentMethodInitializeTokenization",
"TransactionCreate",
"TransactionEventReport",
"TransactionInitialize",
diff --git a/saleor/graphql/payment/mutations/stored_payment_methods/__init__.py b/saleor/graphql/payment/mutations/stored_payment_methods/__init__.py
index 6b19321604..2db73eaf9a 100644
--- a/saleor/graphql/payment/mutations/stored_payment_methods/__init__.py
+++ b/saleor/graphql/payment/mutations/stored_payment_methods/__init__.py
@@ -1,5 +1,13 @@
+from .payment_gateway_initialize_tokenization import (
+ PaymentGatewayInitializeTokenization,
+)
+from .payment_method_intialize_tokenization import PaymentMethodInitializeTokenization
+from .payment_method_process_tokenization import PaymentMethodProcessTokenization
from .payment_method_request_delete import StoredPaymentMethodRequestDelete
__all__ = [
"StoredPaymentMethodRequestDelete",
+ "PaymentGatewayInitializeTokenization",
+ "PaymentMethodInitializeTokenization",
+ "PaymentMethodProcessTokenization",
]
diff --git a/saleor/graphql/payment/mutations/stored_payment_methods/payment_gateway_initialize_tokenization.py b/saleor/graphql/payment/mutations/stored_payment_methods/payment_gateway_initialize_tokenization.py
new file mode 100644
index 0000000000..e31c3c699d
--- /dev/null
+++ b/saleor/graphql/payment/mutations/stored_payment_methods/payment_gateway_initialize_tokenization.py
@@ -0,0 +1,114 @@
+import graphene
+from django.core.exceptions import ValidationError
+
+from .....payment.interface import PaymentGatewayInitializeTokenizationRequestData
+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 PaymentGatewayInitializeTokenizationErrorCode
+from ....core.mutations import BaseMutation
+from ....core.scalars import JSON
+from ....core.types.common import PaymentGatewayInitializeTokenizationError
+from ....core.utils import WebhookEventInfo
+from ....plugins.dataloaders import get_plugin_manager_promise
+from ...enums import PaymentGatewayInitializeTokenizationResultEnum
+
+
+class PaymentGatewayInitializeTokenization(BaseMutation):
+ result = PaymentGatewayInitializeTokenizationResultEnum(
+ description="A status of the payment gateway initialization.", required=True
+ )
+ data = JSON(
+ description="A data returned by payment app.",
+ )
+
+ class Arguments:
+ id = graphene.String(
+ required=True,
+ description=(
+ "The identifier of the payment gateway app to initialize tokenization."
+ ),
+ )
+ channel = graphene.String(
+ description="Slug of a channel related to tokenization request.",
+ required=True,
+ )
+
+ data = graphene.Argument(
+ JSON, description="The data that will be passed to the payment gateway."
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_PAYMENTS
+ description = (
+ "Initializes payment gateway for tokenizing payment method session."
+ + ADDED_IN_316
+ + PREVIEW_FEATURE
+ )
+ webhook_events_info = [
+ WebhookEventInfo(
+ type=(
+ WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_TOKENIZATION_SESSION
+ ),
+ description=(
+ "The customer requested to initialize payment gateway for "
+ "tokenization."
+ ),
+ ),
+ ]
+ error_type_class = PaymentGatewayInitializeTokenizationError
+ permissions = (AuthorizationFilters.AUTHENTICATED_USER,)
+
+ @classmethod
+ def _perform_mutation(cls, root, info, id, channel, data=None):
+ user = info.context.user
+ channel = validate_channel(
+ channel, PaymentGatewayInitializeTokenizationErrorCode
+ )
+
+ manager = get_plugin_manager_promise(info.context).get()
+ is_active = manager.is_event_active_for_any_plugin(
+ "payment_gateway_initialize_tokenization"
+ )
+
+ if not is_active:
+ raise ValidationError(
+ (
+ "No active payment app that could initialize payment gateway for "
+ "tokenization."
+ ),
+ code=PaymentGatewayInitializeTokenizationErrorCode.NOT_FOUND.value,
+ )
+
+ response = manager.payment_gateway_initialize_tokenization(
+ request_data=PaymentGatewayInitializeTokenizationRequestData(
+ app_identifier=id, user=user, channel=channel, data=data
+ )
+ )
+ errors = []
+ result_enum = PaymentGatewayInitializeTokenizationResultEnum
+ if response.result != result_enum.SUCCESSFULLY_INITIALIZED.value:
+ error_code = (
+ PaymentGatewayInitializeTokenizationErrorCode.GATEWAY_ERROR.value
+ )
+ errors.append(
+ {
+ "message": response.error,
+ "code": error_code,
+ }
+ )
+
+ return cls(result=response.result, data=response.data, errors=errors)
+
+ @classmethod
+ def perform_mutation(cls, root, info, id, channel, data=None):
+ try:
+ return cls._perform_mutation(root, info, id, channel, data)
+ except ValidationError as error:
+ error_response = cls.handle_errors(error)
+ error_response.result = (
+ PaymentGatewayInitializeTokenizationResultEnum.FAILED_TO_DELIVER.value
+ )
+ return error_response
diff --git a/saleor/graphql/payment/mutations/stored_payment_methods/payment_method_intialize_tokenization.py b/saleor/graphql/payment/mutations/stored_payment_methods/payment_method_intialize_tokenization.py
new file mode 100644
index 0000000000..535b13728a
--- /dev/null
+++ b/saleor/graphql/payment/mutations/stored_payment_methods/payment_method_intialize_tokenization.py
@@ -0,0 +1,104 @@
+import graphene
+from django.core.exceptions import ValidationError
+
+from .....payment.interface import PaymentMethodInitializeTokenizationRequestData
+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 PaymentMethodInitializeTokenizationErrorCode
+from ....core.mutations import BaseMutation
+from ....core.scalars import JSON
+from ....core.types.common import PaymentMethodInitializeTokenizationError
+from ....core.utils import WebhookEventInfo
+from ...enums import PaymentMethodTokenizationResultEnum, TokenizedPaymentFlowEnum
+from .utils import handle_payment_method_action
+
+
+class PaymentMethodInitializeTokenization(BaseMutation):
+ result = PaymentMethodTokenizationResultEnum(
+ description="A status of the payment method tokenization.", required=True
+ )
+ id = graphene.String(description="The identifier of the payment method.")
+ data = JSON(
+ description="A data returned by the payment app.",
+ )
+
+ class Arguments:
+ id = graphene.String(
+ required=True,
+ description=(
+ "The identifier of the payment gateway app to initialize payment "
+ "method tokenization."
+ ),
+ )
+ channel = graphene.String(
+ description="Slug of a channel related to tokenization request.",
+ required=True,
+ )
+ payment_flow_to_support = TokenizedPaymentFlowEnum(
+ description=(
+ "The payment flow that the tokenized payment method should support."
+ ),
+ required=True,
+ )
+
+ data = graphene.Argument(
+ JSON, description="The data that will be passed to the payment gateway."
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_PAYMENTS
+ description = "Tokenize payment method." + ADDED_IN_316 + PREVIEW_FEATURE
+ webhook_events_info = [
+ WebhookEventInfo(
+ type=(
+ WebhookEventSyncType.PAYMENT_METHOD_INITIALIZE_TOKENIZATION_SESSION
+ ),
+ description="The customer requested to tokenize payment method.",
+ ),
+ ]
+ error_type_class = PaymentMethodInitializeTokenizationError
+ permissions = (AuthorizationFilters.AUTHENTICATED_USER,)
+
+ @classmethod
+ def _perform_mutation(
+ cls, root, info, id, channel, payment_flow_to_support, data=None
+ ):
+ user = info.context.user
+ channel = validate_channel(
+ channel, PaymentMethodInitializeTokenizationErrorCode
+ )
+
+ response, errors = handle_payment_method_action(
+ info,
+ "payment_method_initialize_tokenization",
+ PaymentMethodInitializeTokenizationRequestData(
+ app_identifier=id,
+ user=user,
+ channel=channel,
+ data=data,
+ payment_flow_to_support=payment_flow_to_support,
+ ),
+ PaymentMethodInitializeTokenizationErrorCode,
+ )
+
+ return cls(
+ result=response.result, data=response.data, errors=errors, id=response.id
+ )
+
+ @classmethod
+ def perform_mutation(
+ cls, root, info, id, channel, payment_flow_to_support, data=None
+ ):
+ try:
+ return cls._perform_mutation(
+ root, info, id, channel, payment_flow_to_support, data
+ )
+ except ValidationError as error:
+ error_response = cls.handle_errors(error)
+ error_response.result = (
+ PaymentMethodTokenizationResultEnum.FAILED_TO_DELIVER.value
+ )
+ return error_response
diff --git a/saleor/graphql/payment/mutations/stored_payment_methods/payment_method_process_tokenization.py b/saleor/graphql/payment/mutations/stored_payment_methods/payment_method_process_tokenization.py
new file mode 100644
index 0000000000..e2164989a0
--- /dev/null
+++ b/saleor/graphql/payment/mutations/stored_payment_methods/payment_method_process_tokenization.py
@@ -0,0 +1,83 @@
+import graphene
+from django.core.exceptions import ValidationError
+
+from .....payment.interface import PaymentMethodProcessTokenizationRequestData
+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 PaymentMethodProcessTokenizationErrorCode
+from ....core.mutations import BaseMutation
+from ....core.scalars import JSON
+from ....core.types.common import PaymentMethodProcessTokenizationError
+from ....core.utils import WebhookEventInfo
+from ...enums import PaymentMethodTokenizationResultEnum
+from .utils import handle_payment_method_action
+
+
+class PaymentMethodProcessTokenization(BaseMutation):
+ result = PaymentMethodTokenizationResultEnum(
+ description="A status of the payment method tokenization.", required=True
+ )
+ id = graphene.String(description="The identifier of the payment method.")
+ data = JSON(
+ description="A data returned by the payment app.",
+ )
+
+ class Arguments:
+ id = graphene.String(
+ required=True,
+ description=(
+ "The identifier of the payment gateway app to process payment "
+ "method tokenization."
+ ),
+ )
+ channel = graphene.String(
+ description="Slug of a channel related to tokenization request.",
+ required=True,
+ )
+
+ data = graphene.Argument(
+ JSON, description="The data that will be passed to the payment gateway."
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_PAYMENTS
+ description = "Tokenize payment method." + ADDED_IN_316 + PREVIEW_FEATURE
+ webhook_events_info = [
+ WebhookEventInfo(
+ type=(WebhookEventSyncType.PAYMENT_METHOD_PROCESS_TOKENIZATION_SESSION),
+ description="The customer continues payment method tokenization.",
+ ),
+ ]
+ error_type_class = PaymentMethodProcessTokenizationError
+ permissions = (AuthorizationFilters.AUTHENTICATED_USER,)
+
+ @classmethod
+ def _perform_mutation(cls, root, info, id, channel, data=None):
+ user = info.context.user
+ channel = validate_channel(channel, PaymentMethodProcessTokenizationErrorCode)
+
+ response, errors = handle_payment_method_action(
+ info,
+ "payment_method_process_tokenization",
+ PaymentMethodProcessTokenizationRequestData(
+ id=id, user=user, channel=channel, data=data
+ ),
+ PaymentMethodProcessTokenizationErrorCode,
+ )
+ return cls(
+ result=response.result, data=response.data, errors=errors, id=response.id
+ )
+
+ @classmethod
+ def perform_mutation(cls, root, info, id, channel, data=None):
+ try:
+ return cls._perform_mutation(root, info, id, channel, data)
+ except ValidationError as error:
+ error_response = cls.handle_errors(error)
+ error_response.result = (
+ PaymentMethodTokenizationResultEnum.FAILED_TO_DELIVER.value
+ )
+ return error_response
diff --git a/saleor/graphql/payment/mutations/stored_payment_methods/utils.py b/saleor/graphql/payment/mutations/stored_payment_methods/utils.py
new file mode 100644
index 0000000000..a4670de05b
--- /dev/null
+++ b/saleor/graphql/payment/mutations/stored_payment_methods/utils.py
@@ -0,0 +1,44 @@
+from django.core.exceptions import ValidationError
+
+from .....payment.interface import (
+ PaymentMethodTokenizationBaseRequestData,
+ PaymentMethodTokenizationResponseData,
+)
+from ....core import ResolveInfo
+from ....plugins.dataloaders import get_plugin_manager_promise
+from ...enums import PaymentMethodTokenizationResultEnum
+
+
+def handle_payment_method_action(
+ info: ResolveInfo,
+ manager_func_name: str,
+ request_data: PaymentMethodTokenizationBaseRequestData,
+ error_type_class,
+) -> tuple[PaymentMethodTokenizationResponseData, list[dict]]:
+ manager = get_plugin_manager_promise(info.context).get()
+ is_active = manager.is_event_active_for_any_plugin(manager_func_name)
+
+ if not is_active:
+ raise ValidationError(
+ "No active payment app to handle requested action.",
+ code=error_type_class.NOT_FOUND.value,
+ )
+
+ response = getattr(manager, manager_func_name)(request_data=request_data)
+
+ errors = []
+ result_enum = PaymentMethodTokenizationResultEnum
+ result_without_error = [
+ result_enum.SUCCESSFULLY_TOKENIZED,
+ result_enum.ADDITIONAL_ACTION_REQUIRED,
+ result_enum.PENDING,
+ ]
+ if response.result not in result_without_error:
+ error_code = error_type_class.GATEWAY_ERROR.value
+ errors.append(
+ {
+ "message": response.error,
+ "code": error_code,
+ }
+ )
+ return response, errors
diff --git a/saleor/graphql/payment/schema.py b/saleor/graphql/payment/schema.py
index a939be81e5..4cfcdb56be 100644
--- a/saleor/graphql/payment/schema.py
+++ b/saleor/graphql/payment/schema.py
@@ -12,7 +12,10 @@ from .mutations import (
PaymentCapture,
PaymentCheckBalance,
PaymentGatewayInitialize,
+ PaymentGatewayInitializeTokenization,
PaymentInitialize,
+ PaymentMethodInitializeTokenization,
+ PaymentMethodProcessTokenization,
PaymentRefund,
PaymentVoid,
StoredPaymentMethodRequestDelete,
@@ -100,3 +103,8 @@ class PaymentMutations(graphene.ObjectType):
transaction_process = TransactionProcess.Field()
stored_payment_method_request_delete = StoredPaymentMethodRequestDelete.Field()
+ payment_gateway_initialize_tokenization = (
+ PaymentGatewayInitializeTokenization.Field()
+ )
+ payment_method_initialize_tokenization = PaymentMethodInitializeTokenization.Field()
+ payment_method_process_tokenization = PaymentMethodProcessTokenization.Field()
diff --git a/saleor/graphql/payment/tests/mutations/test_payment_gateway_initialize_tokenization.py b/saleor/graphql/payment/tests/mutations/test_payment_gateway_initialize_tokenization.py
new file mode 100644
index 0000000000..32fa39613c
--- /dev/null
+++ b/saleor/graphql/payment/tests/mutations/test_payment_gateway_initialize_tokenization.py
@@ -0,0 +1,260 @@
+from unittest.mock import patch
+
+import pytest
+
+from .....payment.interface import (
+ PaymentGatewayInitializeTokenizationRequestData,
+ PaymentGatewayInitializeTokenizationResponseData,
+ PaymentGatewayInitializeTokenizationResult,
+)
+from .....plugins.manager import PluginsManager
+from ....core.enums import PaymentGatewayInitializeTokenizationErrorCode
+from ....tests.utils import assert_no_permission, get_graphql_content
+from ...enums import PaymentGatewayInitializeTokenizationResultEnum
+
+PAYMENT_GATEWAY_INITIALIZE_TOKENIZATION = """
+mutation PaymentGatewayInitializeTokenization(
+$id: String!, $channel: String!, $data: JSON){
+ paymentGatewayInitializeTokenization(id: $id, channel: $channel, data: $data){
+ result
+ data
+ errors{
+ field
+ code
+ message
+ }
+ }
+}
+"""
+
+
+ "expected_input_data, expected_output_data",
+ [
+ (None, None),
+ (None, {"foo": "bar1"}),
+ ({"foo": "bar2"}, None),
+ ({"foo": "bar3"}, {"foo": "bar4"}),
+ ],
+)
[email protected](PluginsManager, "payment_gateway_initialize_tokenization")
[email protected](PluginsManager, "is_event_active_for_any_plugin")
+def test_payment_gateway_initialize_tokenization(
+ mocked_is_event_active_for_any_plugin,
+ mocked_payment_gateway_initialize_tokenization,
+ expected_input_data,
+ expected_output_data,
+ user_api_client,
+ channel_USD,
+):
+ # given
+ mocked_is_event_active_for_any_plugin.return_value = True
+ mocked_payment_gateway_initialize_tokenization.return_value = (
+ PaymentGatewayInitializeTokenizationResponseData(
+ result=PaymentGatewayInitializeTokenizationResult.SUCCESSFULLY_INITIALIZED,
+ error=None,
+ data=expected_output_data,
+ )
+ )
+ expected_id = "test_id"
+
+ # when
+ response = user_api_client.post_graphql(
+ PAYMENT_GATEWAY_INITIALIZE_TOKENIZATION,
+ variables={
+ "id": expected_id,
+ "channel": channel_USD.slug,
+ "data": expected_input_data,
+ },
+ )
+
+ # then
+ content = get_graphql_content(response)
+ response_data = content["data"]["paymentGatewayInitializeTokenization"]
+ assert response_data["result"] == (
+ PaymentGatewayInitializeTokenizationResultEnum.SUCCESSFULLY_INITIALIZED.name
+ )
+ assert response_data["data"] == expected_output_data
+
+ mocked_is_event_active_for_any_plugin.assert_called_once_with(
+ "payment_gateway_initialize_tokenization"
+ )
+ mocked_payment_gateway_initialize_tokenization.assert_called_once_with(
+ request_data=PaymentGatewayInitializeTokenizationRequestData(
+ user=user_api_client.user,
+ channel=channel_USD,
+ app_identifier=expected_id,
+ data=expected_input_data,
+ )
+ )
+
+
[email protected](PluginsManager, "payment_gateway_initialize_tokenization")
[email protected](PluginsManager, "is_event_active_for_any_plugin")
+def test_payment_gateway_initialize_tokenization_called_by_anonymous_user(
+ mocked_is_event_active_for_any_plugin,
+ mocked_payment_gateway_initialize_tokenization,
+ api_client,
+ channel_USD,
+):
+ # given
+ expected_id = "test_id"
+
+ # when
+ response = api_client.post_graphql(
+ PAYMENT_GATEWAY_INITIALIZE_TOKENIZATION,
+ 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_payment_gateway_initialize_tokenization.called
+
+
[email protected](PluginsManager, "payment_gateway_initialize_tokenization")
[email protected](PluginsManager, "is_event_active_for_any_plugin")
+def test_payment_gateway_initialize_tokenization_called_by_app(
+ mocked_is_event_active_for_any_plugin,
+ mocked_payment_gateway_initialize_tokenization,
+ app_api_client,
+ channel_USD,
+):
+ # given
+ expected_id = "test_id"
+
+ # when
+ response = app_api_client.post_graphql(
+ PAYMENT_GATEWAY_INITIALIZE_TOKENIZATION,
+ 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_payment_gateway_initialize_tokenization.called
+
+
[email protected](PluginsManager, "payment_gateway_initialize_tokenization")
[email protected](PluginsManager, "is_event_active_for_any_plugin")
+def test_payment_gateway_initialize_tokenization_not_app_or_plugin_subscribed_to_event(
+ mocked_is_event_active_for_any_plugin,
+ mocked_payment_gateway_initialize_tokenization,
+ user_api_client,
+ channel_USD,
+):
+ # given
+ mocked_is_event_active_for_any_plugin.return_value = False
+
+ expected_id = "test_id"
+
+ # when
+ response = user_api_client.post_graphql(
+ PAYMENT_GATEWAY_INITIALIZE_TOKENIZATION,
+ variables={"id": expected_id, "channel": channel_USD.slug},
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert len(content["data"]["paymentGatewayInitializeTokenization"]["errors"]) == 1
+ assert (
+ content["data"]["paymentGatewayInitializeTokenization"]["errors"][0]["code"]
+ == PaymentGatewayInitializeTokenizationErrorCode.NOT_FOUND.name
+ )
+ assert content["data"]["paymentGatewayInitializeTokenization"]["result"] == (
+ PaymentGatewayInitializeTokenizationResultEnum.FAILED_TO_DELIVER.name
+ )
+
+ mocked_is_event_active_for_any_plugin.assert_called_once_with(
+ "payment_gateway_initialize_tokenization"
+ )
+ assert not mocked_payment_gateway_initialize_tokenization.called
+
+
[email protected](PluginsManager, "payment_gateway_initialize_tokenization")
[email protected](PluginsManager, "is_event_active_for_any_plugin")
+def test_payment_gateway_initialize_tokenization_incorrect_channel(
+ mocked_is_event_active_for_any_plugin,
+ mocked_payment_gateway_initialize_tokenization,
+ user_api_client,
+):
+ # given
+ expected_id = "test_id"
+
+ # when
+ response = user_api_client.post_graphql(
+ PAYMENT_GATEWAY_INITIALIZE_TOKENIZATION,
+ variables={"id": expected_id, "channel": "non-exiting-channel"},
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert len(content["data"]["paymentGatewayInitializeTokenization"]["errors"]) == 1
+ assert (
+ content["data"]["paymentGatewayInitializeTokenization"]["errors"][0]["code"]
+ == PaymentGatewayInitializeTokenizationErrorCode.NOT_FOUND.name
+ )
+ assert content["data"]["paymentGatewayInitializeTokenization"]["result"] == (
+ PaymentGatewayInitializeTokenizationResultEnum.FAILED_TO_DELIVER.name
+ )
+
+ assert not mocked_is_event_active_for_any_plugin.called
+ assert not mocked_payment_gateway_initialize_tokenization.called
+
+
[email protected](PluginsManager, "payment_gateway_initialize_tokenization")
[email protected](PluginsManager, "is_event_active_for_any_plugin")
+def test_payment_gateway_initialize_tokenization_failure_from_app(
+ mocked_is_event_active_for_any_plugin,
+ mocked_payment_gateway_initialize_tokenization,
+ user_api_client,
+ channel_USD,
+):
+ # given
+ error_message = "Error message"
+ mocked_is_event_active_for_any_plugin.return_value = True
+ mocked_payment_gateway_initialize_tokenization.return_value = (
+ PaymentGatewayInitializeTokenizationResponseData(
+ result=PaymentGatewayInitializeTokenizationResult.FAILED_TO_INITIALIZE,
+ error=error_message,
+ data=None,
+ )
+ )
+ expected_id = "test_id"
+
+ # when
+ response = user_api_client.post_graphql(
+ PAYMENT_GATEWAY_INITIALIZE_TOKENIZATION,
+ variables={
+ "id": expected_id,
+ "channel": channel_USD.slug,
+ "data": None,
+ },
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["paymentGatewayInitializeTokenization"]["result"] == (
+ PaymentGatewayInitializeTokenizationResultEnum.FAILED_TO_INITIALIZE.name
+ )
+ assert len(content["data"]["paymentGatewayInitializeTokenization"]["errors"]) == 1
+ error = content["data"]["paymentGatewayInitializeTokenization"]["errors"][0]
+ assert (
+ error["code"]
+ == PaymentGatewayInitializeTokenizationErrorCode.GATEWAY_ERROR.name
+ )
+ assert error["message"] == error_message
+
+ mocked_is_event_active_for_any_plugin.assert_called_once_with(
+ "payment_gateway_initialize_tokenization"
+ )
+ mocked_payment_gateway_initialize_tokenization.assert_called_once_with(
+ request_data=PaymentGatewayInitializeTokenizationRequestData(
+ user=user_api_client.user,
+ channel=channel_USD,
+ app_identifier=expected_id,
+ data=None,
+ )
+ )
diff --git a/saleor/graphql/payment/tests/mutations/test_payment_method_initialize_tokenization.py b/saleor/graphql/payment/tests/mutations/test_payment_method_initialize_tokenization.py
new file mode 100644
index 0000000000..6f2ef4e951
--- /dev/null
+++ b/saleor/graphql/payment/tests/mutations/test_payment_method_initialize_tokenization.py
@@ -0,0 +1,288 @@
+from unittest.mock import patch
+
+import pytest
+
+from .....payment import TokenizedPaymentFlow
+from .....payment.interface import (
+ PaymentMethodInitializeTokenizationRequestData,
+ PaymentMethodTokenizationResponseData,
+ PaymentMethodTokenizationResult,
+)
+from .....plugins.manager import PluginsManager
+from .....plugins.webhook.utils import to_payment_app_id
+from ....core.enums import PaymentMethodInitializeTokenizationErrorCode
+from ....tests.utils import assert_no_permission, get_graphql_content
+from ...enums import PaymentMethodTokenizationResultEnum, TokenizedPaymentFlowEnum
+
+PAYMENT_METHOD_INITIALIZE_TOKENIZATION = """
+mutation PaymentMethodInitializeTokenization(
+$id: String!, $channel: String!, $data: JSON,
+$paymentFlowToSupport: TokenizedPaymentFlowEnum!){
+ paymentMethodInitializeTokenization(
+ id: $id, channel: $channel, data: $data, paymentFlowToSupport: $paymentFlowToSupport
+ ){
+ result
+ data
+ id
+ errors{
+ field
+ code
+ message
+ }
+ }
+}
+"""
+
+
+ "expected_input_data, expected_output_data",
+ [
+ (None, None),
+ (None, {"foo": "bar1"}),
+ ({"foo": "bar2"}, None),
+ ({"foo": "bar3"}, {"foo": "bar4"}),
+ ],
+)
[email protected](PluginsManager, "payment_method_initialize_tokenization")
[email protected](PluginsManager, "is_event_active_for_any_plugin")
+def test_payment_method_initialize_tokenization(
+ mocked_is_event_active_for_any_plugin,
+ mocked_payment_method_initialize_tokenization,
+ expected_input_data,
+ expected_output_data,
+ user_api_client,
+ channel_USD,
+ app,
+):
+ # given
+ expected_payment_method_id = to_payment_app_id(app, "test_id")
+ mocked_is_event_active_for_any_plugin.return_value = True
+ mocked_payment_method_initialize_tokenization.return_value = (
+ PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.SUCCESSFULLY_TOKENIZED,
+ id=expected_payment_method_id,
+ error=None,
+ data=expected_output_data,
+ )
+ )
+ expected_id = "test_id"
+
+ # when
+ response = user_api_client.post_graphql(
+ PAYMENT_METHOD_INITIALIZE_TOKENIZATION,
+ variables={
+ "id": expected_id,
+ "channel": channel_USD.slug,
+ "data": expected_input_data,
+ "paymentFlowToSupport": TokenizedPaymentFlowEnum.INTERACTIVE.name,
+ },
+ )
+
+ # then
+ content = get_graphql_content(response)
+ response_data = content["data"]["paymentMethodInitializeTokenization"]
+ assert response_data["result"] == (
+ PaymentMethodTokenizationResultEnum.SUCCESSFULLY_TOKENIZED.name
+ )
+ assert response_data["data"] == expected_output_data
+ assert response_data["id"] == expected_payment_method_id
+ mocked_is_event_active_for_any_plugin.assert_called_once_with(
+ "payment_method_initialize_tokenization"
+ )
+ mocked_payment_method_initialize_tokenization.assert_called_once_with(
+ request_data=PaymentMethodInitializeTokenizationRequestData(
+ user=user_api_client.user,
+ channel=channel_USD,
+ app_identifier=expected_id,
+ data=expected_input_data,
+ payment_flow_to_support=TokenizedPaymentFlow.INTERACTIVE,
+ )
+ )
+
+
[email protected](PluginsManager, "payment_method_initialize_tokenization")
[email protected](PluginsManager, "is_event_active_for_any_plugin")
+def test_payment_method_initialize_tokenization_called_by_anonymous_user(
+ mocked_is_event_active_for_any_plugin,
+ mocked_payment_method_initialize_tokenization,
+ api_client,
+ channel_USD,
+):
+ # given
+ expected_id = "test_id"
+
+ # when
+ response = api_client.post_graphql(
+ PAYMENT_METHOD_INITIALIZE_TOKENIZATION,
+ variables={
+ "id": expected_id,
+ "channel": channel_USD.slug,
+ "paymentFlowToSupport": TokenizedPaymentFlowEnum.INTERACTIVE.name,
+ },
+ )
+
+ # then
+ assert_no_permission(response)
+
+ assert not mocked_is_event_active_for_any_plugin.called
+ assert not mocked_payment_method_initialize_tokenization.called
+
+
[email protected](PluginsManager, "payment_method_initialize_tokenization")
[email protected](PluginsManager, "is_event_active_for_any_plugin")
+def test_payment_method_initialize_tokenization_called_by_app(
+ mocked_is_event_active_for_any_plugin,
+ mocked_payment_method_initialize_tokenization,
+ app_api_client,
+ channel_USD,
+):
+ # given
+ expected_id = "test_id"
+
+ # when
+ response = app_api_client.post_graphql(
+ PAYMENT_METHOD_INITIALIZE_TOKENIZATION,
+ variables={
+ "id": expected_id,
+ "channel": channel_USD.slug,
+ "paymentFlowToSupport": TokenizedPaymentFlowEnum.INTERACTIVE.name,
+ },
+ )
+
+ # then
+ assert_no_permission(response)
+
+ assert not mocked_is_event_active_for_any_plugin.called
+ assert not mocked_payment_method_initialize_tokenization.called
+
+
[email protected](PluginsManager, "payment_method_initialize_tokenization")
[email protected](PluginsManager, "is_event_active_for_any_plugin")
+def test_payment_method_initialize_tokenization_not_app_or_plugin_subscribed_to_event(
+ mocked_is_event_active_for_any_plugin,
+ mocked_payment_method_initialize_tokenization,
+ user_api_client,
+ channel_USD,
+):
+ # given
+ mocked_is_event_active_for_any_plugin.return_value = False
+
+ expected_id = "test_id"
+
+ # when
+ response = user_api_client.post_graphql(
+ PAYMENT_METHOD_INITIALIZE_TOKENIZATION,
+ variables={
+ "id": expected_id,
+ "channel": channel_USD.slug,
+ "paymentFlowToSupport": TokenizedPaymentFlowEnum.INTERACTIVE.name,
+ },
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert len(content["data"]["paymentMethodInitializeTokenization"]["errors"]) == 1
+ assert (
+ content["data"]["paymentMethodInitializeTokenization"]["errors"][0]["code"]
+ == PaymentMethodInitializeTokenizationErrorCode.NOT_FOUND.name
+ )
+ assert content["data"]["paymentMethodInitializeTokenization"]["result"] == (
+ PaymentMethodTokenizationResultEnum.FAILED_TO_DELIVER.name
+ )
+
+ mocked_is_event_active_for_any_plugin.assert_called_once_with(
+ "payment_method_initialize_tokenization"
+ )
+ assert not mocked_payment_method_initialize_tokenization.called
+
+
[email protected](PluginsManager, "payment_method_initialize_tokenization")
[email protected](PluginsManager, "is_event_active_for_any_plugin")
+def test_payment_method_initialize_tokenization_incorrect_channel(
+ mocked_is_event_active_for_any_plugin,
+ mocked_payment_method_initialize_tokenization,
+ user_api_client,
+):
+ # given
+ expected_id = "test_id"
+
+ # when
+ response = user_api_client.post_graphql(
+ PAYMENT_METHOD_INITIALIZE_TOKENIZATION,
+ variables={
+ "id": expected_id,
+ "channel": "non-exiting-channel",
+ "paymentFlowToSupport": TokenizedPaymentFlowEnum.INTERACTIVE.name,
+ },
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert len(content["data"]["paymentMethodInitializeTokenization"]["errors"]) == 1
+ assert (
+ content["data"]["paymentMethodInitializeTokenization"]["errors"][0]["code"]
+ == PaymentMethodInitializeTokenizationErrorCode.NOT_FOUND.name
+ )
+ assert content["data"]["paymentMethodInitializeTokenization"]["result"] == (
+ PaymentMethodTokenizationResultEnum.FAILED_TO_DELIVER.name
+ )
+
+ assert not mocked_is_event_active_for_any_plugin.called
+ assert not mocked_payment_method_initialize_tokenization.called
+
+
[email protected](PluginsManager, "payment_method_initialize_tokenization")
[email protected](PluginsManager, "is_event_active_for_any_plugin")
+def test_payment_method_initialize_tokenization_failure_from_app(
+ mocked_is_event_active_for_any_plugin,
+ mocked_payment_method_initialize_tokenization,
+ user_api_client,
+ channel_USD,
+):
+ # given
+ error_message = "Error message"
+ mocked_is_event_active_for_any_plugin.return_value = True
+ mocked_payment_method_initialize_tokenization.return_value = (
+ PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.FAILED_TO_TOKENIZE,
+ error=error_message,
+ data=None,
+ )
+ )
+ expected_id = "test_id"
+
+ # when
+ response = user_api_client.post_graphql(
+ PAYMENT_METHOD_INITIALIZE_TOKENIZATION,
+ variables={
+ "id": expected_id,
+ "channel": channel_USD.slug,
+ "data": None,
+ "paymentFlowToSupport": TokenizedPaymentFlowEnum.INTERACTIVE.name,
+ },
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["paymentMethodInitializeTokenization"]["result"] == (
+ PaymentMethodTokenizationResultEnum.FAILED_TO_TOKENIZE.name
+ )
+ assert len(content["data"]["paymentMethodInitializeTokenization"]["errors"]) == 1
+ error = content["data"]["paymentMethodInitializeTokenization"]["errors"][0]
+ assert (
+ error["code"] == PaymentMethodInitializeTokenizationErrorCode.GATEWAY_ERROR.name
+ )
+ assert error["message"] == error_message
+
+ mocked_is_event_active_for_any_plugin.assert_called_once_with(
+ "payment_method_initialize_tokenization"
+ )
+ mocked_payment_method_initialize_tokenization.assert_called_once_with(
+ request_data=PaymentMethodInitializeTokenizationRequestData(
+ user=user_api_client.user,
+ channel=channel_USD,
+ app_identifier=expected_id,
+ data=None,
+ payment_flow_to_support=TokenizedPaymentFlow.INTERACTIVE,
+ )
+ )
diff --git a/saleor/graphql/payment/tests/mutations/test_payment_method_process_tokenization.py b/saleor/graphql/payment/tests/mutations/test_payment_method_process_tokenization.py
new file mode 100644
index 0000000000..2f4691361c
--- /dev/null
+++ b/saleor/graphql/payment/tests/mutations/test_payment_method_process_tokenization.py
@@ -0,0 +1,268 @@
+from unittest.mock import patch
+
+import pytest
+
+from .....payment.interface import (
+ PaymentMethodProcessTokenizationRequestData,
+ PaymentMethodTokenizationResponseData,
+ PaymentMethodTokenizationResult,
+)
+from .....plugins.manager import PluginsManager
+from ....core.enums import PaymentMethodProcessTokenizationErrorCode
+from ....tests.utils import assert_no_permission, get_graphql_content
+from ...enums import PaymentMethodTokenizationResultEnum
+
+PAYMENT_METHOD_PROCESS_TOKENIZATION = """
+mutation PaymentMethodProcessTokenization(
+$id: String!, $channel: String!, $data: JSON){
+ paymentMethodProcessTokenization(id: $id, channel: $channel, data: $data){
+ result
+ data
+ id
+ errors{
+ field
+ code
+ message
+ }
+ }
+}
+"""
+
+
+ "expected_input_data, expected_output_data",
+ [
+ (None, None),
+ (None, {"foo": "bar1"}),
+ ({"foo": "bar2"}, None),
+ ({"foo": "bar3"}, {"foo": "bar4"}),
+ ],
+)
[email protected](PluginsManager, "payment_method_process_tokenization")
[email protected](PluginsManager, "is_event_active_for_any_plugin")
+def test_payment_method_process_tokenization(
+ mocked_is_event_active_for_any_plugin,
+ mocked_payment_method_process_tokenization,
+ expected_input_data,
+ expected_output_data,
+ user_api_client,
+ channel_USD,
+ app,
+):
+ # given
+ expected_payment_method_id = "test_id"
+ mocked_is_event_active_for_any_plugin.return_value = True
+ mocked_payment_method_process_tokenization.return_value = (
+ PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.SUCCESSFULLY_TOKENIZED,
+ id=expected_payment_method_id,
+ error=None,
+ data=expected_output_data,
+ )
+ )
+
+ expected_id = "test_id"
+
+ # when
+ response = user_api_client.post_graphql(
+ PAYMENT_METHOD_PROCESS_TOKENIZATION,
+ variables={
+ "id": expected_id,
+ "channel": channel_USD.slug,
+ "data": expected_input_data,
+ },
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ response_data = content["data"]["paymentMethodProcessTokenization"]
+ assert response_data["result"] == (
+ PaymentMethodTokenizationResultEnum.SUCCESSFULLY_TOKENIZED.name
+ )
+ assert response_data["data"] == expected_output_data
+ assert response_data["id"] == expected_payment_method_id
+ mocked_is_event_active_for_any_plugin.assert_called_once_with(
+ "payment_method_process_tokenization"
+ )
+ mocked_payment_method_process_tokenization.assert_called_once_with(
+ request_data=PaymentMethodProcessTokenizationRequestData(
+ user=user_api_client.user,
+ channel=channel_USD,
+ id=expected_id,
+ data=expected_input_data,
+ )
+ )
+
+
[email protected](PluginsManager, "payment_method_process_tokenization")
[email protected](PluginsManager, "is_event_active_for_any_plugin")
+def test_payment_method_process_tokenization_called_by_anonymous_user(
+ mocked_is_event_active_for_any_plugin,
+ mocked_payment_method_process_tokenization,
+ api_client,
+ channel_USD,
+ app,
+):
+ # given
+ expected_id = "test_id"
+
+ # when
+ response = api_client.post_graphql(
+ PAYMENT_METHOD_PROCESS_TOKENIZATION,
+ 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_payment_method_process_tokenization.called
+
+
[email protected](PluginsManager, "payment_method_process_tokenization")
[email protected](PluginsManager, "is_event_active_for_any_plugin")
+def test_payment_method_process_tokenization_called_by_app(
+ mocked_is_event_active_for_any_plugin,
+ mocked_payment_method_process_tokenization,
+ app_api_client,
+ channel_USD,
+ app,
+):
+ # given
+ expected_id = "test_id"
+
+ # when
+ response = app_api_client.post_graphql(
+ PAYMENT_METHOD_PROCESS_TOKENIZATION,
+ 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_payment_method_process_tokenization.called
+
+
[email protected](PluginsManager, "payment_method_process_tokenization")
[email protected](PluginsManager, "is_event_active_for_any_plugin")
+def test_payment_method_process_tokenization_not_app_or_plugin_subscribed_to_event(
+ mocked_is_event_active_for_any_plugin,
+ mocked_payment_method_process_tokenization,
+ user_api_client,
+ channel_USD,
+ app,
+):
+ # given
+ mocked_is_event_active_for_any_plugin.return_value = False
+
+ expected_id = "test_id"
+
+ # when
+ response = user_api_client.post_graphql(
+ PAYMENT_METHOD_PROCESS_TOKENIZATION,
+ variables={"id": expected_id, "channel": channel_USD.slug},
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert len(content["data"]["paymentMethodProcessTokenization"]["errors"]) == 1
+ assert (
+ content["data"]["paymentMethodProcessTokenization"]["errors"][0]["code"]
+ == PaymentMethodProcessTokenizationErrorCode.NOT_FOUND.name
+ )
+ assert content["data"]["paymentMethodProcessTokenization"]["result"] == (
+ PaymentMethodTokenizationResultEnum.FAILED_TO_DELIVER.name
+ )
+
+ mocked_is_event_active_for_any_plugin.assert_called_once_with(
+ "payment_method_process_tokenization"
+ )
+ assert not mocked_payment_method_process_tokenization.called
+
+
[email protected](PluginsManager, "payment_method_process_tokenization")
[email protected](PluginsManager, "is_event_active_for_any_plugin")
+def test_payment_method_process_tokenization_incorrect_channel(
+ mocked_is_event_active_for_any_plugin,
+ mocked_payment_method_process_tokenization,
+ user_api_client,
+ app,
+):
+ # given
+ expected_id = "test_id"
+
+ # when
+ response = user_api_client.post_graphql(
+ PAYMENT_METHOD_PROCESS_TOKENIZATION,
+ variables={"id": expected_id, "channel": "non-exiting-channel"},
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert len(content["data"]["paymentMethodProcessTokenization"]["errors"]) == 1
+ assert (
+ content["data"]["paymentMethodProcessTokenization"]["errors"][0]["code"]
+ == PaymentMethodProcessTokenizationErrorCode.NOT_FOUND.name
+ )
+ assert content["data"]["paymentMethodProcessTokenization"]["result"] == (
+ PaymentMethodTokenizationResultEnum.FAILED_TO_DELIVER.name
+ )
+
+ assert not mocked_is_event_active_for_any_plugin.called
+ assert not mocked_payment_method_process_tokenization.called
+
+
[email protected](PluginsManager, "payment_method_process_tokenization")
[email protected](PluginsManager, "is_event_active_for_any_plugin")
+def test_payment_method_process_tokenization_failure_from_app(
+ mocked_is_event_active_for_any_plugin,
+ mocked_payment_method_process_tokenization,
+ user_api_client,
+ channel_USD,
+ app,
+):
+ # given
+ error_message = "Error message"
+ mocked_is_event_active_for_any_plugin.return_value = True
+ mocked_payment_method_process_tokenization.return_value = (
+ PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.FAILED_TO_TOKENIZE,
+ error=error_message,
+ data=None,
+ )
+ )
+ expected_id = "test_id"
+
+ # when
+ response = user_api_client.post_graphql(
+ PAYMENT_METHOD_PROCESS_TOKENIZATION,
+ variables={
+ "id": expected_id,
+ "channel": channel_USD.slug,
+ "data": None,
+ },
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["paymentMethodProcessTokenization"]["result"] == (
+ PaymentMethodTokenizationResultEnum.FAILED_TO_TOKENIZE.name
+ )
+ assert len(content["data"]["paymentMethodProcessTokenization"]["errors"]) == 1
+ error = content["data"]["paymentMethodProcessTokenization"]["errors"][0]
+ assert error["code"] == PaymentMethodProcessTokenizationErrorCode.GATEWAY_ERROR.name
+ assert error["message"] == error_message
+
+ mocked_is_event_active_for_any_plugin.assert_called_once_with(
+ "payment_method_process_tokenization"
+ )
+ mocked_payment_method_process_tokenization.assert_called_once_with(
+ request_data=PaymentMethodProcessTokenizationRequestData(
+ user=user_api_client.user,
+ channel=channel_USD,
+ id=expected_id,
+ data=None,
+ )
+ )
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
index 04857a010b..a1c3aaa91b 100644
--- 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
@@ -147,7 +147,7 @@ def test_stored_payment_method_request_delete_called_by_app(
@patch.object(PluginsManager, "stored_payment_method_request_delete")
@patch.object(PluginsManager, "is_event_active_for_any_plugin")
-def test_stored_payment_method_request_delete_called_by_anynoums_user(
+def test_stored_payment_method_request_delete_called_by_anonymous_user(
mocked_is_event_active_for_any_plugin,
mocked_stored_payment_method_request_delete,
api_client,
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 462abdb776..c68c24b94b 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -2296,6 +2296,9 @@ enum WebhookEventTypeEnum @doc(category: "Webhooks") {
TRANSACTION_PROCESS_SESSION
LIST_STORED_PAYMENT_METHODS
STORED_PAYMENT_METHOD_DELETE_REQUESTED
+ PAYMENT_GATEWAY_INITIALIZE_TOKENIZATION_SESSION
+ PAYMENT_METHOD_INITIALIZE_TOKENIZATION_SESSION
+ PAYMENT_METHOD_PROCESS_TOKENIZATION_SESSION
}
"""Synchronous webhook event."""
@@ -2384,6 +2387,9 @@ enum WebhookEventTypeSyncEnum @doc(category: "Webhooks") {
TRANSACTION_PROCESS_SESSION
LIST_STORED_PAYMENT_METHODS
STORED_PAYMENT_METHOD_DELETE_REQUESTED
+ PAYMENT_GATEWAY_INITIALIZE_TOKENIZATION_SESSION
+ PAYMENT_METHOD_INITIALIZE_TOKENIZATION_SESSION
+ PAYMENT_METHOD_PROCESS_TOKENIZATION_SESSION
}
"""Asynchronous webhook event."""
@@ -10194,7 +10200,9 @@ type Checkout implements Node & ObjectWithMetadata @doc(category: "Checkout") {
updatedAt: DateTime!
lastChange: DateTime! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `updatedAt` instead.")
- """The user assigned to the checkout."""
+ """
+ The user assigned to the checkout. Requires one of the following permissions: MANAGE_USERS, HANDLE_PAYMENTS, OWNER.
+ """
user: User
"""The channel for which checkout was created."""
@@ -11005,7 +11013,7 @@ type Order implements Node & ObjectWithMetadata @doc(category: "Orders") {
status: OrderStatus!
"""
- User who placed the order. This field is set only for orders placed by authenticated users. Can be fetched for orders created in Saleor 3.2 and later, for other orders requires one of the following permissions: MANAGE_USERS, MANAGE_ORDERS, OWNER.
+ User who placed the order. This field is set only for orders placed by authenticated users. Can be fetched for orders created in Saleor 3.2 and later, for other orders requires one of the following permissions: MANAGE_USERS, MANAGE_ORDERS, HANDLE_PAYMENTS, OWNER.
"""
user: User
@@ -15678,6 +15686,82 @@ type Mutation {
id: ID!
): StoredPaymentMethodRequestDelete @doc(category: "Payments") @webhookEventsInfo(asyncEvents: [], syncEvents: [STORED_PAYMENT_METHOD_DELETE_REQUESTED])
+ """
+ Initializes payment gateway for tokenizing payment method session.
+
+ 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:
+ - PAYMENT_GATEWAY_INITIALIZE_TOKENIZATION_SESSION (sync): The customer requested to initialize payment gateway for tokenization.
+ """
+ paymentGatewayInitializeTokenization(
+ """Slug of a channel related to tokenization request."""
+ channel: String!
+
+ """The data that will be passed to the payment gateway."""
+ data: JSON
+
+ """The identifier of the payment gateway app to initialize tokenization."""
+ id: String!
+ ): PaymentGatewayInitializeTokenization @doc(category: "Payments") @webhookEventsInfo(asyncEvents: [], syncEvents: [PAYMENT_GATEWAY_INITIALIZE_TOKENIZATION_SESSION])
+
+ """
+ Tokenize payment method.
+
+ 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:
+ - PAYMENT_METHOD_INITIALIZE_TOKENIZATION_SESSION (sync): The customer requested to tokenize payment method.
+ """
+ paymentMethodInitializeTokenization(
+ """Slug of a channel related to tokenization request."""
+ channel: String!
+
+ """The data that will be passed to the payment gateway."""
+ data: JSON
+
+ """
+ The identifier of the payment gateway app to initialize payment method tokenization.
+ """
+ id: String!
+
+ """The payment flow that the tokenized payment method should support."""
+ paymentFlowToSupport: TokenizedPaymentFlowEnum!
+ ): PaymentMethodInitializeTokenization @doc(category: "Payments") @webhookEventsInfo(asyncEvents: [], syncEvents: [PAYMENT_METHOD_INITIALIZE_TOKENIZATION_SESSION])
+
+ """
+ Tokenize payment method.
+
+ 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:
+ - PAYMENT_METHOD_PROCESS_TOKENIZATION_SESSION (sync): The customer continues payment method tokenization.
+ """
+ paymentMethodProcessTokenization(
+ """Slug of a channel related to tokenization request."""
+ channel: String!
+
+ """The data that will be passed to the payment gateway."""
+ data: JSON
+
+ """
+ The identifier of the payment gateway app to process payment method tokenization.
+ """
+ id: String!
+ ): PaymentMethodProcessTokenization @doc(category: "Payments") @webhookEventsInfo(asyncEvents: [], syncEvents: [PAYMENT_METHOD_PROCESS_TOKENIZATION_SESSION])
+
"""
Creates a new page.
@@ -23317,6 +23401,173 @@ enum StoredPaymentMethodRequestDeleteErrorCode @doc(category: "Payments") {
GATEWAY_ERROR
}
+"""
+Initializes payment gateway for tokenizing payment method session.
+
+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:
+- PAYMENT_GATEWAY_INITIALIZE_TOKENIZATION_SESSION (sync): The customer requested to initialize payment gateway for tokenization.
+"""
+type PaymentGatewayInitializeTokenization @doc(category: "Payments") @webhookEventsInfo(asyncEvents: [], syncEvents: [PAYMENT_GATEWAY_INITIALIZE_TOKENIZATION_SESSION]) {
+ """A status of the payment gateway initialization."""
+ result: PaymentGatewayInitializeTokenizationResult!
+
+ """A data returned by payment app."""
+ data: JSON
+ errors: [PaymentGatewayInitializeTokenizationError!]!
+}
+
+"""
+Result of initialize payment gateway for tokenization of payment method.
+
+ The result of initialize payment gateway for tokenization of payment method.
+ SUCCESSFULLY_INITIALIZED - The payment gateway was successfully initialized.
+ FAILED_TO_INITIALIZE - The payment gateway was not initialized.
+ FAILED_TO_DELIVER - The request to initialize payment gateway was not delivered.
+"""
+enum PaymentGatewayInitializeTokenizationResult @doc(category: "Payments") {
+ SUCCESSFULLY_INITIALIZED
+ FAILED_TO_INITIALIZE
+ FAILED_TO_DELIVER
+}
+
+type PaymentGatewayInitializeTokenizationError @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: PaymentGatewayInitializeTokenizationErrorCode!
+}
+
+"""An enumeration."""
+enum PaymentGatewayInitializeTokenizationErrorCode @doc(category: "Payments") {
+ GRAPHQL_ERROR
+ INVALID
+ NOT_FOUND
+ CHANNEL_INACTIVE
+ GATEWAY_ERROR
+}
+
+"""
+Tokenize payment method.
+
+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:
+- PAYMENT_METHOD_INITIALIZE_TOKENIZATION_SESSION (sync): The customer requested to tokenize payment method.
+"""
+type PaymentMethodInitializeTokenization @doc(category: "Payments") @webhookEventsInfo(asyncEvents: [], syncEvents: [PAYMENT_METHOD_INITIALIZE_TOKENIZATION_SESSION]) {
+ """A status of the payment method tokenization."""
+ result: PaymentMethodTokenizationResult!
+
+ """The identifier of the payment method."""
+ id: String
+
+ """A data returned by the payment app."""
+ data: JSON
+ errors: [PaymentMethodInitializeTokenizationError!]!
+}
+
+"""
+Result of tokenization of payment method.
+
+ SUCCESSFULLY_TOKENIZED - The payment method was successfully tokenized.
+ ADDITIONAL_ACTION_REQUIRED - The additional action is required to tokenize payment
+ method.
+ PENDING - The payment method is pending tokenization.
+ FAILED_TO_TOKENIZE - The payment method was not tokenized.
+ FAILED_TO_DELIVER - The request to tokenize payment method was not delivered.
+"""
+enum PaymentMethodTokenizationResult @doc(category: "Payments") {
+ SUCCESSFULLY_TOKENIZED
+ PENDING
+ ADDITIONAL_ACTION_REQUIRED
+ FAILED_TO_TOKENIZE
+ FAILED_TO_DELIVER
+}
+
+type PaymentMethodInitializeTokenizationError @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: PaymentMethodInitializeTokenizationErrorCode!
+}
+
+"""An enumeration."""
+enum PaymentMethodInitializeTokenizationErrorCode @doc(category: "Payments") {
+ GRAPHQL_ERROR
+ INVALID
+ NOT_FOUND
+ CHANNEL_INACTIVE
+ GATEWAY_ERROR
+}
+
+"""
+Tokenize payment method.
+
+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:
+- PAYMENT_METHOD_PROCESS_TOKENIZATION_SESSION (sync): The customer continues payment method tokenization.
+"""
+type PaymentMethodProcessTokenization @doc(category: "Payments") @webhookEventsInfo(asyncEvents: [], syncEvents: [PAYMENT_METHOD_PROCESS_TOKENIZATION_SESSION]) {
+ """A status of the payment method tokenization."""
+ result: PaymentMethodTokenizationResult!
+
+ """The identifier of the payment method."""
+ id: String
+
+ """A data returned by the payment app."""
+ data: JSON
+ errors: [PaymentMethodProcessTokenizationError!]!
+}
+
+type PaymentMethodProcessTokenizationError @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: PaymentMethodProcessTokenizationErrorCode!
+}
+
+"""An enumeration."""
+enum PaymentMethodProcessTokenizationErrorCode @doc(category: "Payments") {
+ GRAPHQL_ERROR
+ INVALID
+ NOT_FOUND
+ CHANNEL_INACTIVE
+ GATEWAY_ERROR
+}
+
"""
Creates a new page.
@@ -33231,7 +33482,7 @@ type PaymentGatewayInitializeSession implements Event @doc(category: "Payments")
"""Checkout or order"""
sourceObject: OrderOrCheckout!
- """Payment gateway data in JSON format, recieved from storefront."""
+ """Payment gateway data in JSON format, received from storefront."""
data: JSON
"""Amount requested for initializing the payment gateway."""
@@ -33420,6 +33671,104 @@ type StoredPaymentMethodDeleteRequested implements Event @doc(category: "Payment
channel: Channel!
}
+"""
+Event sent to initialize a new session in payment gateway to store the 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 PaymentGatewayInitializeTokenizationSession 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 related to the requested action."""
+ user: User!
+
+ """Channel related to the requested action."""
+ channel: Channel!
+
+ """Payment gateway data in JSON format, received from storefront."""
+ data: JSON
+}
+
+"""
+Event sent when user requests a tokenization of 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 PaymentMethodInitializeTokenizationSession 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 related to the requested action."""
+ user: User!
+
+ """Channel related to the requested action."""
+ channel: Channel!
+
+ """Payment gateway data in JSON format, received from storefront."""
+ data: JSON
+
+ """The payment flow that the tokenized payment method should support."""
+ paymentFlowToSupport: TokenizedPaymentFlowEnum!
+}
+
+"""
+Event sent when user continues a tokenization of 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 PaymentMethodProcessTokenizationSession 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 related to the requested action."""
+ user: User!
+
+ """Channel related to the requested action."""
+ channel: Channel!
+
+ """Payment gateway data in JSON format, received from storefront."""
+ data: JSON
+
+ """
+ The ID returned by app from `PAYMENT_METHOD_INITIALIZE_TOKENIZATION_SESSION` webhook.
+ """
+ id: String!
+}
+
"""_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 346f0edc29..cf7d7a2abc 100644
--- a/saleor/graphql/webhook/subscription_types.py
+++ b/saleor/graphql/webhook/subscription_types.py
@@ -15,6 +15,9 @@ from ...order.utils import get_all_shipping_methods_for_order
from ...page.models import PageTranslation
from ...payment.interface import (
ListStoredPaymentMethodsRequestData,
+ PaymentMethodInitializeTokenizationRequestData,
+ PaymentMethodProcessTokenizationRequestData,
+ PaymentMethodTokenizationBaseRequestData,
StoredPaymentMethodRequestDeleteData,
TransactionActionData,
TransactionSessionData,
@@ -66,7 +69,7 @@ from ..core.types import NonNullList, SubscriptionObjectType
from ..core.types.order_or_checkout import OrderOrCheckout
from ..order.dataloaders import OrderByIdLoader
from ..order.types import Order, OrderGrantedRefund
-from ..payment.enums import TransactionActionEnum
+from ..payment.enums import TokenizedPaymentFlowEnum, TransactionActionEnum
from ..payment.types import TransactionItem
from ..plugins.dataloaders import plugin_manager_promise_callback
from ..product.dataloaders import ProductVariantByIdLoader
@@ -1781,7 +1784,7 @@ class PaymentGatewayInitializeSession(SubscriptionObjectType):
)
data = graphene.Field(
JSON,
- description="Payment gateway data in JSON format, recieved from storefront.",
+ description="Payment gateway data in JSON format, received from storefront.",
)
amount = graphene.Field(
PositiveDecimal,
@@ -2046,6 +2049,127 @@ class StoredPaymentMethodDeleteRequested(SubscriptionObjectType):
return payment_method_data.channel
+class PaymentMethodTokenizationBase(AbstractType):
+ user = graphene.Field(
+ UserType,
+ description="The user related to the requested action.",
+ required=True,
+ )
+ channel = graphene.Field(
+ "saleor.graphql.channel.types.Channel",
+ description="Channel related to the requested action.",
+ required=True,
+ )
+ data = graphene.Field(
+ JSON,
+ description="Payment gateway data in JSON format, received from storefront.",
+ )
+
+ @classmethod
+ def resolve_channel(
+ cls,
+ root: tuple[str, PaymentMethodTokenizationBaseRequestData],
+ _info: ResolveInfo,
+ ):
+ _, payment_method_data = root
+ return payment_method_data.channel
+
+ @classmethod
+ def resolve_user(
+ cls,
+ root: tuple[str, PaymentMethodTokenizationBaseRequestData],
+ _info: ResolveInfo,
+ ):
+ _, payment_method_data = root
+ return payment_method_data.user
+
+ @classmethod
+ def resolve_data(
+ cls,
+ root: tuple[str, PaymentMethodTokenizationBaseRequestData],
+ _info: ResolveInfo,
+ ):
+ _, payment_method_data = root
+ return payment_method_data.data
+
+
+class PaymentGatewayInitializeTokenizationSession(
+ SubscriptionObjectType, PaymentMethodTokenizationBase
+):
+ class Meta:
+ root_type = None
+ enable_dry_run = False
+ interfaces = (Event,)
+ description = (
+ "Event sent to initialize a new session in payment gateway to store the "
+ "payment method. " + ADDED_IN_316 + PREVIEW_FEATURE
+ )
+ doc_category = DOC_CATEGORY_PAYMENTS
+
+
+class PaymentMethodInitializeTokenizationSession(
+ SubscriptionObjectType, PaymentMethodTokenizationBase
+):
+ payment_flow_to_support = TokenizedPaymentFlowEnum(
+ description=(
+ "The payment flow that the tokenized payment method should support."
+ ),
+ required=True,
+ )
+
+ class Meta:
+ root_type = None
+ enable_dry_run = False
+ interfaces = (Event,)
+ description = (
+ "Event sent when user requests a tokenization of payment method."
+ + ADDED_IN_316
+ + PREVIEW_FEATURE
+ )
+ doc_category = DOC_CATEGORY_PAYMENTS
+
+ @classmethod
+ def resolve_payment_flow_to_support(
+ cls,
+ root: tuple[str, PaymentMethodInitializeTokenizationRequestData],
+ _info: ResolveInfo,
+ ):
+ _, payment_method_data = root
+ return payment_method_data.payment_flow_to_support
+
+
+class PaymentMethodProcessTokenizationSession(
+ SubscriptionObjectType, PaymentMethodTokenizationBase
+):
+ id = graphene.String(
+ description=(
+ "The ID returned by app from "
+ "`PAYMENT_METHOD_INITIALIZE_TOKENIZATION_SESSION` webhook."
+ ),
+ required=True,
+ )
+
+ class Meta:
+ root_type = None
+ enable_dry_run = False
+ interfaces = (Event,)
+ description = (
+ "Event sent when user continues a tokenization of payment method."
+ + ADDED_IN_316
+ + PREVIEW_FEATURE
+ )
+ doc_category = DOC_CATEGORY_PAYMENTS
+
+ @classmethod
+ def resolve_id(
+ cls,
+ root: tuple[str, PaymentMethodProcessTokenizationRequestData],
+ _info: ResolveInfo,
+ ):
+ _, payment_method_data = root
+ return payment_method_data.id
+
+
class TranslationTypes(Union):
class Meta:
types = tuple(TRANSLATIONS_TYPES_MAP.values())
@@ -2577,4 +2701,13 @@ WEBHOOK_TYPES_MAP = {
WebhookEventSyncType.STORED_PAYMENT_METHOD_DELETE_REQUESTED: (
StoredPaymentMethodDeleteRequested
),
+ WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_TOKENIZATION_SESSION: (
+ PaymentGatewayInitializeTokenizationSession
+ ),
+ WebhookEventSyncType.PAYMENT_METHOD_INITIALIZE_TOKENIZATION_SESSION: (
+ PaymentMethodInitializeTokenizationSession
+ ),
+ WebhookEventSyncType.PAYMENT_METHOD_PROCESS_TOKENIZATION_SESSION: (
+ PaymentMethodProcessTokenizationSession
+ ),
}
diff --git a/saleor/payment/error_codes.py b/saleor/payment/error_codes.py
index 076ae064a3..ba7d9bbdc3 100644
--- a/saleor/payment/error_codes.py
+++ b/saleor/payment/error_codes.py
@@ -98,3 +98,27 @@ class StoredPaymentMethodRequestDeleteErrorCode(Enum):
NOT_FOUND = "not_found"
CHANNEL_INACTIVE = "channel_inactive"
GATEWAY_ERROR = "gateway_error"
+
+
+class PaymentGatewayInitializeTokenizationErrorCode(Enum):
+ GRAPHQL_ERROR = "graphql_error"
+ INVALID = "invalid"
+ NOT_FOUND = "not_found"
+ CHANNEL_INACTIVE = "channel_inactive"
+ GATEWAY_ERROR = "gateway_error"
+
+
+class PaymentMethodInitializeTokenizationErrorCode(Enum):
+ GRAPHQL_ERROR = "graphql_error"
+ INVALID = "invalid"
+ NOT_FOUND = "not_found"
+ CHANNEL_INACTIVE = "channel_inactive"
+ GATEWAY_ERROR = "gateway_error"
+
+
+class PaymentMethodProcessTokenizationErrorCode(Enum):
+ GRAPHQL_ERROR = "graphql_error"
+ INVALID = "invalid"
+ NOT_FOUND = "not_found"
+ CHANNEL_INACTIVE = "channel_inactive"
+ GATEWAY_ERROR = "gateway_error"
diff --git a/saleor/payment/interface.py b/saleor/payment/interface.py
index 4efff56a6b..a01134512d 100644
--- a/saleor/payment/interface.py
+++ b/saleor/payment/interface.py
@@ -173,6 +173,96 @@ class TransactionSessionResult:
error: Optional[str] = None
+@dataclass
+class PaymentMethodTokenizationBaseRequestData:
+ channel: "Channel"
+ user: "User"
+ data: Optional[dict]
+
+
+@dataclass
+class PaymentMethodTokenizationBaseResponseData:
+ error: Optional[str]
+ data: Optional[dict]
+
+
+@dataclass
+class PaymentGatewayInitializeTokenizationRequestData(
+ PaymentMethodTokenizationBaseRequestData
+):
+ """Dataclass for storing the request information for payment app."""
+
+ app_identifier: str
+
+
+class PaymentGatewayInitializeTokenizationResult(str, Enum):
+ """Result of initialize payment gateway for tokenization of payment method.
+
+ The result of initialize payment gateway for tokenization of payment method.
+ SUCCESSFULLY_INITIALIZED - The payment gateway was successfully initialized.
+ FAILED_TO_INITIALIZE - The payment gateway was not initialized.
+ FAILED_TO_DELIVER - The request to initialize payment gateway was not delivered.
+ """
+
+ SUCCESSFULLY_INITIALIZED = "successfully_initialized"
+ FAILED_TO_INITIALIZE = "failed_to_initialize"
+ FAILED_TO_DELIVER = "failed_to_deliver"
+
+
+@dataclass
+class PaymentGatewayInitializeTokenizationResponseData(
+ PaymentMethodTokenizationBaseResponseData
+):
+ """Dataclass for storing the response information from payment app."""
+
+ result: PaymentGatewayInitializeTokenizationResult
+
+
+@dataclass
+class PaymentMethodInitializeTokenizationRequestData(
+ PaymentMethodTokenizationBaseRequestData
+):
+ """Dataclass for storing the request information for payment app."""
+
+ app_identifier: str
+ payment_flow_to_support: str
+
+
+@dataclass
+class PaymentMethodProcessTokenizationRequestData(
+ PaymentMethodTokenizationBaseRequestData
+):
+ """Dataclass for storing the request information for payment app."""
+
+ id: str
+
+
+class PaymentMethodTokenizationResult(str, Enum):
+ """Result of tokenization of payment method.
+
+ SUCCESSFULLY_TOKENIZED - The payment method was successfully tokenized.
+ ADDITIONAL_ACTION_REQUIRED - The additional action is required to tokenize payment
+ method.
+ PENDING - The payment method is pending tokenization.
+ FAILED_TO_TOKENIZE - The payment method was not tokenized.
+ FAILED_TO_DELIVER - The request to tokenize payment method was not delivered.
+ """
+
+ SUCCESSFULLY_TOKENIZED = "successfully_tokenized"
+ PENDING = "pending"
+ ADDITIONAL_ACTION_REQUIRED = "additional_action_required"
+ FAILED_TO_TOKENIZE = "failed_to_tokenize"
+ FAILED_TO_DELIVER = "failed_to_deliver"
+
+
+@dataclass
+class PaymentMethodTokenizationResponseData(PaymentMethodTokenizationBaseResponseData):
+ """Dataclass for storing the response information from payment app."""
+
+ result: PaymentMethodTokenizationResult
+ id: Optional[str] = None
+
+
@dataclass
class PaymentMethodInfo:
"""Uniform way to represent payment method information."""
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index 45ab98b535..9d12a526a2 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -32,7 +32,12 @@ from ..payment.interface import (
ListStoredPaymentMethodsRequestData,
PaymentData,
PaymentGateway,
+ PaymentGatewayInitializeTokenizationRequestData,
+ PaymentGatewayInitializeTokenizationResponseData,
PaymentMethodData,
+ PaymentMethodInitializeTokenizationRequestData,
+ PaymentMethodProcessTokenizationRequestData,
+ PaymentMethodTokenizationResponseData,
StoredPaymentMethodRequestDeleteData,
StoredPaymentMethodRequestDeleteResponseData,
TransactionActionData,
@@ -705,6 +710,30 @@ class BasePlugin:
"StoredPaymentMethodRequestDeleteResponseData",
]
+ payment_gateway_initialize_tokenization: Callable[
+ [
+ "PaymentGatewayInitializeTokenizationRequestData",
+ "PaymentGatewayInitializeTokenizationResponseData",
+ ],
+ "PaymentGatewayInitializeTokenizationResponseData",
+ ]
+
+ payment_method_initialize_tokenization: Callable[
+ [
+ "PaymentMethodInitializeTokenizationRequestData",
+ "PaymentMethodTokenizationResponseData",
+ ],
+ "PaymentMethodTokenizationResponseData",
+ ]
+
+ payment_method_process_tokenization: Callable[
+ [
+ "PaymentMethodProcessTokenizationRequestData",
+ "PaymentMethodTokenizationResponseData",
+ ],
+ "PaymentMethodTokenizationResponseData",
+ ]
+
# 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 8bb1789089..89234dfff9 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -40,7 +40,13 @@ from ..payment.interface import (
PaymentData,
PaymentGateway,
PaymentGatewayData,
+ PaymentGatewayInitializeTokenizationRequestData,
+ PaymentGatewayInitializeTokenizationResponseData,
+ PaymentGatewayInitializeTokenizationResult,
PaymentMethodData,
+ PaymentMethodProcessTokenizationRequestData,
+ PaymentMethodTokenizationResponseData,
+ PaymentMethodTokenizationResult,
StoredPaymentMethodRequestDeleteData,
StoredPaymentMethodRequestDeleteResponseData,
StoredPaymentMethodRequestDeleteResult,
@@ -1575,6 +1581,57 @@ class PluginsManager(PaymentInterface):
)
return response
+ def payment_gateway_initialize_tokenization(
+ self,
+ request_data: "PaymentGatewayInitializeTokenizationRequestData",
+ ) -> "PaymentGatewayInitializeTokenizationResponseData":
+ default_response = PaymentGatewayInitializeTokenizationResponseData(
+ result=PaymentGatewayInitializeTokenizationResult.FAILED_TO_DELIVER,
+ error="Payment gateway initialize tokenization failed to deliver.",
+ data=None,
+ )
+
+ response = self.__run_method_on_plugins(
+ "payment_gateway_initialize_tokenization",
+ default_response,
+ request_data,
+ )
+ return response
+
+ def payment_method_initialize_tokenization(
+ self,
+ request_data: "PaymentMethodProcessTokenizationRequestData",
+ ) -> "PaymentMethodTokenizationResponseData":
+ default_response = PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.FAILED_TO_DELIVER,
+ error="Payment method initialize tokenization failed to deliver.",
+ data=None,
+ )
+
+ response = self.__run_method_on_plugins(
+ "payment_method_initialize_tokenization",
+ default_response,
+ request_data,
+ )
+ return response
+
+ def payment_method_process_tokenization(
+ self,
+ request_data: "PaymentMethodProcessTokenizationRequestData",
+ ) -> "PaymentMethodTokenizationResponseData":
+ default_response = PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.FAILED_TO_DELIVER,
+ error="Payment method process tokenization failed to deliver.",
+ data=None,
+ )
+
+ response = self.__run_method_on_plugins(
+ "payment_method_process_tokenization",
+ default_response,
+ request_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 b1ecfb9144..57072a7382 100644
--- a/saleor/plugins/tests/sample_plugins.py
+++ b/saleor/plugins/tests/sample_plugins.py
@@ -356,6 +356,15 @@ class PluginSample(BasePlugin):
def stored_payment_method_request_delete(self, request_delete_data, previous_value):
return previous_value
+ def payment_gateway_initialize_tokenization(self, request_data, previous_value):
+ return previous_value
+
+ def payment_method_initialize_tokenization(self, request_data, previous_value):
+ return previous_value
+
+ def payment_method_process_tokenization(self, request_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 9fac0aad30..1c31206a19 100644
--- a/saleor/plugins/tests/test_manager.py
+++ b/saleor/plugins/tests/test_manager.py
@@ -17,10 +17,18 @@ from ...discount.utils import (
fetch_catalogue_info,
)
from ...graphql.discount.mutations.utils import convert_catalogue_info_to_global_ids
+from ...payment import TokenizedPaymentFlow
from ...payment.interface import (
ListStoredPaymentMethodsRequestData,
PaymentGateway,
PaymentGatewayData,
+ PaymentGatewayInitializeTokenizationRequestData,
+ PaymentGatewayInitializeTokenizationResponseData,
+ PaymentGatewayInitializeTokenizationResult,
+ PaymentMethodInitializeTokenizationRequestData,
+ PaymentMethodProcessTokenizationRequestData,
+ PaymentMethodTokenizationResponseData,
+ PaymentMethodTokenizationResult,
StoredPaymentMethodRequestDeleteData,
StoredPaymentMethodRequestDeleteResponseData,
StoredPaymentMethodRequestDeleteResult,
@@ -1391,3 +1399,109 @@ def test_stored_payment_method_request_delete(
mocked_stored_payment_method_request_delete.assert_called_once_with(
request_delete_data, previous_value=previous_response
)
+
+
+@patch(
+ "saleor.plugins.tests.sample_plugins.PluginSample."
+ "payment_gateway_initialize_tokenization"
+)
+def test_payment_gateway_initialize_tokenization(
+ mocked_payment_gateway_initialize_tokenization, customer_user, channel_USD, app
+):
+ # given
+ plugins = [
+ "saleor.plugins.tests.sample_plugins.PluginSample",
+ "saleor.plugins.tests.sample_plugins.PluginInactive",
+ ]
+ manager = PluginsManager(plugins=plugins)
+ request_data = PaymentGatewayInitializeTokenizationRequestData(
+ user=customer_user,
+ app_identifier=app.identifier,
+ channel=channel_USD,
+ data={"data": "ABC"},
+ )
+ previous_response = PaymentGatewayInitializeTokenizationResponseData(
+ result=PaymentGatewayInitializeTokenizationResult.FAILED_TO_DELIVER,
+ error="Payment gateway initialize tokenization failed to deliver.",
+ data=None,
+ )
+
+ # when
+ manager.payment_gateway_initialize_tokenization(request_data=request_data)
+
+ # then
+ mocked_payment_gateway_initialize_tokenization.assert_called_once_with(
+ request_data, previous_value=previous_response
+ )
+
+
+@patch(
+ "saleor.plugins.tests.sample_plugins.PluginSample."
+ "payment_method_initialize_tokenization"
+)
+def test_payment_method_initialize_tokenization(
+ mocked_payment_method_initialize_tokenization, customer_user, channel_USD, app
+):
+ # given
+ plugins = [
+ "saleor.plugins.tests.sample_plugins.PluginSample",
+ "saleor.plugins.tests.sample_plugins.PluginInactive",
+ ]
+ manager = PluginsManager(plugins=plugins)
+ request_data = PaymentMethodInitializeTokenizationRequestData(
+ user=customer_user,
+ app_identifier=app.identifier,
+ channel=channel_USD,
+ data={"data": "ABC"},
+ payment_flow_to_support=TokenizedPaymentFlow.INTERACTIVE,
+ )
+ previous_response = PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.FAILED_TO_DELIVER,
+ error="Payment method initialize tokenization failed to deliver.",
+ data=None,
+ )
+
+ # when
+ manager.payment_method_initialize_tokenization(request_data=request_data)
+
+ # then
+ mocked_payment_method_initialize_tokenization.assert_called_once_with(
+ request_data, previous_value=previous_response
+ )
+
+
+@patch(
+ "saleor.plugins.tests.sample_plugins.PluginSample."
+ "payment_method_process_tokenization"
+)
+def test_payment_method_process_tokenization(
+ mocked_payment_method_process_tokenization, customer_user, channel_USD, app
+):
+ # given
+ plugins = [
+ "saleor.plugins.tests.sample_plugins.PluginSample",
+ "saleor.plugins.tests.sample_plugins.PluginInactive",
+ ]
+ manager = PluginsManager(plugins=plugins)
+
+ expected_id = "test_id"
+
+ request_data = PaymentMethodProcessTokenizationRequestData(
+ user=customer_user,
+ id=expected_id,
+ channel=channel_USD,
+ data={"data": "ABC"},
+ )
+ previous_response = PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.FAILED_TO_DELIVER,
+ error="Payment method process tokenization failed to deliver.",
+ data=None,
+ )
+
+ # when
+ manager.payment_method_process_tokenization(request_data=request_data)
+
+ # then
+ mocked_payment_method_process_tokenization.assert_called_once_with(
+ request_data, previous_value=previous_response
+ )
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 316e5fdf38..41ac31a4b3 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -35,7 +35,14 @@ from ...payment.interface import (
PaymentData,
PaymentGateway,
PaymentGatewayData,
+ PaymentGatewayInitializeTokenizationRequestData,
+ PaymentGatewayInitializeTokenizationResponseData,
PaymentMethodData,
+ PaymentMethodInitializeTokenizationRequestData,
+ PaymentMethodProcessTokenizationRequestData,
+ PaymentMethodTokenizationBaseRequestData,
+ PaymentMethodTokenizationResponseData,
+ PaymentMethodTokenizationResult,
StoredPaymentMethodRequestDeleteData,
StoredPaymentMethodRequestDeleteResponseData,
TransactionActionData,
@@ -85,6 +92,8 @@ from .shipping import (
from .stored_payment_methods import (
get_list_stored_payment_methods_data_dict,
get_list_stored_payment_methods_from_response,
+ get_response_for_payment_gateway_initialize_tokenization,
+ get_response_for_payment_method_tokenization,
get_response_for_stored_payment_method_request_delete,
invalidate_cache_for_stored_payment_methods,
)
@@ -2119,6 +2128,134 @@ class WebhookPlugin(BasePlugin):
)
return previous_value
+ def _handle_payment_tokenization_request(
+ self,
+ webhook: "Webhook",
+ event_type: str,
+ request_data: PaymentMethodTokenizationBaseRequestData,
+ additional_legacy_payload_data: Optional[dict] = None,
+ ) -> Optional[dict]:
+ payload_data = {
+ "user_id": graphene.Node.to_global_id("User", request_data.user.id),
+ "channel_slug": request_data.channel.slug,
+ "data": request_data.data,
+ }
+ if additional_legacy_payload_data:
+ payload_data.update(additional_legacy_payload_data)
+
+ payload = self._serialize_payload(payload_data)
+ response_data = trigger_webhook_sync(
+ event_type,
+ payload,
+ webhook,
+ subscribable_object=request_data,
+ timeout=WEBHOOK_SYNC_TIMEOUT,
+ )
+ return response_data
+
+ def payment_gateway_initialize_tokenization(
+ self,
+ request_data: "PaymentGatewayInitializeTokenizationRequestData",
+ previous_value: "PaymentGatewayInitializeTokenizationResponseData",
+ ) -> "PaymentGatewayInitializeTokenizationResponseData":
+ if not self.active:
+ return previous_value
+
+ event_type = (
+ WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_TOKENIZATION_SESSION
+ )
+ webhook = get_webhooks_for_event(
+ event_type, apps_identifier=[request_data.app_identifier]
+ ).first()
+
+ if not webhook:
+ return previous_value
+
+ response_data = self._handle_payment_tokenization_request(
+ event_type=event_type, webhook=webhook, request_data=request_data
+ )
+ return get_response_for_payment_gateway_initialize_tokenization(response_data)
+
+ def _handle_payment_method_tokenization(
+ self,
+ app_identifier: str,
+ event_type: str,
+ request_data: PaymentMethodTokenizationBaseRequestData,
+ previous_value: "PaymentMethodTokenizationResponseData",
+ additional_legacy_payload_data: Optional[dict] = None,
+ ):
+ webhook = get_webhooks_for_event(
+ event_type, apps_identifier=[app_identifier]
+ ).first()
+
+ if not webhook:
+ return previous_value
+
+ response_data = self._handle_payment_tokenization_request(
+ event_type=event_type,
+ webhook=webhook,
+ request_data=request_data,
+ additional_legacy_payload_data=additional_legacy_payload_data,
+ )
+
+ response = get_response_for_payment_method_tokenization(
+ response_data, webhook.app
+ )
+ if response.result in [
+ PaymentMethodTokenizationResult.SUCCESSFULLY_TOKENIZED,
+ PaymentMethodTokenizationResult.PENDING,
+ ]:
+ invalidate_cache_for_stored_payment_methods(
+ request_data.user.id,
+ request_data.channel.slug,
+ app_identifier,
+ )
+ return response
+
+ def payment_method_initialize_tokenization(
+ self,
+ request_data: "PaymentMethodInitializeTokenizationRequestData",
+ previous_value: "PaymentMethodTokenizationResponseData",
+ ) -> "PaymentMethodTokenizationResponseData":
+ if not self.active:
+ return previous_value
+
+ event_type = WebhookEventSyncType.PAYMENT_METHOD_INITIALIZE_TOKENIZATION_SESSION
+
+ return self._handle_payment_method_tokenization(
+ app_identifier=request_data.app_identifier,
+ event_type=event_type,
+ request_data=request_data,
+ previous_value=previous_value,
+ additional_legacy_payload_data={
+ "payment_flow_to_support": request_data.payment_flow_to_support
+ },
+ )
+
+ def payment_method_process_tokenization(
+ self,
+ request_data: "PaymentMethodProcessTokenizationRequestData",
+ previous_value: "PaymentMethodTokenizationResponseData",
+ ) -> "PaymentMethodTokenizationResponseData":
+ if not self.active:
+ return previous_value
+
+ app_data = from_payment_app_id(request_data.id)
+
+ if not app_data or not app_data.app_identifier:
+ return previous_value
+
+ request_data.id = app_data.name
+
+ event_type = WebhookEventSyncType.PAYMENT_METHOD_PROCESS_TOKENIZATION_SESSION
+ return self._handle_payment_method_tokenization(
+ app_identifier=app_data.app_identifier,
+ event_type=event_type,
+ request_data=request_data,
+ previous_value=previous_value,
+ additional_legacy_payload_data={"id": request_data.id},
+ )
+
def _request_transaction_action(
self,
transaction_data: "TransactionActionData",
@@ -2654,6 +2791,15 @@ class WebhookPlugin(BasePlugin):
"stored_payment_method_request_delete": (
WebhookEventSyncType.STORED_PAYMENT_METHOD_DELETE_REQUESTED
),
+ "payment_gateway_initialize_tokenization": (
+ WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_TOKENIZATION_SESSION
+ ),
+ "payment_method_initialize_tokenization": (
+ WebhookEventSyncType.PAYMENT_METHOD_INITIALIZE_TOKENIZATION_SESSION
+ ),
+ "payment_method_process_tokenization": (
+ WebhookEventSyncType.PAYMENT_METHOD_PROCESS_TOKENIZATION_SESSION
+ ),
}
if event in map_event:
diff --git a/saleor/plugins/webhook/stored_payment_methods.py b/saleor/plugins/webhook/stored_payment_methods.py
index e40d201d5a..9799077372 100644
--- a/saleor/plugins/webhook/stored_payment_methods.py
+++ b/saleor/plugins/webhook/stored_payment_methods.py
@@ -8,8 +8,12 @@ from ...app.models import App
from ...payment import TokenizedPaymentFlow
from ...payment.interface import (
PaymentGateway,
+ PaymentGatewayInitializeTokenizationResponseData,
+ PaymentGatewayInitializeTokenizationResult,
PaymentMethodCreditCardInfo,
PaymentMethodData,
+ PaymentMethodTokenizationResponseData,
+ PaymentMethodTokenizationResult,
StoredPaymentMethodRequestDeleteResponseData,
StoredPaymentMethodRequestDeleteResult,
)
@@ -185,3 +189,59 @@ def invalidate_cache_for_stored_payment_methods(
cache_data, webhook.target_url, event_type, webhook.app_id
)
cache.delete(cache_key)
+
+
+def get_response_for_payment_gateway_initialize_tokenization(
+ response_data: Optional[dict],
+) -> "PaymentGatewayInitializeTokenizationResponseData":
+ data = None
+ if response_data is None:
+ result = PaymentGatewayInitializeTokenizationResult.FAILED_TO_DELIVER
+ error = "Failed to delivery request."
+ else:
+ try:
+ response_result = response_data.get("result") or ""
+ result = PaymentGatewayInitializeTokenizationResult[response_result]
+ error = response_data.get("error", None)
+ data = response_data.get("data", None)
+ except KeyError:
+ result = PaymentGatewayInitializeTokenizationResult.FAILED_TO_INITIALIZE
+ error = "Missing or incorrect `result` in response."
+
+ return PaymentGatewayInitializeTokenizationResponseData(
+ result=result, error=error, data=data
+ )
+
+
+def get_response_for_payment_method_tokenization(
+ response_data: Optional[dict], app: "App"
+) -> "PaymentMethodTokenizationResponseData":
+ data = None
+ payment_method_id = None
+ if response_data is None:
+ result = PaymentMethodTokenizationResult.FAILED_TO_DELIVER
+ error = "Failed to delivery request."
+ else:
+ try:
+ response_result = response_data.get("result") or ""
+ result = PaymentMethodTokenizationResult[response_result]
+ error = response_data.get("error", None)
+ data = response_data.get("data", None)
+ except KeyError:
+ result = PaymentMethodTokenizationResult.FAILED_TO_TOKENIZE
+ error = "Missing or incorrect `result` in response."
+
+ try:
+ payment_method_id = response_data["id"]
+ payment_method_id = to_payment_app_id(app, payment_method_id)
+ except KeyError:
+ if result in [
+ PaymentMethodTokenizationResult.SUCCESSFULLY_TOKENIZED,
+ PaymentMethodTokenizationResult.ADDITIONAL_ACTION_REQUIRED,
+ ]:
+ result = PaymentMethodTokenizationResult.FAILED_TO_TOKENIZE
+ error = "Missing payment method `id` in response."
+
+ return PaymentMethodTokenizationResponseData(
+ result=result, error=error, data=data, id=payment_method_id
+ )
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_gateway_initialize_tokenization_session.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_gateway_initialize_tokenization_session.py
new file mode 100644
index 0000000000..24c9cdeba2
--- /dev/null
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_gateway_initialize_tokenization_session.py
@@ -0,0 +1,89 @@
+import json
+
+import graphene
+
+from .....payment.interface import PaymentGatewayInitializeTokenizationRequestData
+from .....webhook.event_types import WebhookEventSyncType
+from ...tasks import create_deliveries_for_subscriptions
+
+PAYMENT_GATEWAY_INITIALIZE_TOKENIZATION = """
+subscription {
+ event {
+ ... on PaymentGatewayInitializeTokenizationSession{
+ user{
+ id
+ }
+ channel{
+ id
+ }
+ data
+ }
+ }
+}
+"""
+
+
+def test_payment_gateway_initialize_tokenization_without_data(
+ payment_gateway_initialize_tokenization_app, customer_user, channel_USD
+):
+ # given
+ webhook = payment_gateway_initialize_tokenization_app.webhooks.first()
+ webhook.subscription_query = PAYMENT_GATEWAY_INITIALIZE_TOKENIZATION
+ webhook.save()
+
+ request_delete_data = PaymentGatewayInitializeTokenizationRequestData(
+ user=customer_user,
+ app_identifier=payment_gateway_initialize_tokenization_app.identifier,
+ channel=channel_USD,
+ data=None,
+ )
+
+ event_type = WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_TOKENIZATION_SESSION
+
+ # 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) == {
+ "data": None,
+ "user": {"id": graphene.Node.to_global_id("User", customer_user.pk)},
+ "channel": {"id": graphene.Node.to_global_id("Channel", channel_USD.pk)},
+ }
+
+
+def test_payment_gateway_initialize_tokenization_with_data(
+ payment_gateway_initialize_tokenization_app, customer_user, channel_USD
+):
+ # given
+ webhook = payment_gateway_initialize_tokenization_app.webhooks.first()
+ webhook.subscription_query = PAYMENT_GATEWAY_INITIALIZE_TOKENIZATION
+ webhook.save()
+
+ expected_data = {"data": {"foo": "bar"}}
+
+ request_delete_data = PaymentGatewayInitializeTokenizationRequestData(
+ user=customer_user,
+ app_identifier=payment_gateway_initialize_tokenization_app.identifier,
+ channel=channel_USD,
+ data=expected_data,
+ )
+
+ event_type = WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_TOKENIZATION_SESSION
+
+ # 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) == {
+ "data": expected_data,
+ "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/subscription_webhooks/test_create_deliveries_for_payment_method_initialize_tokenization.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_method_initialize_tokenization.py
new file mode 100644
index 0000000000..eda5fe40a6
--- /dev/null
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_method_initialize_tokenization.py
@@ -0,0 +1,95 @@
+import json
+
+import graphene
+
+from .....payment import TokenizedPaymentFlow
+from .....payment.interface import PaymentMethodInitializeTokenizationRequestData
+from .....webhook.event_types import WebhookEventSyncType
+from ...tasks import create_deliveries_for_subscriptions
+
+PAYMENT_METHOD_INITIALIZE_TOKENIZATION_SESSION = """
+subscription{
+ event{
+ ...on PaymentMethodInitializeTokenizationSession{
+ paymentFlowToSupport
+ user{
+ id
+ }
+ channel{
+ id
+ }
+ data
+ }
+ }
+}
+"""
+
+
+def test_payment_method_initialize_tokenization_without_data(
+ payment_method_initialize_tokenization_app, customer_user, channel_USD
+):
+ # given
+ webhook = payment_method_initialize_tokenization_app.webhooks.first()
+ webhook.subscription_query = PAYMENT_METHOD_INITIALIZE_TOKENIZATION_SESSION
+ webhook.save()
+
+ request_delete_data = PaymentMethodInitializeTokenizationRequestData(
+ user=customer_user,
+ app_identifier=payment_method_initialize_tokenization_app.identifier,
+ channel=channel_USD,
+ data=None,
+ payment_flow_to_support=TokenizedPaymentFlow.INTERACTIVE,
+ )
+
+ event_type = WebhookEventSyncType.PAYMENT_METHOD_INITIALIZE_TOKENIZATION_SESSION
+
+ # 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) == {
+ "data": None,
+ "user": {"id": graphene.Node.to_global_id("User", customer_user.pk)},
+ "channel": {"id": graphene.Node.to_global_id("Channel", channel_USD.pk)},
+ "paymentFlowToSupport": "INTERACTIVE",
+ }
+
+
+def test_payment_method_initialize_tokenization_with_data(
+ payment_method_initialize_tokenization_app, customer_user, channel_USD
+):
+ # given
+ webhook = payment_method_initialize_tokenization_app.webhooks.first()
+ webhook.subscription_query = PAYMENT_METHOD_INITIALIZE_TOKENIZATION_SESSION
+ webhook.save()
+
+ expected_data = {"data": {"foo": "bar"}}
+
+ request_delete_data = PaymentMethodInitializeTokenizationRequestData(
+ user=customer_user,
+ app_identifier=payment_method_initialize_tokenization_app.identifier,
+ channel=channel_USD,
+ data=expected_data,
+ payment_flow_to_support=TokenizedPaymentFlow.INTERACTIVE,
+ )
+
+ event_type = WebhookEventSyncType.PAYMENT_METHOD_INITIALIZE_TOKENIZATION_SESSION
+
+ # 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) == {
+ "data": expected_data,
+ "user": {"id": graphene.Node.to_global_id("User", customer_user.pk)},
+ "channel": {"id": graphene.Node.to_global_id("Channel", channel_USD.pk)},
+ "paymentFlowToSupport": "INTERACTIVE",
+ }
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_method_process_tokenization.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_method_process_tokenization.py
new file mode 100644
index 0000000000..39ef54f96d
--- /dev/null
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_method_process_tokenization.py
@@ -0,0 +1,95 @@
+import json
+
+import graphene
+
+from .....payment.interface import PaymentMethodProcessTokenizationRequestData
+from .....webhook.event_types import WebhookEventSyncType
+from ...tasks import create_deliveries_for_subscriptions
+
+PAYMENT_METHOD_PROCESS_TOKENIZATION_SESSION = """
+subscription{
+ event{
+ ...on PaymentMethodProcessTokenizationSession{
+ id
+ user{
+ id
+ }
+ channel{
+ id
+ }
+ data
+ }
+ }
+}
+"""
+
+
+def test_payment_method_process_tokenization_without_data(
+ payment_method_process_tokenization_app, customer_user, channel_USD
+):
+ # given
+ webhook = payment_method_process_tokenization_app.webhooks.first()
+ webhook.subscription_query = PAYMENT_METHOD_PROCESS_TOKENIZATION_SESSION
+ webhook.save()
+
+ expected_id = "test_id"
+
+ request_data = PaymentMethodProcessTokenizationRequestData(
+ user=customer_user,
+ id=expected_id,
+ channel=channel_USD,
+ data=None,
+ )
+
+ event_type = WebhookEventSyncType.PAYMENT_METHOD_PROCESS_TOKENIZATION_SESSION
+
+ # when
+ delivery = create_deliveries_for_subscriptions(event_type, request_data, [webhook])[
+ 0
+ ]
+
+ # then
+ assert delivery.payload
+ assert delivery.payload.payload
+ assert json.loads(delivery.payload.payload) == {
+ "data": None,
+ "user": {"id": graphene.Node.to_global_id("User", customer_user.pk)},
+ "channel": {"id": graphene.Node.to_global_id("Channel", channel_USD.pk)},
+ "id": expected_id,
+ }
+
+
+def test_payment_method_process_tokenization_with_data(
+ payment_method_process_tokenization_app, customer_user, channel_USD
+):
+ # given
+ webhook = payment_method_process_tokenization_app.webhooks.first()
+ webhook.subscription_query = PAYMENT_METHOD_PROCESS_TOKENIZATION_SESSION
+ webhook.save()
+
+ expected_data = {"data": {"foo": "bar"}}
+ expected_id = "test_id"
+
+ request_data = PaymentMethodProcessTokenizationRequestData(
+ user=customer_user,
+ id=expected_id,
+ channel=channel_USD,
+ data=expected_data,
+ )
+
+ event_type = WebhookEventSyncType.PAYMENT_METHOD_PROCESS_TOKENIZATION_SESSION
+
+ # when
+ delivery = create_deliveries_for_subscriptions(event_type, request_data, [webhook])[
+ 0
+ ]
+
+ # then
+ assert delivery.payload
+ assert delivery.payload.payload
+ assert json.loads(delivery.payload.payload) == {
+ "data": expected_data,
+ "user": {"id": graphene.Node.to_global_id("User", customer_user.pk)},
+ "channel": {"id": graphene.Node.to_global_id("Channel", channel_USD.pk)},
+ "id": expected_id,
+ }
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_initialize_session.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_initialize_session.py
index 89ff250b5e..cbf2b5ed66 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_initialize_session.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_initialize_session.py
@@ -29,6 +29,9 @@ subscription {
__typename
... on Checkout{
id
+ user{
+ id
+ }
totalPrice{
gross{
amount
@@ -37,6 +40,9 @@ subscription {
}
... on Order{
id
+ user{
+ id
+ }
}
}
}
@@ -46,9 +52,16 @@ subscription {
def test_transaction_initialize_session_checkout_with_data(
- checkout, webhook_app, permission_manage_payments, transaction_item_generator
+ checkout,
+ webhook_app,
+ permission_manage_payments,
+ transaction_item_generator,
+ customer_user,
):
# given
+ checkout.user = customer_user
+ checkout.save()
+
webhook_app.permissions.add(permission_manage_payments)
webhook = Webhook.objects.create(
name="Webhook",
@@ -107,6 +120,7 @@ def test_transaction_initialize_session_checkout_with_data(
"__typename": "Checkout",
"id": checkout_id,
"totalPrice": {"gross": {"amount": 0.0}},
+ "user": {"id": graphene.Node.to_global_id("User", customer_user.pk)},
},
}
@@ -173,6 +187,7 @@ def test_transaction_initialize_session_checkout_without_data(
"__typename": "Checkout",
"id": checkout_id,
"totalPrice": {"gross": {"amount": 0.0}},
+ "user": None,
},
}
@@ -239,6 +254,7 @@ def test_transaction_initialize_session_order_with_data(
"sourceObject": {
"__typename": "Order",
"id": order_id,
+ "user": {"id": graphene.Node.to_global_id("User", order.user.pk)},
},
}
@@ -304,6 +320,7 @@ def test_transaction_initialize_session_order_without_data(
"sourceObject": {
"__typename": "Order",
"id": order_id,
+ "user": {"id": graphene.Node.to_global_id("User", order.user.pk)},
},
}
@@ -369,5 +386,6 @@ def test_transaction_initialize_session_empty_customer_ip_addess(
"sourceObject": {
"__typename": "Order",
"id": order_id,
+ "user": {"id": graphene.Node.to_global_id("User", order.user.pk)},
},
}
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_process_session.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_process_session.py
index 1c405ca9a5..81eed57945 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_process_session.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_process_session.py
@@ -29,6 +29,9 @@ subscription {
__typename
... on Checkout{
id
+ user{
+ id
+ }
totalPrice{
gross{
amount
@@ -37,6 +40,9 @@ subscription {
}
... on Order{
id
+ user{
+ id
+ }
}
}
}
@@ -46,9 +52,15 @@ subscription {
def test_transaction_process_session_checkout_with_data(
- checkout, webhook_app, permission_manage_payments, transaction_item_generator
+ checkout,
+ webhook_app,
+ permission_manage_payments,
+ transaction_item_generator,
+ customer_user,
):
# given
+ checkout.user = customer_user
+ checkout.save()
webhook_app.permissions.add(permission_manage_payments)
webhook = Webhook.objects.create(
name="Webhook",
@@ -106,6 +118,7 @@ def test_transaction_process_session_checkout_with_data(
"sourceObject": {
"__typename": "Checkout",
"id": checkout_id,
+ "user": {"id": graphene.Node.to_global_id("User", customer_user.pk)},
"totalPrice": {"gross": {"amount": 0.0}},
},
}
@@ -173,14 +186,22 @@ def test_transaction_process_session_checkout_without_data(
"__typename": "Checkout",
"id": checkout_id,
"totalPrice": {"gross": {"amount": 0.0}},
+ "user": None,
},
}
def test_transaction_process_session_order_with_data(
- order, webhook_app, permission_manage_payments, transaction_item_generator
+ order,
+ webhook_app,
+ permission_manage_payments,
+ transaction_item_generator,
+ customer_user,
):
# given
+ order.user = customer_user
+ order.save()
+
webhook_app.permissions.add(permission_manage_payments)
webhook = Webhook.objects.create(
name="Webhook",
@@ -239,6 +260,7 @@ def test_transaction_process_session_order_with_data(
"sourceObject": {
"__typename": "Order",
"id": order_id,
+ "user": {"id": graphene.Node.to_global_id("User", customer_user.pk)},
},
}
@@ -304,6 +326,7 @@ def test_transaction_process_session_order_without_data(
"sourceObject": {
"__typename": "Order",
"id": order_id,
+ "user": {"id": graphene.Node.to_global_id("User", order.user.pk)},
},
}
@@ -369,5 +392,6 @@ def test_transaction_process_session_empty_customer_ip_address(
"sourceObject": {
"__typename": "Order",
"id": order_id,
+ "user": {"id": graphene.Node.to_global_id("User", order.user.pk)},
},
}
diff --git a/saleor/plugins/webhook/tests/test_payment_gateway_initialize_tokenization.py b/saleor/plugins/webhook/tests/test_payment_gateway_initialize_tokenization.py
new file mode 100644
index 0000000000..df8469ad56
--- /dev/null
+++ b/saleor/plugins/webhook/tests/test_payment_gateway_initialize_tokenization.py
@@ -0,0 +1,244 @@
+import json
+
+import graphene
+import mock
+import pytest
+
+from ....core.models import EventDelivery
+from ....payment.interface import (
+ PaymentGatewayInitializeTokenizationRequestData,
+ PaymentGatewayInitializeTokenizationResponseData,
+ PaymentGatewayInitializeTokenizationResult,
+)
+from ....settings import WEBHOOK_SYNC_TIMEOUT
+
+PAYMENT_GATEWAY_INITIALIZE_TOKENIZATION = """
+subscription {
+ event {
+ ... on PaymentGatewayInitializeTokenizationSession{
+ user{
+ id
+ }
+ channel{
+ id
+ }
+ data
+ }
+ }
+}
+"""
+
+
+def webhook_payment_gateway_initialize_tokenization_response():
+ return {
+ "result": (
+ PaymentGatewayInitializeTokenizationResult.SUCCESSFULLY_INITIALIZED.name
+ ),
+ "data": {"foo": "bar"},
+ }
+
+
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_payment_gateway_initialize_tokenization_with_static_payload(
+ mock_request,
+ customer_user,
+ webhook_plugin,
+ payment_gateway_initialize_tokenization_app,
+ webhook_payment_gateway_initialize_tokenization_response,
+ channel_USD,
+):
+ # given
+ mock_request.return_value = webhook_payment_gateway_initialize_tokenization_response
+
+ plugin = webhook_plugin()
+
+ expected_data = {"foo": "bar"}
+ request_data = PaymentGatewayInitializeTokenizationRequestData(
+ user=customer_user,
+ app_identifier=payment_gateway_initialize_tokenization_app.identifier,
+ channel=channel_USD,
+ data=expected_data,
+ )
+
+ previous_value = PaymentGatewayInitializeTokenizationResponseData(
+ result=PaymentGatewayInitializeTokenizationResult.FAILED_TO_DELIVER,
+ error="Payment gateway initialize tokenization failed to deliver.",
+ data=None,
+ )
+
+ # when
+ response = plugin.payment_gateway_initialize_tokenization(
+ request_data, previous_value
+ )
+
+ # then
+ delivery = EventDelivery.objects.get()
+ assert json.loads(delivery.payload.payload) == {
+ "user_id": graphene.Node.to_global_id("User", customer_user.pk),
+ "channel_slug": channel_USD.slug,
+ "data": expected_data,
+ }
+ mock_request.assert_called_once_with(delivery, timeout=WEBHOOK_SYNC_TIMEOUT)
+
+ assert response == PaymentGatewayInitializeTokenizationResponseData(
+ result=PaymentGatewayInitializeTokenizationResult.SUCCESSFULLY_INITIALIZED,
+ error=None,
+ data=webhook_payment_gateway_initialize_tokenization_response["data"],
+ )
+
+
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_payment_gateway_initialize_tokenization_with_subscription_payload(
+ mock_request,
+ customer_user,
+ webhook_plugin,
+ payment_gateway_initialize_tokenization_app,
+ webhook_payment_gateway_initialize_tokenization_response,
+ channel_USD,
+):
+ # given
+ mock_request.return_value = webhook_payment_gateway_initialize_tokenization_response
+
+ webhook = payment_gateway_initialize_tokenization_app.webhooks.first()
+ webhook.subscription_query = PAYMENT_GATEWAY_INITIALIZE_TOKENIZATION
+ webhook.save()
+
+ plugin = webhook_plugin()
+
+ expected_data = {"foo": "bar"}
+
+ request_data = PaymentGatewayInitializeTokenizationRequestData(
+ user=customer_user,
+ app_identifier=payment_gateway_initialize_tokenization_app.identifier,
+ channel=channel_USD,
+ data=expected_data,
+ )
+
+ previous_value = PaymentGatewayInitializeTokenizationResponseData(
+ result=PaymentGatewayInitializeTokenizationResult.FAILED_TO_DELIVER,
+ error="Payment gateway initialize tokenization failed to deliver.",
+ data=None,
+ )
+
+ # when
+ response = plugin.payment_gateway_initialize_tokenization(
+ request_data, previous_value
+ )
+
+ # then
+ delivery = EventDelivery.objects.get()
+ assert json.loads(delivery.payload.payload) == {
+ "user": {"id": graphene.Node.to_global_id("User", customer_user.pk)},
+ "data": expected_data,
+ "channel": {"id": graphene.Node.to_global_id("Channel", channel_USD.pk)},
+ }
+ mock_request.assert_called_once_with(delivery, timeout=WEBHOOK_SYNC_TIMEOUT)
+
+ assert response == PaymentGatewayInitializeTokenizationResponseData(
+ result=PaymentGatewayInitializeTokenizationResult.SUCCESSFULLY_INITIALIZED,
+ error=None,
+ data=webhook_payment_gateway_initialize_tokenization_response["data"],
+ )
+
+
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_payment_gateway_initialize_tokenization_missing_correct_response_from_webhook(
+ mock_request,
+ customer_user,
+ webhook_plugin,
+ payment_gateway_initialize_tokenization_app,
+ channel_USD,
+):
+ # given
+ mock_request.return_value = None
+
+ webhook = payment_gateway_initialize_tokenization_app.webhooks.first()
+ webhook.subscription_query = PAYMENT_GATEWAY_INITIALIZE_TOKENIZATION
+ webhook.save()
+
+ plugin = webhook_plugin()
+
+ expected_data = {"foo": "bar"}
+
+ request_data = PaymentGatewayInitializeTokenizationRequestData(
+ user=customer_user,
+ app_identifier=payment_gateway_initialize_tokenization_app.identifier,
+ channel=channel_USD,
+ data=expected_data,
+ )
+
+ previous_value = PaymentGatewayInitializeTokenizationResponseData(
+ result=PaymentGatewayInitializeTokenizationResult.FAILED_TO_DELIVER,
+ error="Payment gateway initialize tokenization failed to deliver.",
+ data=None,
+ )
+
+ # when
+ response = plugin.payment_gateway_initialize_tokenization(
+ request_data, previous_value
+ )
+
+ # then
+ delivery = EventDelivery.objects.get()
+
+ mock_request.assert_called_once_with(delivery, timeout=WEBHOOK_SYNC_TIMEOUT)
+
+ assert response == PaymentGatewayInitializeTokenizationResponseData(
+ result=PaymentGatewayInitializeTokenizationResult.FAILED_TO_DELIVER,
+ error="Failed to delivery request.",
+ data=None,
+ )
+
+
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_payment_gateway_initialize_tokenization_failure_from_app(
+ mock_request,
+ customer_user,
+ webhook_plugin,
+ payment_gateway_initialize_tokenization_app,
+ channel_USD,
+):
+ # given
+ expected_error_msg = "Expected error msg."
+ mock_request.return_value = {
+ "result": PaymentGatewayInitializeTokenizationResult.FAILED_TO_INITIALIZE.name,
+ "error": expected_error_msg,
+ "data": None,
+ }
+
+ plugin = webhook_plugin()
+
+ expected_data = {"foo": "bar"}
+ request_data = PaymentGatewayInitializeTokenizationRequestData(
+ user=customer_user,
+ app_identifier=payment_gateway_initialize_tokenization_app.identifier,
+ channel=channel_USD,
+ data=expected_data,
+ )
+
+ previous_value = PaymentGatewayInitializeTokenizationResponseData(
+ result=PaymentGatewayInitializeTokenizationResult.FAILED_TO_DELIVER,
+ error="Payment gateway initialize tokenization failed to deliver.",
+ data=None,
+ )
+
+ # when
+ response = plugin.payment_gateway_initialize_tokenization(
+ request_data, previous_value
+ )
+
+ # then
+ delivery = EventDelivery.objects.get()
+ assert json.loads(delivery.payload.payload) == {
+ "user_id": graphene.Node.to_global_id("User", customer_user.pk),
+ "channel_slug": channel_USD.slug,
+ "data": expected_data,
+ }
+ mock_request.assert_called_once_with(delivery, timeout=WEBHOOK_SYNC_TIMEOUT)
+
+ assert response == PaymentGatewayInitializeTokenizationResponseData(
+ result=PaymentGatewayInitializeTokenizationResult.FAILED_TO_INITIALIZE,
+ error=expected_error_msg,
+ data=None,
+ )
diff --git a/saleor/plugins/webhook/tests/test_payment_method_initialize_tokenization.py b/saleor/plugins/webhook/tests/test_payment_method_initialize_tokenization.py
new file mode 100644
index 0000000000..5f7964ed7d
--- /dev/null
+++ b/saleor/plugins/webhook/tests/test_payment_method_initialize_tokenization.py
@@ -0,0 +1,512 @@
+import json
+
+import graphene
+import mock
+import pytest
+
+from ....core.models import EventDelivery
+from ....payment import TokenizedPaymentFlow
+from ....payment.interface import (
+ ListStoredPaymentMethodsRequestData,
+ PaymentMethodInitializeTokenizationRequestData,
+ PaymentMethodTokenizationResponseData,
+ PaymentMethodTokenizationResult,
+)
+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
+
+PAYMENT_METHOD_INITIALIZE_TOKENIZATION_SESSION = """
+subscription{
+ event{
+ ...on PaymentMethodInitializeTokenizationSession{
+ user{
+ id
+ }
+ paymentFlowToSupport
+ channel{
+ id
+ }
+ data
+ }
+ }
+}
+"""
+
+
+def webhook_payment_method_initialize_tokenization_response():
+ return {
+ "result": (PaymentMethodTokenizationResult.SUCCESSFULLY_TOKENIZED.name),
+ "id": "payment-method-id",
+ "data": {"foo": "bar"},
+ }
+
+
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_payment_method_initialize_tokenization_with_static_payload(
+ mock_request,
+ customer_user,
+ webhook_plugin,
+ payment_method_initialize_tokenization_app,
+ webhook_payment_method_initialize_tokenization_response,
+ channel_USD,
+):
+ # given
+ mock_request.return_value = webhook_payment_method_initialize_tokenization_response
+
+ plugin = webhook_plugin()
+
+ expected_data = {"foo": "bar"}
+ request_data = PaymentMethodInitializeTokenizationRequestData(
+ user=customer_user,
+ app_identifier=payment_method_initialize_tokenization_app.identifier,
+ channel=channel_USD,
+ data=expected_data,
+ payment_flow_to_support=TokenizedPaymentFlow.INTERACTIVE,
+ )
+
+ previous_value = PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.FAILED_TO_DELIVER,
+ error="Payment method initialize tokenization failed to deliver.",
+ data=None,
+ )
+
+ # when
+ response = plugin.payment_method_initialize_tokenization(
+ request_data, previous_value
+ )
+
+ # then
+ delivery = EventDelivery.objects.get()
+ assert json.loads(delivery.payload.payload) == {
+ "user_id": graphene.Node.to_global_id("User", customer_user.pk),
+ "channel_slug": channel_USD.slug,
+ "data": expected_data,
+ "payment_flow_to_support": "interactive",
+ }
+ mock_request.assert_called_once_with(delivery, timeout=WEBHOOK_SYNC_TIMEOUT)
+
+ assert response == PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.SUCCESSFULLY_TOKENIZED,
+ id=to_payment_app_id(
+ payment_method_initialize_tokenization_app,
+ webhook_payment_method_initialize_tokenization_response["id"],
+ ),
+ error=None,
+ data=webhook_payment_method_initialize_tokenization_response["data"],
+ )
+
+
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_payment_method_initialize_tokenization_with_subscription_payload(
+ mock_request,
+ customer_user,
+ webhook_plugin,
+ payment_method_initialize_tokenization_app,
+ webhook_payment_method_initialize_tokenization_response,
+ channel_USD,
+):
+ # given
+ mock_request.return_value = webhook_payment_method_initialize_tokenization_response
+
+ webhook = payment_method_initialize_tokenization_app.webhooks.first()
+ webhook.subscription_query = PAYMENT_METHOD_INITIALIZE_TOKENIZATION_SESSION
+ webhook.save()
+
+ plugin = webhook_plugin()
+
+ expected_data = {"foo": "bar"}
+
+ request_data = PaymentMethodInitializeTokenizationRequestData(
+ user=customer_user,
+ app_identifier=payment_method_initialize_tokenization_app.identifier,
+ channel=channel_USD,
+ data=expected_data,
+ payment_flow_to_support=TokenizedPaymentFlow.INTERACTIVE,
+ )
+
+ previous_value = PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.FAILED_TO_DELIVER,
+ error="Payment method initialize tokenization failed to deliver.",
+ data=None,
+ )
+
+ # when
+ response = plugin.payment_method_initialize_tokenization(
+ request_data, previous_value
+ )
+
+ # then
+ delivery = EventDelivery.objects.get()
+ assert json.loads(delivery.payload.payload) == {
+ "user": {"id": graphene.Node.to_global_id("User", customer_user.pk)},
+ "data": expected_data,
+ "channel": {"id": graphene.Node.to_global_id("Channel", channel_USD.pk)},
+ "paymentFlowToSupport": "INTERACTIVE",
+ }
+ mock_request.assert_called_once_with(delivery, timeout=WEBHOOK_SYNC_TIMEOUT)
+
+ assert response == PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.SUCCESSFULLY_TOKENIZED,
+ id=to_payment_app_id(
+ payment_method_initialize_tokenization_app,
+ webhook_payment_method_initialize_tokenization_response["id"],
+ ),
+ error=None,
+ data=webhook_payment_method_initialize_tokenization_response["data"],
+ )
+
+
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_payment_method_initialize_tokenization_missing_correct_response_from_webhook(
+ mock_request,
+ customer_user,
+ webhook_plugin,
+ payment_method_initialize_tokenization_app,
+ channel_USD,
+):
+ # given
+ mock_request.return_value = None
+
+ webhook = payment_method_initialize_tokenization_app.webhooks.first()
+ webhook.subscription_query = PAYMENT_METHOD_INITIALIZE_TOKENIZATION_SESSION
+ webhook.save()
+
+ plugin = webhook_plugin()
+
+ expected_data = {"foo": "bar"}
+
+ request_data = PaymentMethodInitializeTokenizationRequestData(
+ user=customer_user,
+ app_identifier=payment_method_initialize_tokenization_app.identifier,
+ channel=channel_USD,
+ data=expected_data,
+ payment_flow_to_support=TokenizedPaymentFlow.INTERACTIVE,
+ )
+
+ previous_value = PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.FAILED_TO_DELIVER,
+ error="Payment method initialize tokenization failed to deliver.",
+ data=None,
+ )
+
+ # when
+ response = plugin.payment_method_initialize_tokenization(
+ request_data, previous_value
+ )
+
+ # then
+ delivery = EventDelivery.objects.get()
+
+ mock_request.assert_called_once_with(delivery, timeout=WEBHOOK_SYNC_TIMEOUT)
+
+ assert response == PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.FAILED_TO_DELIVER,
+ error="Failed to delivery request.",
+ id=None,
+ data=None,
+ )
+
+
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_payment_method_initialize_tokenization_failure_from_app(
+ mock_request,
+ customer_user,
+ webhook_plugin,
+ payment_method_initialize_tokenization_app,
+ channel_USD,
+):
+ # given
+ expected_error_msg = "Expected error msg."
+ mock_request.return_value = {
+ "result": PaymentMethodTokenizationResult.FAILED_TO_TOKENIZE.name,
+ "error": expected_error_msg,
+ "data": None,
+ }
+
+ plugin = webhook_plugin()
+
+ expected_data = {"foo": "bar"}
+ request_data = PaymentMethodInitializeTokenizationRequestData(
+ user=customer_user,
+ app_identifier=payment_method_initialize_tokenization_app.identifier,
+ channel=channel_USD,
+ data=expected_data,
+ payment_flow_to_support=TokenizedPaymentFlow.INTERACTIVE,
+ )
+
+ previous_value = PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.FAILED_TO_DELIVER,
+ error="Payment method initialize tokenization failed to deliver.",
+ data=None,
+ )
+
+ # when
+ response = plugin.payment_method_initialize_tokenization(
+ request_data, previous_value
+ )
+
+ # then
+ delivery = EventDelivery.objects.get()
+ assert json.loads(delivery.payload.payload) == {
+ "user_id": graphene.Node.to_global_id("User", customer_user.pk),
+ "channel_slug": channel_USD.slug,
+ "data": expected_data,
+ "payment_flow_to_support": "interactive",
+ }
+ mock_request.assert_called_once_with(delivery, timeout=WEBHOOK_SYNC_TIMEOUT)
+
+ assert response == PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.FAILED_TO_TOKENIZE,
+ error=expected_error_msg,
+ id=None,
+ data=None,
+ )
+
+
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_payment_method_initialize_tokenization_additional_action_required(
+ mock_request,
+ customer_user,
+ webhook_plugin,
+ payment_method_initialize_tokenization_app,
+ channel_USD,
+):
+ # given
+ expected_payment_method_id = "payment_method_id"
+ expected_additiona_data = {"foo": "bar1"}
+ mock_request.return_value = {
+ "result": PaymentMethodTokenizationResult.ADDITIONAL_ACTION_REQUIRED.name,
+ "id": expected_payment_method_id,
+ "data": expected_additiona_data,
+ }
+
+ plugin = webhook_plugin()
+
+ expected_data = {"foo": "bar"}
+ request_data = PaymentMethodInitializeTokenizationRequestData(
+ user=customer_user,
+ app_identifier=payment_method_initialize_tokenization_app.identifier,
+ channel=channel_USD,
+ data=expected_data,
+ payment_flow_to_support=TokenizedPaymentFlow.INTERACTIVE,
+ )
+
+ previous_value = PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.FAILED_TO_DELIVER,
+ error="Payment method initialize tokenization failed to deliver.",
+ data=None,
+ )
+
+ # when
+ response = plugin.payment_method_initialize_tokenization(
+ request_data, previous_value
+ )
+
+ # then
+ delivery = EventDelivery.objects.get()
+ assert json.loads(delivery.payload.payload) == {
+ "user_id": graphene.Node.to_global_id("User", customer_user.pk),
+ "channel_slug": channel_USD.slug,
+ "data": expected_data,
+ "payment_flow_to_support": "interactive",
+ }
+ mock_request.assert_called_once_with(delivery, timeout=WEBHOOK_SYNC_TIMEOUT)
+
+ assert response == PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.ADDITIONAL_ACTION_REQUIRED,
+ id=to_payment_app_id(
+ payment_method_initialize_tokenization_app, expected_payment_method_id
+ ),
+ data=expected_additiona_data,
+ error=None,
+ )
+
+
+ "result",
+ [
+ PaymentMethodTokenizationResult.SUCCESSFULLY_TOKENIZED.name,
+ PaymentMethodTokenizationResult.ADDITIONAL_ACTION_REQUIRED.name,
+ ],
+)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_payment_method_initialize_tokenization_missing_required_id(
+ mock_request,
+ result,
+ customer_user,
+ webhook_plugin,
+ payment_method_initialize_tokenization_app,
+ channel_USD,
+):
+ # given
+ expected_error_msg = "Missing payment method `id` in response."
+ mock_request.return_value = {
+ "result": result,
+ "data": None,
+ }
+
+ plugin = webhook_plugin()
+
+ expected_data = {"foo": "bar"}
+ request_data = PaymentMethodInitializeTokenizationRequestData(
+ user=customer_user,
+ app_identifier=payment_method_initialize_tokenization_app.identifier,
+ channel=channel_USD,
+ data=expected_data,
+ payment_flow_to_support=TokenizedPaymentFlow.INTERACTIVE,
+ )
+
+ previous_value = PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.FAILED_TO_DELIVER,
+ error="Payment method initialize tokenization failed to deliver.",
+ data=None,
+ )
+
+ # when
+ response = plugin.payment_method_initialize_tokenization(
+ request_data, previous_value
+ )
+
+ # then
+ delivery = EventDelivery.objects.get()
+ assert json.loads(delivery.payload.payload) == {
+ "user_id": graphene.Node.to_global_id("User", customer_user.pk),
+ "channel_slug": channel_USD.slug,
+ "data": expected_data,
+ "payment_flow_to_support": "interactive",
+ }
+ mock_request.assert_called_once_with(delivery, timeout=WEBHOOK_SYNC_TIMEOUT)
+
+ assert response == PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.FAILED_TO_TOKENIZE,
+ error=expected_error_msg,
+ id=None,
+ data=None,
+ )
+
+
+ "result",
+ [
+ PaymentMethodTokenizationResult.SUCCESSFULLY_TOKENIZED,
+ PaymentMethodTokenizationResult.PENDING,
+ ],
+)
[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_expected_result_invalidates_cache_for_app(
+ mocked_request,
+ mocked_cache_get,
+ mocked_cache_set,
+ mocked_cache_delete,
+ result,
+ customer_user,
+ webhook_plugin,
+ payment_method_initialize_tokenization_app,
+ webhook_payment_method_initialize_tokenization_response,
+ channel_USD,
+):
+ # given
+ mocked_cache_get.return_value = None
+
+ webhook = Webhook.objects.create(
+ name="list_stored_payment_methods",
+ app=payment_method_initialize_tokenization_app,
+ target_url="http://localhost:8000/endpoint/",
+ )
+ webhook.events.create(
+ event_type=WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS,
+ )
+ list_stored_payment_methods_response = {"paymentMethods": []}
+ response = webhook_payment_method_initialize_tokenization_response
+ response["result"] = result.name
+ mocked_request.side_effect = [
+ list_stored_payment_methods_response,
+ response,
+ ]
+
+ webhook = payment_method_initialize_tokenization_app.webhooks.first()
+ webhook.subscription_query = PAYMENT_METHOD_INITIALIZE_TOKENIZATION_SESSION
+ webhook.save()
+
+ plugin = webhook_plugin()
+
+ expected_data = {"foo": "bar"}
+
+ request_data = PaymentMethodInitializeTokenizationRequestData(
+ user=customer_user,
+ app_identifier=payment_method_initialize_tokenization_app.identifier,
+ channel=channel_USD,
+ data=expected_data,
+ payment_flow_to_support=TokenizedPaymentFlow.INTERACTIVE,
+ )
+
+ previous_value = PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.FAILED_TO_DELIVER,
+ error="Payment method initialize tokenization failed to deliver.",
+ data=None,
+ )
+
+ 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,
+ payment_method_initialize_tokenization_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.payment_method_initialize_tokenization(
+ request_data, previous_value
+ )
+
+ # then
+ delivery = EventDelivery.objects.filter(
+ event_type=WebhookEventSyncType.PAYMENT_METHOD_INITIALIZE_TOKENIZATION_SESSION
+ ).first()
+ assert json.loads(delivery.payload.payload) == {
+ "user": {"id": graphene.Node.to_global_id("User", customer_user.pk)},
+ "data": expected_data,
+ "channel": {"id": graphene.Node.to_global_id("Channel", channel_USD.pk)},
+ "paymentFlowToSupport": "INTERACTIVE",
+ }
+
+ # 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 == PaymentMethodTokenizationResponseData(
+ result=result,
+ id=to_payment_app_id(
+ payment_method_initialize_tokenization_app,
+ webhook_payment_method_initialize_tokenization_response["id"],
+ ),
+ error=None,
+ data=webhook_payment_method_initialize_tokenization_response["data"],
+ )
diff --git a/saleor/plugins/webhook/tests/test_payment_method_process_tokenization.py b/saleor/plugins/webhook/tests/test_payment_method_process_tokenization.py
new file mode 100644
index 0000000000..c049750f6a
--- /dev/null
+++ b/saleor/plugins/webhook/tests/test_payment_method_process_tokenization.py
@@ -0,0 +1,527 @@
+import json
+
+import graphene
+import mock
+import pytest
+
+from ....core.models import EventDelivery
+from ....payment.interface import (
+ ListStoredPaymentMethodsRequestData,
+ PaymentMethodProcessTokenizationRequestData,
+ PaymentMethodTokenizationResponseData,
+ PaymentMethodTokenizationResult,
+)
+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
+
+PAYMENT_METHOD_PROCESS_TOKENIZATION_SESSION = """
+subscription{
+ event{
+ ...on PaymentMethodProcessTokenizationSession{
+ id
+ user{
+ id
+ }
+ channel{
+ id
+ }
+ data
+ }
+ }
+}
+"""
+
+
+def webhook_payment_method_process_tokenization_response():
+ return {
+ "result": PaymentMethodTokenizationResult.SUCCESSFULLY_TOKENIZED.name,
+ "id": "payment-method-id",
+ "data": {"foo": "bar"},
+ }
+
+
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_payment_method_process_tokenization_with_static_payload(
+ mock_request,
+ customer_user,
+ webhook_plugin,
+ payment_method_process_tokenization_app,
+ webhook_payment_method_process_tokenization_response,
+ channel_USD,
+ app,
+):
+ # given
+ mock_request.return_value = webhook_payment_method_process_tokenization_response
+
+ plugin = webhook_plugin()
+
+ expected_payment_method_id = "payment-method-id"
+ expected_saleor_id = to_payment_app_id(
+ payment_method_process_tokenization_app, expected_payment_method_id
+ )
+
+ expected_data = {"foo": "bar"}
+ request_data = PaymentMethodProcessTokenizationRequestData(
+ user=customer_user,
+ id=expected_saleor_id,
+ channel=channel_USD,
+ data=expected_data,
+ )
+
+ previous_value = PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.FAILED_TO_DELIVER,
+ error="Payment method process tokenization failed to deliver.",
+ data=None,
+ )
+
+ # when
+ response = plugin.payment_method_process_tokenization(request_data, previous_value)
+
+ # then
+ delivery = EventDelivery.objects.get()
+ assert json.loads(delivery.payload.payload) == {
+ "id": expected_payment_method_id,
+ "user_id": graphene.Node.to_global_id("User", customer_user.pk),
+ "channel_slug": channel_USD.slug,
+ "data": expected_data,
+ }
+ mock_request.assert_called_once_with(delivery, timeout=WEBHOOK_SYNC_TIMEOUT)
+
+ assert response == PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.SUCCESSFULLY_TOKENIZED,
+ id=to_payment_app_id(
+ payment_method_process_tokenization_app,
+ webhook_payment_method_process_tokenization_response["id"],
+ ),
+ error=None,
+ data=webhook_payment_method_process_tokenization_response["data"],
+ )
+
+
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_payment_method_process_tokenization_with_subscription_payload(
+ mock_request,
+ customer_user,
+ webhook_plugin,
+ payment_method_process_tokenization_app,
+ webhook_payment_method_process_tokenization_response,
+ channel_USD,
+ app,
+):
+ # given
+ mock_request.return_value = webhook_payment_method_process_tokenization_response
+
+ webhook = payment_method_process_tokenization_app.webhooks.first()
+ webhook.subscription_query = PAYMENT_METHOD_PROCESS_TOKENIZATION_SESSION
+ webhook.save()
+
+ plugin = webhook_plugin()
+
+ expected_payment_method_id = "payment-method-id"
+ expected_saleor_id = to_payment_app_id(
+ payment_method_process_tokenization_app, expected_payment_method_id
+ )
+
+ expected_data = {"foo": "bar"}
+
+ request_data = PaymentMethodProcessTokenizationRequestData(
+ user=customer_user,
+ id=expected_saleor_id,
+ channel=channel_USD,
+ data=expected_data,
+ )
+
+ previous_value = PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.FAILED_TO_DELIVER,
+ error="Payment method process tokenization failed to deliver.",
+ data=None,
+ )
+
+ # when
+ response = plugin.payment_method_process_tokenization(request_data, previous_value)
+
+ # then
+ delivery = EventDelivery.objects.get()
+ assert json.loads(delivery.payload.payload) == {
+ "user": {"id": graphene.Node.to_global_id("User", customer_user.pk)},
+ "data": expected_data,
+ "channel": {"id": graphene.Node.to_global_id("Channel", channel_USD.pk)},
+ "id": expected_payment_method_id,
+ }
+ mock_request.assert_called_once_with(delivery, timeout=WEBHOOK_SYNC_TIMEOUT)
+
+ assert response == PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.SUCCESSFULLY_TOKENIZED,
+ id=to_payment_app_id(
+ payment_method_process_tokenization_app,
+ webhook_payment_method_process_tokenization_response["id"],
+ ),
+ error=None,
+ data=webhook_payment_method_process_tokenization_response["data"],
+ )
+
+
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_payment_method_process_tokenization_missing_correct_response_from_webhook(
+ mock_request,
+ customer_user,
+ webhook_plugin,
+ payment_method_process_tokenization_app,
+ channel_USD,
+ app,
+):
+ # given
+ mock_request.return_value = None
+
+ webhook = payment_method_process_tokenization_app.webhooks.first()
+ webhook.subscription_query = PAYMENT_METHOD_PROCESS_TOKENIZATION_SESSION
+ webhook.save()
+
+ plugin = webhook_plugin()
+
+ expected_id = to_payment_app_id(
+ payment_method_process_tokenization_app, "payment-method-id"
+ )
+ expected_data = {"foo": "bar"}
+
+ request_data = PaymentMethodProcessTokenizationRequestData(
+ user=customer_user,
+ id=expected_id,
+ channel=channel_USD,
+ data=expected_data,
+ )
+
+ previous_value = PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.FAILED_TO_DELIVER,
+ error="Payment method process tokenization failed to deliver.",
+ data=None,
+ )
+
+ # when
+ response = plugin.payment_method_process_tokenization(request_data, previous_value)
+
+ # then
+ delivery = EventDelivery.objects.get()
+
+ mock_request.assert_called_once_with(delivery, timeout=WEBHOOK_SYNC_TIMEOUT)
+
+ assert response == PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.FAILED_TO_DELIVER,
+ error="Failed to delivery request.",
+ id=None,
+ data=None,
+ )
+
+
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_payment_method_process_tokenization_failure_from_app(
+ mock_request,
+ customer_user,
+ webhook_plugin,
+ payment_method_process_tokenization_app,
+ channel_USD,
+ app,
+):
+ # given
+ expected_error_msg = "Expected error msg."
+ mock_request.return_value = {
+ "result": PaymentMethodTokenizationResult.FAILED_TO_TOKENIZE.name,
+ "error": expected_error_msg,
+ "data": None,
+ }
+
+ plugin = webhook_plugin()
+
+ expected_payment_method_id = "payment-method-id"
+ expected_saleor_id = to_payment_app_id(
+ payment_method_process_tokenization_app, expected_payment_method_id
+ )
+
+ expected_data = {"foo": "bar"}
+ request_data = PaymentMethodProcessTokenizationRequestData(
+ user=customer_user,
+ id=expected_saleor_id,
+ channel=channel_USD,
+ data=expected_data,
+ )
+
+ previous_value = PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.FAILED_TO_DELIVER,
+ error="Payment method process tokenization failed to deliver.",
+ data=None,
+ )
+
+ # when
+ response = plugin.payment_method_process_tokenization(request_data, previous_value)
+
+ # then
+ delivery = EventDelivery.objects.get()
+ assert json.loads(delivery.payload.payload) == {
+ "id": expected_payment_method_id,
+ "user_id": graphene.Node.to_global_id("User", customer_user.pk),
+ "channel_slug": channel_USD.slug,
+ "data": expected_data,
+ }
+ mock_request.assert_called_once_with(delivery, timeout=WEBHOOK_SYNC_TIMEOUT)
+
+ assert response == PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.FAILED_TO_TOKENIZE,
+ error=expected_error_msg,
+ id=None,
+ data=None,
+ )
+
+
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_payment_method_process_tokenization_additional_action_required(
+ mock_request,
+ customer_user,
+ webhook_plugin,
+ payment_method_process_tokenization_app,
+ channel_USD,
+ app,
+):
+ # given
+ expected_payment_method_id = "payment-method-id"
+ expected_saleor_id = to_payment_app_id(
+ payment_method_process_tokenization_app, expected_payment_method_id
+ )
+
+ expected_additiona_data = {"foo": "bar1"}
+ mock_request.return_value = {
+ "result": PaymentMethodTokenizationResult.ADDITIONAL_ACTION_REQUIRED.name,
+ "id": expected_payment_method_id,
+ "data": expected_additiona_data,
+ }
+
+ plugin = webhook_plugin()
+
+ expected_data = {"foo": "bar"}
+ request_data = PaymentMethodProcessTokenizationRequestData(
+ user=customer_user,
+ id=expected_saleor_id,
+ channel=channel_USD,
+ data=expected_data,
+ )
+
+ previous_value = PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.FAILED_TO_DELIVER,
+ error="Payment method process tokenization failed to deliver.",
+ data=None,
+ )
+
+ # when
+ response = plugin.payment_method_process_tokenization(request_data, previous_value)
+
+ # then
+ delivery = EventDelivery.objects.get()
+ assert json.loads(delivery.payload.payload) == {
+ "id": expected_payment_method_id,
+ "user_id": graphene.Node.to_global_id("User", customer_user.pk),
+ "channel_slug": channel_USD.slug,
+ "data": expected_data,
+ }
+ mock_request.assert_called_once_with(delivery, timeout=WEBHOOK_SYNC_TIMEOUT)
+
+ assert response == PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.ADDITIONAL_ACTION_REQUIRED,
+ id=to_payment_app_id(
+ payment_method_process_tokenization_app, expected_payment_method_id
+ ),
+ data=expected_additiona_data,
+ error=None,
+ )
+
+
+ "result",
+ [
+ PaymentMethodTokenizationResult.SUCCESSFULLY_TOKENIZED.name,
+ PaymentMethodTokenizationResult.ADDITIONAL_ACTION_REQUIRED.name,
+ ],
+)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_payment_method_process_tokenization_missing_required_id(
+ mock_request,
+ result,
+ customer_user,
+ webhook_plugin,
+ payment_method_process_tokenization_app,
+ channel_USD,
+ app,
+):
+ # given
+ expected_error_msg = "Missing payment method `id` in response."
+ mock_request.return_value = {
+ "result": result,
+ "data": None,
+ }
+
+ plugin = webhook_plugin()
+
+ expected_payment_method_id = "payment-method-id"
+ expected_saleor_id = to_payment_app_id(
+ payment_method_process_tokenization_app, expected_payment_method_id
+ )
+ expected_data = {"foo": "bar"}
+ request_data = PaymentMethodProcessTokenizationRequestData(
+ user=customer_user,
+ id=expected_saleor_id,
+ channel=channel_USD,
+ data=expected_data,
+ )
+
+ previous_value = PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.FAILED_TO_DELIVER,
+ error="Payment method process tokenization failed to deliver.",
+ data=None,
+ )
+
+ # when
+ response = plugin.payment_method_process_tokenization(request_data, previous_value)
+
+ # then
+ delivery = EventDelivery.objects.get()
+ assert json.loads(delivery.payload.payload) == {
+ "user_id": graphene.Node.to_global_id("User", customer_user.pk),
+ "channel_slug": channel_USD.slug,
+ "data": expected_data,
+ "id": expected_payment_method_id,
+ }
+ mock_request.assert_called_once_with(delivery, timeout=WEBHOOK_SYNC_TIMEOUT)
+
+ assert response == PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.FAILED_TO_TOKENIZE,
+ error=expected_error_msg,
+ id=None,
+ data=None,
+ )
+
+
+ "result",
+ [
+ PaymentMethodTokenizationResult.SUCCESSFULLY_TOKENIZED,
+ PaymentMethodTokenizationResult.PENDING,
+ ],
+)
[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_expected_result_invalidates_cache_for_app(
+ mocked_request,
+ mocked_cache_get,
+ mocked_cache_set,
+ mocked_cache_delete,
+ result,
+ customer_user,
+ webhook_plugin,
+ payment_method_process_tokenization_app,
+ webhook_payment_method_process_tokenization_response,
+ channel_USD,
+ app,
+):
+ # given
+ mocked_cache_get.return_value = None
+
+ webhook = Webhook.objects.create(
+ name="list_stored_payment_methods",
+ app=payment_method_process_tokenization_app,
+ target_url="http://localhost:8000/endpoint/",
+ )
+ webhook.events.create(
+ event_type=WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS,
+ )
+ list_stored_payment_methods_response = {"paymentMethods": []}
+ response = webhook_payment_method_process_tokenization_response
+ response["result"] = result.name
+ mocked_request.side_effect = [
+ list_stored_payment_methods_response,
+ response,
+ ]
+
+ webhook = payment_method_process_tokenization_app.webhooks.first()
+ webhook.subscription_query = PAYMENT_METHOD_PROCESS_TOKENIZATION_SESSION
+ webhook.save()
+
+ plugin = webhook_plugin()
+
+ expected_payment_method_id = "payment-method-id"
+ expected_saleor_id = to_payment_app_id(
+ payment_method_process_tokenization_app, expected_payment_method_id
+ )
+ expected_data = {"foo": "bar"}
+
+ request_data = PaymentMethodProcessTokenizationRequestData(
+ user=customer_user,
+ id=expected_saleor_id,
+ channel=channel_USD,
+ data=expected_data,
+ )
+
+ previous_value = PaymentMethodTokenizationResponseData(
+ result=PaymentMethodTokenizationResult.FAILED_TO_DELIVER,
+ error="Payment method process tokenization failed to deliver.",
+ data=None,
+ )
+
+ 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,
+ payment_method_process_tokenization_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.payment_method_process_tokenization(request_data, previous_value)
+
+ # then
+ delivery = EventDelivery.objects.filter(
+ event_type=WebhookEventSyncType.PAYMENT_METHOD_PROCESS_TOKENIZATION_SESSION
+ ).first()
+ assert json.loads(delivery.payload.payload) == {
+ "user": {"id": graphene.Node.to_global_id("User", customer_user.pk)},
+ "data": expected_data,
+ "channel": {"id": graphene.Node.to_global_id("Channel", channel_USD.pk)},
+ "id": expected_payment_method_id,
+ }
+
+ # 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 == PaymentMethodTokenizationResponseData(
+ result=result,
+ id=to_payment_app_id(
+ payment_method_process_tokenization_app,
+ webhook_payment_method_process_tokenization_response["id"],
+ ),
+ error=None,
+ data=webhook_payment_method_process_tokenization_response["data"],
+ )
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 05dc345008..1c7f13b450 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -6561,6 +6561,69 @@ def stored_payment_method_request_delete_app(db, permission_manage_payments):
return app
+def payment_gateway_initialize_tokenization_app(db, permission_manage_payments):
+ app = App.objects.create(
+ name="Payment method request delete",
+ is_active=True,
+ identifier="saleor.payment.app.payment.gateway.initialize.tokenization",
+ )
+ app.tokens.create(name="Default")
+ app.permissions.add(permission_manage_payments)
+
+ webhook = Webhook.objects.create(
+ name="payment_gateway_initialize_tokenization",
+ app=app,
+ target_url="http://localhost:8000/endpoint/",
+ )
+ webhook.events.create(
+ event_type=WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_TOKENIZATION_SESSION,
+ )
+ return app
+
+
+def payment_method_initialize_tokenization_app(db, permission_manage_payments):
+ app = App.objects.create(
+ name="Payment method initialize tokenization",
+ is_active=True,
+ identifier="saleor.payment.app.payment.method.initialize.tokenization",
+ )
+ app.tokens.create(name="Default")
+ app.permissions.add(permission_manage_payments)
+
+ webhook = Webhook.objects.create(
+ name="payment_method_initialize_tokenization",
+ app=app,
+ target_url="http://localhost:8000/endpoint/",
+ )
+ webhook.events.create(
+ event_type=WebhookEventSyncType.PAYMENT_METHOD_INITIALIZE_TOKENIZATION_SESSION,
+ )
+ return app
+
+
+def payment_method_process_tokenization_app(db, permission_manage_payments):
+ app = App.objects.create(
+ name="Payment method process tokenization",
+ is_active=True,
+ identifier="saleor.payment.app.payment.method.process.tokenization",
+ )
+ app.tokens.create(name="Default")
+ app.permissions.add(permission_manage_payments)
+
+ webhook = Webhook.objects.create(
+ name="payment_method_process_tokenization",
+ app=app,
+ target_url="http://localhost:8000/endpoint/",
+ )
+ webhook.events.create(
+ event_type=WebhookEventSyncType.PAYMENT_METHOD_PROCESS_TOKENIZATION_SESSION,
+ )
+ 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 85318a0782..7f546132b8 100644
--- a/saleor/webhook/event_types.py
+++ b/saleor/webhook/event_types.py
@@ -750,6 +750,16 @@ class WebhookEventSyncType:
LIST_STORED_PAYMENT_METHODS = "list_stored_payment_methods"
STORED_PAYMENT_METHOD_DELETE_REQUESTED = "stored_payment_method_delete_requested"
+ PAYMENT_GATEWAY_INITIALIZE_TOKENIZATION_SESSION = (
+ "payment_gateway_initialize_tokenization_session"
+ )
+ PAYMENT_METHOD_INITIALIZE_TOKENIZATION_SESSION = (
+ "payment_method_initialize_tokenization_session"
+ )
+ PAYMENT_METHOD_PROCESS_TOKENIZATION_SESSION = (
+ "payment_method_process_tokenization_session"
+ )
+
EVENT_MAP: dict[str, dict[str, Any]] = {
PAYMENT_LIST_GATEWAYS: {
"name": "List payment gateways",
@@ -831,6 +841,18 @@ class WebhookEventSyncType:
"name": "Request deletion of a tokenized payment method.",
"permission": PaymentPermissions.HANDLE_PAYMENTS,
},
+ PAYMENT_GATEWAY_INITIALIZE_TOKENIZATION_SESSION: {
+ "name": "Initialize payment gateway tokenization session.",
+ "permission": PaymentPermissions.HANDLE_PAYMENTS,
+ },
+ PAYMENT_METHOD_INITIALIZE_TOKENIZATION_SESSION: {
+ "name": "Initialize payment method tokenization session.",
+ "permission": PaymentPermissions.HANDLE_PAYMENTS,
+ },
+ PAYMENT_METHOD_PROCESS_TOKENIZATION_SESSION: {
+ "name": "Process payment method tokenization.",
+ "permission": PaymentPermissions.HANDLE_PAYMENTS,
+ },
}
CHOICES = [