Skip to content

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

[Programmatic payments] payment method api (#13581)

Maciej Korycinski6b11c389d4c7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 68fbc1bbcb..a806b8e5fe 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -85,6 +85,7 @@ Shipping methods can be removed by the user after it has been assigned to a chec
- `checkoutShippingAddressUpdate`, `checkoutBillingAddressUpdate`, `shopAddressUpdate`, `warehouseUpdate`
- Add `metadata` to `AddressInput` field
- Add support for unhandled field `Shop.trackInventoryByDefault` for `productVariantCreate` and `productVariantBulkCreate` - #13492 by @Smit-Parmar
+- Add `storedPaymentMethods` field to `User` and `Checkout` type - #13581
- - Add `AttributeBulkUpdate` mutation - #13532 by @SzymJ
- Better checkout error feedback - #13458 by @korycins
diff --git a/saleor/graphql/account/tests/queries/test_me.py b/saleor/graphql/account/tests/queries/test_me.py
index eba1d4831c..698ccd7724 100644
--- a/saleor/graphql/account/tests/queries/test_me.py
+++ b/saleor/graphql/account/tests/queries/test_me.py
@@ -1,6 +1,14 @@
import graphene
+import mock
from .....order.models import FulfillmentStatus
+from .....payment.interface import (
+ ListStoredPaymentMethodsRequestData,
+ PaymentGateway,
+ PaymentMethodCreditCardInfo,
+ PaymentMethodData,
+)
+from ....payment.enums import TokenizedPaymentFlowEnum
from ....tests.utils import assert_no_permission, get_graphql_content
ME_QUERY = """
@@ -271,3 +279,125 @@ def test_me_with_cancelled_fulfillments(
fulfillments = order["fulfillments"]
assert len(fulfillments) == 1
assert fulfillments[0]["status"] == FulfillmentStatus.FULFILLED.upper()
+
+
+QUERY_ME_WITH_STORED_PAYMENT_METHODS = """
+query Me($channel: String!) {
+ me{
+ storedPaymentMethods(channel: $channel){
+ id
+ gateway{
+ name
+ id
+ config{
+ field
+ value
+ }
+ currencies
+ }
+ paymentMethodId
+ creditCardInfo{
+ brand
+ firstDigits
+ lastDigits
+ expMonth
+ expYear
+ }
+ supportedPaymentFlows
+ type
+ name
+ data
+ }
+ }
+}
+"""
+
+
[email protected]("saleor.plugins.manager.PluginsManager.list_stored_payment_methods")
+def test_me_query_stored_payment_methods(
+ mocked_list_stored_payment_methods, user_api_client, channel_USD, customer_user
+):
+ # given
+ payment_method_id = "app:payment-method-id"
+ external_id = "payment-method-id"
+ supported_payment_flow = TokenizedPaymentFlowEnum.INTERACTIVE
+ payment_method_type = "credit-card"
+ payment_method_name = "Payment method name"
+ payment_method_data = {"additional_data": "value"}
+
+ payment_gateway_id = "gateway-id"
+ payment_gateway_name = "gateway-name"
+
+ credit_card_brand = "brand"
+ credit_card_first_digits = "123"
+ credit_card_last_digits = "456"
+ credit_card_exp_month = 1
+ credit_card_exp_year = 2021
+
+ mocked_list_stored_payment_methods.return_value = [
+ PaymentMethodData(
+ id=payment_method_id,
+ external_id=external_id,
+ supported_payment_flows=[supported_payment_flow.value],
+ type=payment_method_type,
+ credit_card_info=PaymentMethodCreditCardInfo(
+ brand=credit_card_brand,
+ first_digits=credit_card_first_digits,
+ last_digits=credit_card_last_digits,
+ exp_month=credit_card_exp_month,
+ exp_year=credit_card_exp_year,
+ ),
+ name=payment_method_name,
+ data=payment_method_data,
+ gateway=PaymentGateway(
+ id=payment_gateway_id,
+ name=payment_gateway_name,
+ currencies=[channel_USD.currency_code],
+ config=[],
+ ),
+ )
+ ]
+
+ request_data = ListStoredPaymentMethodsRequestData(
+ user=user_api_client.user,
+ channel=channel_USD,
+ )
+
+ query = QUERY_ME_WITH_STORED_PAYMENT_METHODS
+
+ # when
+ response = user_api_client.post_graphql(
+ query,
+ variables={
+ "channel": channel_USD.slug,
+ },
+ )
+
+ # then
+ mocked_list_stored_payment_methods.assert_called_once_with(request_data)
+ content = get_graphql_content(response)
+
+ data = content["data"]["me"]
+ assert data["storedPaymentMethods"] == [
+ {
+ "id": payment_method_id,
+ "gateway": {
+ "name": payment_gateway_name,
+ "id": payment_gateway_id,
+ "config": [],
+ "currencies": [channel_USD.currency_code],
+ },
+ "paymentMethodId": external_id,
+ "creditCardInfo": {
+ "brand": credit_card_brand,
+ "firstDigits": credit_card_first_digits,
+ "lastDigits": credit_card_last_digits,
+ "expMonth": credit_card_exp_month,
+ "expYear": credit_card_exp_year,
+ },
+ "supportedPaymentFlows": [supported_payment_flow.name],
+ "type": payment_method_type,
+ "name": payment_method_name,
+ "data": payment_method_data,
+ }
+ ]
diff --git a/saleor/graphql/account/tests/queries/test_user.py b/saleor/graphql/account/tests/queries/test_user.py
index f7d906b583..ff0f529805 100644
--- a/saleor/graphql/account/tests/queries/test_user.py
+++ b/saleor/graphql/account/tests/queries/test_user.py
@@ -1,6 +1,7 @@
from unittest.mock import MagicMock
import graphene
+import mock
import pytest
from django.core.files import File
@@ -1279,3 +1280,63 @@ def test_unauthenticated_query_user_by_email_for_federation(api_client, customer
)
content = get_graphql_content(response)
assert content["data"]["_entities"] == [None]
+
+
+USER_QUERY_WITH_STORED_PAYMENT_METHODS = """
+query User($id: ID, $channel: String!) {
+ user(id: $id) {
+ storedPaymentMethods(channel: $channel){
+ id
+ gateway{
+ name
+ id
+ config{
+ field
+ value
+ }
+ currencies
+ }
+ paymentMethodId
+ creditCardInfo{
+ brand
+ firstDigits
+ lastDigits
+ expMonth
+ expYear
+ }
+ supportedPaymentFlows
+ type
+ name
+ data
+ }
+ }
+}
+"""
+
+
[email protected]("saleor.plugins.manager.PluginsManager.list_stored_payment_methods")
+def test_query_customer_stored_payment_methods(
+ mocked_list_stored_payment_methods,
+ staff_api_client,
+ permission_manage_users,
+ customer_user,
+ channel_USD,
+):
+ query = USER_QUERY_WITH_STORED_PAYMENT_METHODS
+ staff_api_client.user.user_permissions.add(permission_manage_users)
+
+ # when
+ response = staff_api_client.post_graphql(
+ query,
+ variables={
+ "channel": channel_USD.slug,
+ "id": graphene.Node.to_global_id("User", customer_user.pk),
+ },
+ )
+
+ # then
+ assert not mocked_list_stored_payment_methods.called
+
+ content = get_graphql_content(response)
+
+ assert content["data"]["user"]["storedPaymentMethods"] == []
diff --git a/saleor/graphql/account/types.py b/saleor/graphql/account/types.py
index 9f9cfee130..02f6f2a871 100644
--- a/saleor/graphql/account/types.py
+++ b/saleor/graphql/account/types.py
@@ -12,6 +12,7 @@ from ...checkout.utils import get_user_checkout
from ...core.exceptions import PermissionDenied
from ...graphql.meta.inputs import MetadataInput
from ...order import OrderStatus
+from ...payment.interface import ListStoredPaymentMethodsRequestData
from ...permission.auth_filters import AuthorizationFilters
from ...permission.enums import AccountPermissions, AppPermission, OrderPermissions
from ...thumbnail.utils import (
@@ -22,6 +23,7 @@ from ...thumbnail.utils import (
from ..account.utils import check_is_owner_or_has_one_of_perms
from ..app.dataloaders import AppByIdLoader, get_app_promise
from ..app.types import App
+from ..channel.dataloaders import ChannelBySlugLoader
from ..channel.types import Channel
from ..checkout.dataloaders import CheckoutByUserAndChannelLoader, CheckoutByUserLoader
from ..checkout.types import Checkout, CheckoutCountableConnection
@@ -55,6 +57,7 @@ from ..core.utils import from_global_id_or_error, str_to_enum, to_global_id_or_n
from ..giftcard.dataloaders import GiftCardsByUserLoader
from ..meta.types import ObjectWithMetadata
from ..order.dataloaders import OrderLineByIdLoader, OrdersByUserLoader
+from ..payment.types import StoredPaymentMethod
from ..plugins.dataloaders import get_plugin_manager_promise
from ..utils import format_permissions_for_display, get_user_or_app_from_context
from .dataloaders import (
@@ -399,7 +402,10 @@ class User(ModelObjectType[models.User]):
)
stored_payment_sources = NonNullList(
"saleor.graphql.payment.types.PaymentSource",
- description="List of stored payment sources.",
+ description=(
+ "List of stored payment sources. The field returns a list of payment "
+ "sources stored for payment plugins."
+ ),
channel=graphene.String(
description="Slug of a channel for which the data should be returned."
),
@@ -427,6 +433,19 @@ class User(ModelObjectType[models.User]):
required=True,
description="The data when the user last update the account information.",
)
+ stored_payment_methods = NonNullList(
+ StoredPaymentMethod,
+ description=(
+ "Returns a list of user's stored payment methods that can be used in "
+ "provided channel. The field returns a list of stored payment methods by "
+ "payment apps. When `amount` is not provided, 0 will be used as default "
+ "value." + ADDED_IN_315 + PREVIEW_FEATURE
+ ),
+ channel=graphene.String(
+ description="Slug of a channel for which the data should be returned.",
+ required=True,
+ ),
+ )
class Meta:
description = "Represents user data."
@@ -666,6 +685,31 @@ class User(ModelObjectType[models.User]):
results.append(users_by_email.get(root.email))
return results
+ @staticmethod
+ def resolve_stored_payment_methods(
+ root: models.User,
+ info: ResolveInfo,
+ channel: str,
+ ):
+ requestor = get_user_or_app_from_context(info.context)
+ if not requestor or requestor.id != root.id:
+ return []
+
+ def get_stored_payment_methods(data):
+ channel_obj, manager = data
+ request_data = ListStoredPaymentMethodsRequestData(
+ user=root,
+ channel=channel_obj,
+ )
+ return manager.list_stored_payment_methods(request_data)
+
+ return Promise.all(
+ [
+ ChannelBySlugLoader(info.context).load(channel),
+ get_plugin_manager_promise(info.context),
+ ]
+ ).then(get_stored_payment_methods)
+
class UserCountableConnection(CountableConnection):
class Meta:
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.py
index f218f54b82..75113a0bac 100644
--- a/saleor/graphql/checkout/tests/test_checkout.py
+++ b/saleor/graphql/checkout/tests/test_checkout.py
@@ -24,6 +24,12 @@ from ....core.prices import quantize_price
from ....discount import DiscountValueType, VoucherType
from ....discount.utils import generate_sale_discount_objects_for_checkout
from ....payment import TransactionAction
+from ....payment.interface import (
+ ListStoredPaymentMethodsRequestData,
+ PaymentGateway,
+ PaymentMethodCreditCardInfo,
+ PaymentMethodData,
+)
from ....plugins.manager import get_plugins_manager
from ....plugins.tests.sample_plugins import ActiveDummyPaymentGateway
from ....product.models import ProductVariant
@@ -33,6 +39,7 @@ from ....tests.utils import dummy_editorjs
from ....warehouse import WarehouseClickAndCollectOption
from ....warehouse.models import PreorderReservation, Reservation, Stock, Warehouse
from ...core.utils import to_global_id_or_none
+from ...payment.enums import TokenizedPaymentFlowEnum
from ...tests.utils import assert_no_permission, get_graphql_content
from ..enums import CheckoutAuthorizeStatusEnum, CheckoutChargeStatusEnum
from ..mutations.utils import (
@@ -2446,3 +2453,229 @@ def test_checkout_no_metadata(checkout, user_api_client):
assert content["data"]["checkout"]["metadata"] == []
assert content["data"]["checkout"]["metafield"] is None
assert content["data"]["checkout"]["metafields"] == {}
+
+
+QUERY_CHECKOUT_STORED_PAYMENT_METHODS = """
+query getCheckout($id: ID, $amount: PositiveDecimal) {
+ checkout(id: $id) {
+ storedPaymentMethods(amount: $amount){
+ id
+ gateway{
+ name
+ id
+ config{
+ field
+ value
+ }
+ currencies
+ }
+ paymentMethodId
+ creditCardInfo{
+ brand
+ firstDigits
+ lastDigits
+ expMonth
+ expYear
+ }
+ supportedPaymentFlows
+ type
+ name
+ data
+ }
+ }
+}
+"""
+
+
[email protected]("saleor.plugins.manager.PluginsManager.list_stored_payment_methods")
+def test_checkout_with_stored_payment_methods_empty_response(
+ mocked_list_stored_payment_methods,
+ user_api_client,
+ checkout_with_prices,
+):
+ # given
+ checkout_with_prices.user = user_api_client.user
+ checkout_with_prices.save(update_fields=["user"])
+
+ mocked_list_stored_payment_methods.return_value = []
+ query = QUERY_CHECKOUT_STORED_PAYMENT_METHODS
+ variables = {"id": to_global_id_or_none(checkout_with_prices)}
+
+ request_data = ListStoredPaymentMethodsRequestData(
+ user=checkout_with_prices.user,
+ channel=checkout_with_prices.channel,
+ )
+
+ # when
+ response = user_api_client.post_graphql(
+ query,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ mocked_list_stored_payment_methods.assert_called_once_with(request_data)
+ assert content["data"]["checkout"]["storedPaymentMethods"] == []
+
+
[email protected]("saleor.plugins.manager.PluginsManager.list_stored_payment_methods")
+def test_checkout_with_stored_payment_methods(
+ mocked_list_stored_payment_methods,
+ user_api_client,
+ checkout_with_prices,
+):
+ # given
+ checkout_with_prices.user = user_api_client.user
+ checkout_with_prices.save(update_fields=["user"])
+
+ payment_method_id = "app:payment-method-id"
+ external_id = "payment-method-id"
+ supported_payment_flow = TokenizedPaymentFlowEnum.INTERACTIVE
+ payment_method_type = "credit-card"
+ payment_method_name = "Payment method name"
+ payment_method_data = {"additional_data": "value"}
+
+ payment_gateway_id = "gateway-id"
+ payment_gateway_name = "gateway-name"
+
+ credit_card_brand = "brand"
+ credit_card_first_digits = "123"
+ credit_card_last_digits = "456"
+ credit_card_exp_month = 1
+ credit_card_exp_year = 2021
+
+ mocked_list_stored_payment_methods.return_value = [
+ PaymentMethodData(
+ id=payment_method_id,
+ external_id=external_id,
+ supported_payment_flows=[supported_payment_flow.value],
+ type=payment_method_type,
+ credit_card_info=PaymentMethodCreditCardInfo(
+ brand=credit_card_brand,
+ first_digits=credit_card_first_digits,
+ last_digits=credit_card_last_digits,
+ exp_month=credit_card_exp_month,
+ exp_year=credit_card_exp_year,
+ ),
+ name=payment_method_name,
+ data=payment_method_data,
+ gateway=PaymentGateway(
+ id=payment_gateway_id,
+ name=payment_gateway_name,
+ currencies=[checkout_with_prices.currency],
+ config=[],
+ ),
+ )
+ ]
+
+ query = QUERY_CHECKOUT_STORED_PAYMENT_METHODS
+ variables = {"id": to_global_id_or_none(checkout_with_prices)}
+
+ request_data = ListStoredPaymentMethodsRequestData(
+ user=checkout_with_prices.user,
+ channel=checkout_with_prices.channel,
+ )
+
+ # when
+ response = user_api_client.post_graphql(
+ query,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ mocked_list_stored_payment_methods.assert_called_once_with(request_data)
+ assert content["data"]["checkout"]["storedPaymentMethods"] == [
+ {
+ "id": payment_method_id,
+ "gateway": {
+ "name": payment_gateway_name,
+ "id": payment_gateway_id,
+ "config": [],
+ "currencies": [checkout_with_prices.currency],
+ },
+ "paymentMethodId": external_id,
+ "creditCardInfo": {
+ "brand": credit_card_brand,
+ "firstDigits": credit_card_first_digits,
+ "lastDigits": credit_card_last_digits,
+ "expMonth": credit_card_exp_month,
+ "expYear": credit_card_exp_year,
+ },
+ "supportedPaymentFlows": [supported_payment_flow.name],
+ "type": payment_method_type,
+ "name": payment_method_name,
+ "data": payment_method_data,
+ }
+ ]
+
+
[email protected]("saleor.plugins.manager.PluginsManager.list_stored_payment_methods")
+def test_checkout_with_stored_payment_methods_requested_by_staff_user(
+ mocked_list_stored_payment_methods,
+ staff_api_client,
+ checkout_with_prices,
+ customer_user2,
+ permission_manage_checkouts,
+ permission_manage_users,
+):
+ # given
+ checkout_with_prices.user = customer_user2
+ checkout_with_prices.save(update_fields=["user"])
+
+ staff_api_client.user.user_permissions.add(permission_manage_checkouts)
+
+ mocked_list_stored_payment_methods.return_value = []
+ query = QUERY_CHECKOUT_STORED_PAYMENT_METHODS
+ variables = {"id": to_global_id_or_none(checkout_with_prices)}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query,
+ variables,
+ )
+
+ # then
+ assert customer_user2 != staff_api_client.user
+
+ content = get_graphql_content(response)
+
+ assert not mocked_list_stored_payment_methods.called
+ assert content["data"]["checkout"]["storedPaymentMethods"] == []
+
+
[email protected]("saleor.plugins.manager.PluginsManager.list_stored_payment_methods")
+def test_checkout_with_stored_payment_methods_requested_by_app(
+ mocked_list_stored_payment_methods,
+ app_api_client,
+ checkout_with_prices,
+ customer_user2,
+ permission_manage_checkouts,
+ permission_manage_users,
+):
+ # given
+ app = app_api_client.app
+ app.permissions.add(
+ permission_manage_checkouts,
+ permission_manage_users,
+ )
+ checkout_with_prices.user = customer_user2
+ checkout_with_prices.save(update_fields=["user"])
+
+ mocked_list_stored_payment_methods.return_value = []
+ query = QUERY_CHECKOUT_STORED_PAYMENT_METHODS
+ variables = {"id": to_global_id_or_none(checkout_with_prices)}
+
+ # when
+ response = app_api_client.post_graphql(
+ query,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert not mocked_list_stored_payment_methods.called
+ assert content["data"]["checkout"]["storedPaymentMethods"] == []
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index 1cfae81b26..ae3a6875eb 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -1,3 +1,4 @@
+from decimal import Decimal
from typing import TYPE_CHECKING, Optional
import graphene
@@ -12,6 +13,7 @@ from ...checkout.calculations import fetch_checkout_data
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.enums import (
AccountPermissions,
CheckoutPermissions,
@@ -22,7 +24,7 @@ from ...tax.utils import get_display_gross_prices
from ...warehouse import models as warehouse_models
from ...warehouse.reservations import is_reservation_enabled
from ...webhook.event_types import WebhookEventSyncType
-from ..account.dataloaders import AddressByIdLoader
+from ..account.dataloaders import AddressByIdLoader, UserByUserIdLoader
from ..account.utils import check_is_owner_or_has_one_of_perms
from ..channel import ChannelContext
from ..channel.dataloaders import ChannelByIdLoader
@@ -45,10 +47,10 @@ from ..core.descriptions import (
DEPRECATED_IN_3X_FIELD,
PREVIEW_FEATURE,
)
-from ..core.doc_category import DOC_CATEGORY_CHECKOUT, DOC_CATEGORY_PAYMENTS
+from ..core.doc_category import DOC_CATEGORY_CHECKOUT
from ..core.enums import LanguageCodeEnum
from ..core.fields import BaseField
-from ..core.scalars import UUID
+from ..core.scalars import UUID, PositiveDecimal
from ..core.tracing import traced_resolver
from ..core.types import BaseObjectType, ModelObjectType, Money, NonNullList, TaxedMoney
from ..core.utils import CHECKOUT_CALCULATE_TAXES_MESSAGE, WebhookEventInfo, str_to_enum
@@ -57,7 +59,7 @@ from ..giftcard.dataloaders import GiftCardsByCheckoutIdLoader
from ..giftcard.types import GiftCard
from ..meta import resolvers as MetaResolvers
from ..meta.types import ObjectWithMetadata, _filter_metadata
-from ..payment.types import TransactionItem
+from ..payment.types import PaymentGateway, StoredPaymentMethod, TransactionItem
from ..plugins.dataloaders import (
get_plugin_manager_promise,
plugin_manager_promise_callback,
@@ -196,37 +198,6 @@ class CheckoutProblem(graphene.Union):
return super(CheckoutProblem, cls).resolve_type(instance, info)
-class GatewayConfigLine(BaseObjectType):
- field = graphene.String(required=True, description="Gateway config key.")
- value = graphene.String(description="Gateway config value for key.")
-
- class Meta:
- description = "Payment gateway client configuration key and value pair."
- doc_category = DOC_CATEGORY_PAYMENTS
-
-
-class PaymentGateway(BaseObjectType):
- name = graphene.String(required=True, description="Payment gateway name.")
- id = graphene.ID(required=True, description="Payment gateway ID.")
- config = NonNullList(
- GatewayConfigLine,
- required=True,
- description="Payment gateway client configuration.",
- )
- currencies = NonNullList(
- graphene.String,
- required=True,
- description="Payment gateway supported currencies.",
- )
-
- class Meta:
- description = (
- "Available payment gateway backend with configuration "
- "necessary to setup client."
- )
- doc_category = DOC_CATEGORY_PAYMENTS
-
-
class CheckoutLine(ModelObjectType[models.CheckoutLine]):
id = graphene.GlobalID(required=True, description="The ID of the checkout line.")
variant = graphene.Field(
@@ -777,6 +748,18 @@ class Checkout(ModelObjectType[models.Checkout]):
),
],
)
+ stored_payment_methods = NonNullList(
+ StoredPaymentMethod,
+ description=(
+ "List of user's stored payment methods that can be used in this checkout "
+ "session. It uses the channel that the checkout was created in. "
+ "When `amount` is not provided, `checkout.total` will be used as a default "
+ "value." + ADDED_IN_315 + PREVIEW_FEATURE
+ ),
+ amount=PositiveDecimal(
+ description="Amount that will be used to fetch stored payment methods."
+ ),
+ )
problems = NonNullList(
CheckoutProblem,
@@ -1213,6 +1196,31 @@ class Checkout(ModelObjectType[models.Checkout]):
)
return checkout_problems_dataloader.load(root.pk)
+ @staticmethod
+ def resolve_stored_payment_methods(
+ root: models.Checkout, info: ResolveInfo, amount: Optional[Decimal] = None
+ ):
+ if root.user_id is None:
+ return []
+ requestor = get_user_or_app_from_context(info.context)
+ if not requestor or requestor.id != root.user_id:
+ return []
+
+ def _resolve_stored_payment_methods(data):
+ channel, user, manager = data
+ request_data = ListStoredPaymentMethodsRequestData(
+ user=user,
+ channel=channel,
+ )
+ return manager.list_stored_payment_methods(request_data)
+
+ manager = get_plugin_manager_promise(info.context)
+ channel_loader = ChannelByIdLoader(info.context).load(root.channel_id)
+ user_loader = UserByUserIdLoader(info.context).load(root.user_id)
+ return Promise.all([channel_loader, user_loader, manager]).then(
+ _resolve_stored_payment_methods
+ )
+
class CheckoutCountableConnection(CountableConnection):
class Meta:
diff --git a/saleor/graphql/payment/enums.py b/saleor/graphql/payment/enums.py
index ab5015d71d..2f17943426 100644
--- a/saleor/graphql/payment/enums.py
+++ b/saleor/graphql/payment/enums.py
@@ -1,6 +1,7 @@
from ...payment import (
ChargeStatus,
StorePaymentMethod,
+ TokenizedPaymentFlow,
TransactionAction,
TransactionEventType,
TransactionKind,
@@ -73,3 +74,9 @@ StorePaymentMethodEnum = to_enum(
StorePaymentMethod, type_name="StorePaymentMethodEnum", description=description
)
StorePaymentMethodEnum.doc_category = DOC_CATEGORY_PAYMENTS
+
+TokenizedPaymentFlowEnum = to_enum(
+ TokenizedPaymentFlow,
+ type_name="TokenizedPaymentFlowEnum",
+ description=TokenizedPaymentFlow.__doc__,
+)
diff --git a/saleor/graphql/payment/types.py b/saleor/graphql/payment/types.py
index efb79b086a..591a48cb49 100644
--- a/saleor/graphql/payment/types.py
+++ b/saleor/graphql/payment/types.py
@@ -7,6 +7,7 @@ from graphene import relay
from ...core.exceptions import PermissionDenied
from ...payment import models
+from ...payment.interface import PaymentMethodData
from ...permission.enums import OrderPermissions
from ..account.dataloaders import UserByUserIdLoader
from ..app.dataloaders import AppByIdLoader, AppsByAppIdentifierLoader
@@ -18,10 +19,12 @@ from ..core.descriptions import (
ADDED_IN_34,
ADDED_IN_36,
ADDED_IN_313,
+ ADDED_IN_315,
PREVIEW_FEATURE,
)
from ..core.doc_category import DOC_CATEGORY_PAYMENTS
from ..core.fields import JSONString, PermissionsField
+from ..core.scalars import JSON
from ..core.tracing import traced_resolver
from ..core.types import BaseObjectType, ModelObjectType, Money, NonNullList
from ..meta.permissions import public_payment_permissions
@@ -36,6 +39,7 @@ from .dataloaders import (
from .enums import (
OrderAction,
PaymentChargeStatusEnum,
+ TokenizedPaymentFlowEnum,
TransactionActionEnum,
TransactionEventTypeEnum,
TransactionKindEnum,
@@ -588,3 +592,87 @@ class TransactionItem(ModelObjectType[models.TransactionItem]):
return model.objects.get(lookup)
except model.DoesNotExist:
return None
+
+
+class GatewayConfigLine(BaseObjectType):
+ field = graphene.String(required=True, description="Gateway config key.")
+ value = graphene.String(description="Gateway config value for key.")
+
+ class Meta:
+ description = "Payment gateway client configuration key and value pair."
+ doc_category = DOC_CATEGORY_PAYMENTS
+
+
+class PaymentGateway(BaseObjectType):
+ name = graphene.String(required=True, description="Payment gateway name.")
+ id = graphene.ID(required=True, description="Payment gateway ID.")
+ config = NonNullList(
+ GatewayConfigLine,
+ required=True,
+ description="Payment gateway client configuration.",
+ )
+ currencies = NonNullList(
+ graphene.String,
+ required=True,
+ description="Payment gateway supported currencies.",
+ )
+
+ class Meta:
+ description = (
+ "Available payment gateway backend with configuration "
+ "necessary to setup client."
+ )
+ doc_category = DOC_CATEGORY_PAYMENTS
+
+
+class StoredPaymentMethod(BaseObjectType):
+ id = graphene.ID(required=True, description="Stored payment method ID.")
+
+ gateway = graphene.Field(
+ PaymentGateway,
+ required=True,
+ description="Payment gateway that stores this payment method.",
+ )
+ payment_method_id = graphene.String(
+ description=(
+ "ID of stored payment method used to make payment actions. "
+ "Note: method ID is unique only within the payment gateway."
+ ),
+ required=True,
+ )
+
+ credit_card_info = graphene.Field(
+ CreditCard,
+ required=False,
+ description="Stored credit card details if available.",
+ )
+
+ supported_payment_flows = graphene.Field(NonNullList(TokenizedPaymentFlowEnum))
+
+ type = graphene.String(
+ required=True,
+ description="Type of the payment method. Example: credit card, wallet, etc.",
+ )
+ name = graphene.String(
+ description=(
+ "Payment method name. Example: last 4 digits of credit card, obfuscated "
+ "email, etc."
+ )
+ )
+ data = graphene.Field(
+ JSON,
+ description=(
+ "JSON data returned by Payment Provider app for this payment method."
+ ),
+ )
+
+ class Meta:
+ description = (
+ "Represents a payment method stored for user (tokenized) in payment "
+ "gateway." + ADDED_IN_315 + PREVIEW_FEATURE
+ )
+ doc_category = DOC_CATEGORY_PAYMENTS
+
+ @staticmethod
+ def resolve_payment_method_id(root: PaymentMethodData, _info: ResolveInfo):
+ return root.external_id
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 320c530544..3e0d5ab0db 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -2275,6 +2275,7 @@ enum WebhookEventTypeEnum @doc(category: "Webhooks") {
PAYMENT_GATEWAY_INITIALIZE_SESSION
TRANSACTION_INITIALIZE_SESSION
TRANSACTION_PROCESS_SESSION
+ LIST_STORED_PAYMENT_METHODS
}
"""Synchronous webhook event."""
@@ -2361,6 +2362,7 @@ enum WebhookEventTypeSyncEnum @doc(category: "Webhooks") {
PAYMENT_GATEWAY_INITIALIZE_SESSION
TRANSACTION_INITIALIZE_SESSION
TRANSACTION_PROCESS_SESSION
+ LIST_STORED_PAYMENT_METHODS
}
"""Asynchronous webhook event."""
@@ -10024,7 +10026,9 @@ type User implements Node & ObjectWithMetadata @doc(category: "Users") {
"""
events: [CustomerEvent!]
- """List of stored payment sources."""
+ """
+ List of stored payment sources. The field returns a list of payment sources stored for payment plugins.
+ """
storedPaymentSources(
"""Slug of a channel for which the data should be returned."""
channel: String
@@ -10054,6 +10058,18 @@ type User implements Node & ObjectWithMetadata @doc(category: "Users") {
"""The data when the user last update the account information."""
updatedAt: DateTime!
+
+ """
+ Returns a list of user's stored payment methods that can be used in provided channel. The field returns a list of stored payment methods by payment apps. When `amount` is not provided, 0 will be used as default value.
+
+ Added in Saleor 3.15.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ storedPaymentMethods(
+ """Slug of a channel for which the data should be returned."""
+ channel: String!
+ ): [StoredPaymentMethod!]
}
"""Checkout object."""
@@ -10307,6 +10323,18 @@ type Checkout implements Node & ObjectWithMetadata @doc(category: "Checkout") {
"""
chargeStatus: CheckoutChargeStatusEnum! @webhookEventsInfo(asyncEvents: [], syncEvents: [CHECKOUT_CALCULATE_TAXES])
+ """
+ List of user's stored payment methods that can be used in this checkout session. It uses the channel that the checkout was created in. When `amount` is not provided, `checkout.total` will be used as a default value.
+
+ Added in Saleor 3.15.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ storedPaymentMethods(
+ """Amount that will be used to fetch stored payment methods."""
+ amount: PositiveDecimal
+ ): [StoredPaymentMethod!]
+
"""
List of problems with the checkout.
@@ -12365,6 +12393,54 @@ enum CheckoutChargeStatusEnum @doc(category: "Checkout") {
OVERCHARGED
}
+"""
+Represents a payment method stored for user (tokenized) in payment gateway.
+
+Added in Saleor 3.15.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+type StoredPaymentMethod @doc(category: "Payments") {
+ """Stored payment method ID."""
+ id: ID!
+
+ """Payment gateway that stores this payment method."""
+ gateway: PaymentGateway!
+
+ """
+ ID of stored payment method used to make payment actions. Note: method ID is unique only within the payment gateway.
+ """
+ paymentMethodId: String!
+
+ """Stored credit card details if available."""
+ creditCardInfo: CreditCard
+ supportedPaymentFlows: [TokenizedPaymentFlowEnum!]
+
+ """Type of the payment method. Example: credit card, wallet, etc."""
+ type: String!
+
+ """
+ Payment method name. Example: last 4 digits of credit card, obfuscated email, etc.
+ """
+ name: String
+
+ """JSON data returned by Payment Provider app for this payment method."""
+ data: JSON
+}
+
+"""
+Represents possible tokenized payment flows that can be used to process payment.
+
+ The following flows are possible:
+ INTERACTIVE - Payment method can be used for 1 click checkout - it's prefilled in
+ checkout form (might require additional authentication from user)
+"""
+enum TokenizedPaymentFlowEnum {
+ INTERACTIVE
+}
+
+scalar JSON
+
"""
Represents an problem in the checkout.
@@ -22928,8 +23004,6 @@ type PaymentGatewayConfig @doc(category: "Payments") {
errors: [PaymentGatewayConfigError!]
}
-scalar JSON
-
type PaymentGatewayConfigError @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.
@@ -32946,6 +33020,35 @@ type ShopMetadataUpdated implements Event {
shop: Shop
}
+"""
+List payment methods stored for the user by payment gateway.
+
+Added in Saleor 3.15.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+type ListStoredPaymentMethods implements Event @doc(category: "Payments") {
+ """Time of the event."""
+ issuedAt: DateTime
+
+ """Saleor version that triggered the event."""
+ version: String
+
+ """The user or application that triggered the event."""
+ issuingPrincipal: IssuingPrincipal
+
+ """The application receiving the webhook."""
+ recipient: App
+
+ """The user for which the app should return a list of payment methods."""
+ user: User!
+
+ """
+ Channel in context which was used to fetch the list of payment methods.
+ """
+ channel: Channel!
+}
+
"""_Any value scalar as defined by Federation spec."""
scalar _Any
diff --git a/saleor/graphql/shop/types.py b/saleor/graphql/shop/types.py
index e405e6d166..3f74bf5dc0 100644
--- a/saleor/graphql/shop/types.py
+++ b/saleor/graphql/shop/types.py
@@ -14,7 +14,6 @@ from ...permission.auth_filters import AuthorizationFilters
from ...permission.enums import SitePermissions, get_permissions
from ...site import models as site_models
from ..account.types import Address, AddressInput, StaffNotificationRecipient
-from ..checkout.types import PaymentGateway
from ..core import ResolveInfo
from ..core.descriptions import (
ADDED_IN_31,
@@ -43,6 +42,7 @@ from ..core.types import (
)
from ..core.utils import str_to_enum
from ..meta.types import ObjectWithMetadata
+from ..payment.types import PaymentGateway
from ..plugins.dataloaders import plugin_manager_promise_callback
from ..shipping.types import ShippingMethod
from ..site.dataloaders import get_site_promise, load_site_callback
diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.py
index 3206cdcc03..ba332d8429 100644
--- a/saleor/graphql/webhook/subscription_types.py
+++ b/saleor/graphql/webhook/subscription_types.py
@@ -13,7 +13,11 @@ from ...graphql.shop.types import Shop
from ...menu.models import MenuItemTranslation
from ...order.utils import get_all_shipping_methods_for_order
from ...page.models import PageTranslation
-from ...payment.interface import TransactionActionData, TransactionSessionData
+from ...payment.interface import (
+ ListStoredPaymentMethodsRequestData,
+ TransactionActionData,
+ TransactionSessionData,
+)
from ...product.models import (
CategoryTranslation,
CollectionTranslation,
@@ -1795,6 +1799,48 @@ class TransactionProcessSession(TransactionSessionBase):
doc_category = DOC_CATEGORY_PAYMENTS
+class ListStoredPaymentMethods(SubscriptionObjectType):
+ user = graphene.Field(
+ UserType,
+ description=(
+ "The user for which the app should return a list of payment methods."
+ ),
+ required=True,
+ )
+ channel = graphene.Field(
+ "saleor.graphql.channel.types.Channel",
+ description=(
+ "Channel in context which was used to fetch the list of payment methods."
+ ),
+ required=True,
+ )
+
+ class Meta:
+ root_type = None
+ enable_dry_run = False
+ interfaces = (Event,)
+ description = (
+ "List payment methods stored for the user by payment gateway."
+ + ADDED_IN_315
+ + PREVIEW_FEATURE
+ )
+ doc_category = DOC_CATEGORY_PAYMENTS
+
+ @classmethod
+ def resolve_user(
+ cls, root: tuple[str, ListStoredPaymentMethodsRequestData], _info: ResolveInfo
+ ):
+ _, payment_method_data = root
+ return payment_method_data.user
+
+ @classmethod
+ def resolve_channel(
+ cls, root: tuple[str, ListStoredPaymentMethodsRequestData], _info: ResolveInfo
+ ):
+ _, payment_method_data = root
+ return payment_method_data.channel
+
+
class TransactionItemMetadataUpdated(SubscriptionObjectType):
transaction = graphene.Field(
TransactionItem,
@@ -2334,4 +2380,5 @@ WEBHOOK_TYPES_MAP = {
WebhookEventSyncType.TRANSACTION_INITIALIZE_SESSION: TransactionInitializeSession,
WebhookEventSyncType.TRANSACTION_PROCESS_SESSION: TransactionProcessSession,
WebhookEventAsyncType.SHOP_METADATA_UPDATED: ShopMetadataUpdated,
+ WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS: ListStoredPaymentMethods,
}
diff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.py
index 9a5b311f28..84bdd1f740 100644
--- a/saleor/payment/__init__.py
+++ b/saleor/payment/__init__.py
@@ -233,3 +233,18 @@ class TransactionEventType:
(CANCEL_REQUEST, "Represents cancel request"),
(INFO, "Represents an info event"),
]
+
+
+class TokenizedPaymentFlow:
+ """Represents possible tokenized payment flows that can be used to process payment.
+
+ The following flows are possible:
+ INTERACTIVE - Payment method can be used for 1 click checkout - it's prefilled in
+ checkout form (might require additional authentication from user)
+ """
+
+ INTERACTIVE = "interactive"
+
+ CHOICES = [
+ (INTERACTIVE, "Interactive"),
+ ]
diff --git a/saleor/payment/interface.py b/saleor/payment/interface.py
index d63dcba5e7..b4bf2db0d7 100644
--- a/saleor/payment/interface.py
+++ b/saleor/payment/interface.py
@@ -10,7 +10,9 @@ from ..order.fetch import OrderLineInfo
from ..payment.models import TransactionEvent, TransactionItem
if TYPE_CHECKING:
+ from ..account.models import User
from ..app.models import App
+ from ..channel.models import Channel
from ..checkout.models import Checkout
from ..order.models import Order, OrderGrantedRefund
@@ -18,6 +20,60 @@ JSONValue = Union[str, int, float, bool, None, Dict[str, Any], List[Any]]
JSONType = Union[Dict[str, JSONValue], List[JSONValue]]
+@dataclass
+class PaymentGateway:
+ """Dataclass for storing information about a payment gateway."""
+
+ id: str
+ name: str
+ currencies: List[str]
+ config: List[Dict[str, Any]]
+
+
+@dataclass
+class ListStoredPaymentMethodsRequestData:
+ channel: "Channel"
+ user: "User"
+
+
+@dataclass
+class PaymentMethodCreditCardInfo:
+ brand: str
+ last_digits: str
+ exp_month: int
+ exp_year: int
+ first_digits: Optional[str] = None
+
+
+@dataclass
+class PaymentMethodData:
+ """Payment method data.
+
+ Represents a payment method stored for user (tokenized) in payment gateway, such
+ as credit card or SEPA direct debit
+
+ id - ID of stored payment method used to make payment actions
+ type - Type of the payment method
+ gateway - The app that owns the payment method
+ external_id - ID of the payment method in the payment gateway
+ supported_payment_flows - List of supported flows that can be performed with this
+ payment method
+ credit_card_info - Credit card information if the payment method is a credit card
+ name - Name of the payment method. Example: last 4 digits of credit card,
+ obfuscated email
+ data - JSON data returned by Payment Provider app for this payment method
+ """
+
+ id: str
+ type: str
+ external_id: str
+ gateway: PaymentGateway
+ supported_payment_flows: List[str] = field(default_factory=list)
+ credit_card_info: Optional[PaymentMethodCreditCardInfo] = None
+ name: Optional[str] = None
+ data: Optional[JSONType] = None
+
+
@dataclass
class TransactionActionData:
action_type: str
@@ -247,16 +303,6 @@ class CustomerSource:
metadata: Optional[Dict[str, str]] = None
-@dataclass
-class PaymentGateway:
- """Dataclass for storing information about a payment gateway."""
-
- id: str
- name: str
- currencies: List[str]
- config: List[Dict[str, Any]]
-
-
@dataclass
class InitializedPaymentResponse:
gateway: str
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index 0ca6e10008..5df1cbdec6 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -29,8 +29,10 @@ from ..payment.interface import (
CustomerSource,
GatewayResponse,
InitializedPaymentResponse,
+ ListStoredPaymentMethodsRequestData,
PaymentData,
PaymentGateway,
+ PaymentMethodData,
TransactionActionData,
TransactionSessionResult,
)
@@ -681,6 +683,11 @@ class BasePlugin:
list_payment_sources: Callable[[str, Any], List["CustomerSource"]]
+ list_stored_payment_methods: Callable[
+ ["ListStoredPaymentMethodsRequestData", list["PaymentMethodData"]],
+ list["PaymentMethodData"],
+ ]
+
# 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 6cb0cf47de..0eedc3de40 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -53,9 +53,11 @@ if TYPE_CHECKING:
CustomerSource,
GatewayResponse,
InitializedPaymentResponse,
+ ListStoredPaymentMethodsRequestData,
PaymentData,
PaymentGateway,
PaymentGatewayData,
+ PaymentMethodData,
TokenConfig,
TransactionActionData,
TransactionSessionData,
@@ -1526,6 +1528,16 @@ class PluginsManager(PaymentInterface):
)
raise Exception(f"Payment plugin {gateway} is inaccessible!")
+ def list_stored_payment_methods(
+ self, list_stored_payment_methods_data: "ListStoredPaymentMethodsRequestData"
+ ) -> list["PaymentMethodData"]:
+ default_value: list = []
+ return self.__run_method_on_plugins(
+ "list_stored_payment_methods",
+ default_value,
+ list_stored_payment_methods_data,
+ )
+
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 0e234c88a5..0023281a5f 100644
--- a/saleor/plugins/tests/sample_plugins.py
+++ b/saleor/plugins/tests/sample_plugins.py
@@ -334,18 +334,25 @@ class PluginSample(BasePlugin):
app_identifier="321", response=None, error="Some error"
)
- def checkout_fully_paid(self, checkout):
+ def checkout_fully_paid(self, checkout, previous_value):
return None
- def order_fully_refunded(self, order):
+ def order_fully_refunded(self, order, previous_value):
return None
- def order_paid(self, order):
+ def order_paid(self, order, previous_value):
return None
- def order_refunded(self, order):
+ def order_refunded(self, order, previous_value):
return None
+ def list_stored_payment_methods(
+ self,
+ list_payment_method_data,
+ previous_value,
+ ):
+ return []
+
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 8237df9f40..22bf4cdf0e 100644
--- a/saleor/plugins/tests/test_manager.py
+++ b/saleor/plugins/tests/test_manager.py
@@ -18,6 +18,7 @@ from ...discount.utils import (
)
from ...graphql.discount.mutations.utils import convert_catalogue_info_to_global_ids
from ...payment.interface import (
+ ListStoredPaymentMethodsRequestData,
PaymentGateway,
PaymentGatewayData,
TransactionProcessActionData,
@@ -1332,3 +1333,26 @@ def test_order_paid(mocked_sample_method, order):
# then
mocked_sample_method.assert_called_once_with(order, previous_value=None)
+
+
+@patch("saleor.plugins.tests.sample_plugins.PluginSample.list_stored_payment_methods")
+def test_list_stored_payment_methods(
+ mocked_list_stored_payment_methods, channel_USD, customer_user
+):
+ # given
+ data = ListStoredPaymentMethodsRequestData(
+ channel=channel_USD,
+ user=customer_user,
+ )
+
+ plugins = [
+ "saleor.plugins.tests.sample_plugins.PluginSample",
+ "saleor.plugins.tests.sample_plugins.PluginInactive",
+ ]
+ manager = PluginsManager(plugins=plugins)
+
+ # when
+ manager.list_stored_payment_methods(data)
+
+ # then
+ mocked_list_stored_payment_methods.assert_called_once()
diff --git a/saleor/plugins/webhook/const.py b/saleor/plugins/webhook/const.py
index 047e488379..001ce067d6 100644
--- a/saleor/plugins/webhook/const.py
+++ b/saleor/plugins/webhook/const.py
@@ -1,3 +1,4 @@
CACHE_EXCLUDED_SHIPPING_KEY = "webhook_exclude_shipping_id_"
CACHE_EXCLUDED_SHIPPING_TIME = 60 * 3
EXCLUDED_SHIPPING_REQUEST_TIMEOUT = 2
+WEBHOOK_CACHE_DEFAULT_TIMEOUT: int = 5 * 60 # 5 minutes
diff --git a/saleor/plugins/webhook/list_stored_payment_methods.py b/saleor/plugins/webhook/list_stored_payment_methods.py
new file mode 100644
index 0000000000..a3685d76df
--- /dev/null
+++ b/saleor/plugins/webhook/list_stored_payment_methods.py
@@ -0,0 +1,139 @@
+import logging
+from typing import Optional, cast
+
+from ...app.models import App
+from ...payment import TokenizedPaymentFlow
+from ...payment.interface import (
+ PaymentGateway,
+ PaymentMethodCreditCardInfo,
+ PaymentMethodData,
+)
+from .utils import to_payment_app_id
+
+logger = logging.getLogger(__name__)
+
+
+def get_credit_card_info(
+ app: App, credit_card_info: dict
+) -> Optional[PaymentMethodCreditCardInfo]:
+ required_fields = [
+ "brand",
+ "lastDigits",
+ "expYear",
+ "expMonth",
+ ]
+ brand = credit_card_info.get("brand")
+ last_digits = credit_card_info.get("lastDigits")
+ exp_year = credit_card_info.get("expYear")
+ exp_month = credit_card_info.get("expMonth")
+ first_digits = credit_card_info.get("firstDigits")
+ if not all(field in credit_card_info for field in required_fields):
+ logger.warning(
+ "Skipping stored payment method. Missing required fields for credit card "
+ "info. Required fields: %s, received fields: %s from app %s.",
+ required_fields,
+ credit_card_info.keys(),
+ app.id,
+ )
+ return None
+ if not all([brand, last_digits, exp_year, exp_month]):
+ logger.warning("Skipping stored credit card info without required fields")
+ return None
+ if not isinstance(exp_year, int):
+ if isinstance(exp_year, str) and exp_year.isdigit():
+ exp_year = int(exp_year)
+ else:
+ logger.warning(
+ "Skipping stored payment method with invalid expYear, "
+ "received from app %s",
+ app.id,
+ )
+ return None
+
+ if not isinstance(exp_month, int):
+ if isinstance(exp_month, str) and exp_month.isdigit():
+ exp_month = int(exp_month)
+ else:
+ logger.warning(
+ "Skipping stored payment method with invalid expMonth, "
+ "received from app %s",
+ app.id,
+ )
+ return None
+
+ return PaymentMethodCreditCardInfo(
+ brand=str(brand),
+ last_digits=str(last_digits),
+ exp_year=exp_year,
+ exp_month=exp_month,
+ first_digits=str(first_digits) if first_digits else None,
+ )
+
+
+def get_payment_method_from_response(
+ app: "App", payment_method: dict, currency: str
+) -> Optional[PaymentMethodData]:
+ payment_method_external_id = payment_method.get("id")
+ if not payment_method_external_id:
+ logger.warning(
+ "Skipping stored payment method without id, received from app %s", app.id
+ )
+ return None
+ payment_method_type = payment_method.get("type")
+ if not payment_method_type:
+ logger.warning(
+ "Skipping stored payment method without type, received from app %s",
+ app.id,
+ )
+ return None
+
+ supported_payment_flows = payment_method.get("supportedPaymentFlows")
+ if not supported_payment_flows or not isinstance(supported_payment_flows, list):
+ logger.warning(
+ "Skipping stored payment method with incorrect `supportedPaymentFlows`, "
+ "received from app %s",
+ app.id,
+ )
+ return None
+ payment_flow_choices = {
+ flow[0].upper(): flow[0] for flow in TokenizedPaymentFlow.CHOICES
+ }
+ if set(supported_payment_flows).difference(payment_flow_choices.keys()):
+ logger.warning(
+ "Skipping stored payment method with unsupported payment flows, "
+ "received from app %s",
+ app.id,
+ )
+ return None
+ app_identifier = cast(str, app.identifier)
+ credit_card_info = payment_method.get("creditCardInfo")
+ name = payment_method.get("name")
+ return PaymentMethodData(
+ id=to_payment_app_id(app, payment_method_external_id),
+ external_id=payment_method_external_id,
+ supported_payment_flows=[
+ payment_flow_choices[flow] for flow in supported_payment_flows
+ ],
+ type=payment_method_type,
+ credit_card_info=get_credit_card_info(app, credit_card_info)
+ if credit_card_info
+ else None,
+ name=name if name else None,
+ data=payment_method.get("data"),
+ gateway=PaymentGateway(
+ id=app_identifier, name=app.name, currencies=[currency], config=[]
+ ),
+ )
+
+
+def get_list_stored_payment_methods_from_response(
+ app: "App", response_data: dict, currency: str
+) -> list["PaymentMethodData"]:
+ payment_methods_response = response_data.get("paymentMethods", [])
+ payment_methods = []
+ for payment_method in payment_methods_response:
+ if parsed_payment_method := get_payment_method_from_response(
+ app, payment_method, currency
+ ):
+ payment_methods.append(parsed_payment_method)
+ return payment_methods
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 155fd294ee..a21e285c8a 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -4,7 +4,6 @@ from decimal import Decimal
from typing import TYPE_CHECKING, Any, DefaultDict, Final, List, Optional, Set, Union
import graphene
-from django.core.cache import cache
from ...app.models import App
from ...checkout.models import Checkout
@@ -18,14 +17,17 @@ from ...graphql.webhook.subscription_payload import initialize_request
from ...payment import PaymentError, TransactionKind
from ...payment.interface import (
GatewayResponse,
+ ListStoredPaymentMethodsRequestData,
PaymentData,
PaymentGateway,
PaymentGatewayData,
+ PaymentMethodData,
TransactionActionData,
TransactionSessionData,
TransactionSessionResult,
)
from ...payment.models import Payment, TransactionItem
+from ...settings import WEBHOOK_SYNC_TIMEOUT
from ...thumbnail.models import Thumbnail
from ...webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ...webhook.payloads import (
@@ -58,9 +60,10 @@ from ...webhook.payloads import (
)
from ...webhook.utils import get_webhooks_for_event
from ..base_plugin import BasePlugin, ExcludedShippingMethod
-from .const import CACHE_EXCLUDED_SHIPPING_KEY
+from .const import CACHE_EXCLUDED_SHIPPING_KEY, WEBHOOK_CACHE_DEFAULT_TIMEOUT
+from .list_stored_payment_methods import get_list_stored_payment_methods_from_response
from .shipping import (
- generate_cache_key_for_shipping_list_methods_for_checkout,
+ get_cache_data_for_shipping_list_methods_for_checkout,
get_excluded_shipping_data,
parse_list_shipping_methods_response,
)
@@ -69,6 +72,7 @@ from .tasks import (
trigger_all_webhooks_sync,
trigger_transaction_request,
trigger_webhook_sync,
+ trigger_webhook_sync_if_not_cached,
trigger_webhooks_async,
)
from .utils import (
@@ -1633,6 +1637,46 @@ class WebhookPlugin(BasePlugin):
delivery_update(delivery, status=EventDeliveryStatus.PENDING)
send_webhook_request_async.delay(delivery.pk)
+ def list_stored_payment_methods(
+ self,
+ list_payment_method_data: "ListStoredPaymentMethodsRequestData",
+ previous_value: list["PaymentMethodData"],
+ ) -> list["PaymentMethodData"]:
+ if not self.active:
+ return previous_value
+
+ event_type = WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS
+
+ if webhooks := get_webhooks_for_event(event_type):
+ payload_dict = {
+ "user_id": graphene.Node.to_global_id(
+ "User", list_payment_method_data.user.id
+ ),
+ "channel_slug": list_payment_method_data.channel.slug,
+ }
+ payload = self._serialize_payload(payload_dict)
+ for webhook in webhooks:
+ if not webhook.app.identifier:
+ continue
+ response_data = trigger_webhook_sync_if_not_cached(
+ event_type,
+ payload,
+ webhook,
+ cache_data=payload_dict,
+ subscribable_object=list_payment_method_data,
+ request_timeout=WEBHOOK_SYNC_TIMEOUT,
+ cache_timeout=WEBHOOK_CACHE_DEFAULT_TIMEOUT,
+ )
+ if response_data:
+ previous_value.extend(
+ get_list_stored_payment_methods_from_response(
+ webhook.app,
+ response_data,
+ list_payment_method_data.channel.currency_code,
+ )
+ )
+ return previous_value
+
def _request_transaction_action(
self,
transaction_data: "TransactionActionData",
@@ -2071,30 +2115,17 @@ class WebhookPlugin(BasePlugin):
webhooks = get_webhooks_for_event(event_type)
if webhooks:
payload = generate_checkout_payload(checkout, self.requestor)
+ cache_data = get_cache_data_for_shipping_list_methods_for_checkout(payload)
for webhook in webhooks:
- if not webhook:
- raise PaymentError(
- f"No payment webhook found for event: {event_type}."
- )
-
- cache_key = generate_cache_key_for_shipping_list_methods_for_checkout(
- payload, webhook.target_url
+ response_data = trigger_webhook_sync_if_not_cached(
+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ payload=payload,
+ webhook=webhook,
+ cache_data=cache_data,
+ subscribable_object=checkout,
+ request_timeout=WEBHOOK_SYNC_TIMEOUT,
+ cache_timeout=CACHE_TIME_SHIPPING_LIST_METHODS_FOR_CHECKOUT,
)
- response_data = cache.get(cache_key)
-
- if response_data is None:
- response_data = trigger_webhook_sync(
- event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
- payload=payload,
- webhook=webhook,
- subscribable_object=checkout,
- )
- if response_data is not None:
- cache.set(
- cache_key,
- response_data,
- CACHE_TIME_SHIPPING_LIST_METHODS_FOR_CHECKOUT,
- )
if response_data:
shipping_methods = parse_list_shipping_methods_response(
diff --git a/saleor/plugins/webhook/shipping.py b/saleor/plugins/webhook/shipping.py
index 380cf35324..e17f3e7ec5 100644
--- a/saleor/plugins/webhook/shipping.py
+++ b/saleor/plugins/webhook/shipping.py
@@ -1,5 +1,4 @@
import base64
-import hashlib
import json
import logging
from collections import defaultdict
@@ -206,16 +205,10 @@ def parse_excluded_shipping_methods(
return excluded_methods_map
-def generate_cache_key_for_shipping_list_methods_for_checkout(
- payload: str, target_url: str
-) -> str:
+def get_cache_data_for_shipping_list_methods_for_checkout(payload: str) -> dict:
key_data = json.loads(payload)
# drop fields that change between requests but are not relevant for cache key
key_data[0].pop("last_change")
key_data[0]["meta"].pop("issued_at")
-
- # make cache key
- key = json.dumps(key_data)
- key = f"{target_url}-{hashlib.sha256(key.encode('utf-8')).hexdigest()}"
- return key
+ return key_data
diff --git a/saleor/plugins/webhook/tasks.py b/saleor/plugins/webhook/tasks.py
index 5eda08cb94..a573fa3c84 100644
--- a/saleor/plugins/webhook/tasks.py
+++ b/saleor/plugins/webhook/tasks.py
@@ -13,6 +13,7 @@ from celery import group
from celery.exceptions import MaxRetriesExceededError, Retry
from celery.utils.log import get_task_logger
from django.conf import settings
+from django.core.cache import cache
from django.urls import reverse
from google.cloud import pubsub_v1
from requests.exceptions import RequestException
@@ -43,6 +44,7 @@ from ...webhook.observability import WebhookData
from ...webhook.payloads import generate_transaction_action_request_payload
from ...webhook.utils import get_webhooks_for_event
from . import signature_for_payload
+from .const import WEBHOOK_CACHE_DEFAULT_TIMEOUT
from .utils import (
attempt_update,
catch_duration_time,
@@ -50,6 +52,7 @@ from .utils import (
create_attempt,
create_event_delivery_list_for_webhooks,
delivery_update,
+ generate_cache_key_for_webhook,
get_delivery_for_webhook,
)
@@ -224,6 +227,44 @@ def group_webhooks_by_subscription(webhooks):
return regular, subscription
+def trigger_webhook_sync_if_not_cached(
+ event_type: str,
+ payload: str,
+ webhook: "Webhook",
+ cache_data: dict,
+ subscribable_object=None,
+ request_timeout=None,
+ cache_timeout=None,
+ request=None,
+) -> Optional[dict]:
+ """Get response for synchronous webhook.
+
+ - Send a synchronous webhook request if cache is expired.
+ - Fetch response from cache if it is still valid.
+ """
+
+ cache_key = generate_cache_key_for_webhook(
+ cache_data, webhook.target_url, event_type, webhook.app_id
+ )
+ response_data = cache.get(cache_key)
+ if response_data is None:
+ response_data = trigger_webhook_sync(
+ event_type,
+ payload,
+ webhook,
+ subscribable_object=subscribable_object,
+ timeout=request_timeout,
+ request=request,
+ )
+ if response_data is not None:
+ cache.set(
+ cache_key,
+ response_data,
+ timeout=cache_timeout or WEBHOOK_CACHE_DEFAULT_TIMEOUT,
+ )
+ return response_data
+
+
def trigger_webhook_sync(
event_type: str,
payload: str,
@@ -233,9 +274,6 @@ def trigger_webhook_sync(
request=None,
) -> Optional[Dict[Any, Any]]:
"""Send a synchronous webhook request."""
- if not webhook:
- raise PaymentError(f"No payment webhook found for event: {event_type}.")
-
if webhook.subscription_query:
delivery = create_delivery_for_subscription_sync_event(
event_type=event_type,
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_list_payment_methods.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_list_payment_methods.py
new file mode 100644
index 0000000000..1a8da41671
--- /dev/null
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_list_payment_methods.py
@@ -0,0 +1,52 @@
+import json
+
+import graphene
+
+from .....payment.interface import ListStoredPaymentMethodsRequestData
+from .....webhook.event_types import WebhookEventSyncType
+from ...tasks import create_deliveries_for_subscriptions
+
+LIST_STORED_PAYMENT_METHODS = """
+subscription {
+ event {
+ ... on ListStoredPaymentMethods{
+ user{
+ id
+ }
+ channel{
+ id
+ }
+ }
+ }
+}
+"""
+
+
+def test_list_stored_payment_methods(
+ list_stored_payment_methods_app,
+ webhook_list_stored_payment_methods_response,
+ channel_USD,
+ customer_user,
+):
+ # given
+ webhook = list_stored_payment_methods_app.webhooks.first()
+ webhook.subscription_query = LIST_STORED_PAYMENT_METHODS
+ webhook.save()
+
+ data = ListStoredPaymentMethodsRequestData(
+ channel=channel_USD,
+ user=customer_user,
+ )
+
+ event_type = WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS
+
+ # when
+ delivery = create_deliveries_for_subscriptions(event_type, data, [webhook])[0]
+
+ # then
+ assert delivery.payload
+ assert delivery.payload.payload
+ assert json.loads(delivery.payload.payload) == {
+ "channel": {"id": graphene.Node.to_global_id("Channel", channel_USD.pk)},
+ "user": {"id": graphene.Node.to_global_id("User", customer_user.pk)},
+ }
diff --git a/saleor/plugins/webhook/tests/test_list_shipping_methods_for_checkout.py b/saleor/plugins/webhook/tests/test_list_shipping_methods_for_checkout.py
index 8825a13d4f..79660ed56a 100644
--- a/saleor/plugins/webhook/tests/test_list_shipping_methods_for_checkout.py
+++ b/saleor/plugins/webhook/tests/test_list_shipping_methods_for_checkout.py
@@ -1,15 +1,17 @@
-import json
from datetime import timedelta
from decimal import Decimal
from unittest import mock
from django.utils import timezone
+from ....webhook.event_types import WebhookEventSyncType
from ....webhook.payloads import generate_checkout_payload
-from ..shipping import generate_cache_key_for_shipping_list_methods_for_checkout
+from ..plugin import CACHE_TIME_SHIPPING_LIST_METHODS_FOR_CHECKOUT
+from ..shipping import get_cache_data_for_shipping_list_methods_for_checkout
+from ..utils import generate_cache_key_for_webhook
[email protected]("saleor.plugins.webhook.plugin.cache.set")
[email protected]("saleor.plugins.webhook.tasks.cache.set")
@mock.patch("saleor.plugins.webhook.tasks.send_webhook_request_sync")
def test_get_shipping_methods_for_checkout_set_cache(
mocked_webhook,
@@ -37,7 +39,7 @@ def test_get_shipping_methods_for_checkout_set_cache(
assert mocked_cache_set.called
[email protected]("saleor.plugins.webhook.plugin.cache.set")
[email protected]("saleor.plugins.webhook.tasks.cache.set")
@mock.patch("saleor.plugins.webhook.tasks.send_webhook_request_sync")
def test_get_shipping_methods_no_webhook_response_does_not_set_cache(
mocked_webhook,
@@ -58,7 +60,7 @@ def test_get_shipping_methods_no_webhook_response_does_not_set_cache(
assert not mocked_cache_set.called
[email protected]("saleor.plugins.webhook.plugin.cache.get")
[email protected]("saleor.plugins.webhook.tasks.cache.get")
@mock.patch("saleor.plugins.webhook.tasks.send_webhook_request_sync")
def test_get_shipping_methods_for_checkout_use_cache(
mocked_webhook,
@@ -86,7 +88,7 @@ def test_get_shipping_methods_for_checkout_use_cache(
assert mocked_cache_get.called
[email protected]("saleor.plugins.webhook.plugin.cache.get")
[email protected]("saleor.plugins.webhook.tasks.cache.get")
@mock.patch("saleor.plugins.webhook.tasks.send_webhook_request_sync")
def test_get_shipping_methods_for_checkout_use_cache_for_empty_list(
mocked_webhook,
@@ -107,67 +109,115 @@ def test_get_shipping_methods_for_checkout_use_cache_for_empty_list(
assert mocked_cache_get.called
-def test_checkout_change_invalidates_cache_key(checkout_with_item, shipping_app):
[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_checkout_change_invalidates_cache_key(
+ mocked_webhook,
+ mocked_cache_get,
+ mocked_cache_set,
+ webhook_plugin,
+ checkout_with_item,
+ shipping_app,
+):
# given
+ mocked_webhook_response = [
+ {
+ "id": "method-1",
+ "name": "Standard Shipping",
+ "amount": Decimal("5.5"),
+ "currency": "GBP",
+ }
+ ]
+ mocked_webhook.return_value = mocked_webhook_response
+ mocked_cache_get.return_value = None
+
payload = generate_checkout_payload(checkout_with_item)
+ key_data = get_cache_data_for_shipping_list_methods_for_checkout(payload)
target_url = shipping_app.webhooks.first().target_url
- cache_key = generate_cache_key_for_shipping_list_methods_for_checkout(
- payload, target_url
+ cache_key = generate_cache_key_for_webhook(
+ key_data,
+ target_url,
+ WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ shipping_app.id,
)
+ plugin = webhook_plugin()
# when
checkout_with_item.email = "[email protected]"
checkout_with_item.save(update_fields=["email"])
new_payload = generate_checkout_payload(checkout_with_item)
- new_cache_key = generate_cache_key_for_shipping_list_methods_for_checkout(
- new_payload, target_url
+ new_key_data = get_cache_data_for_shipping_list_methods_for_checkout(new_payload)
+ new_cache_key = generate_cache_key_for_webhook(
+ new_key_data,
+ target_url,
+ WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ shipping_app.id,
)
+ plugin.get_shipping_methods_for_checkout(checkout_with_item, None)
# then
assert cache_key != new_cache_key
+ mocked_cache_get.assert_called_once_with(new_cache_key)
+ mocked_cache_set.assert_called_once_with(
+ new_cache_key,
+ mocked_webhook_response,
+ timeout=CACHE_TIME_SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ )
[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_ignore_selected_fields_on_generating_cache_key(
- checkout_with_item, shipping_app
+ mocked_webhook,
+ mocked_cache_get,
+ mocked_cache_set,
+ webhook_plugin,
+ checkout_with_item,
+ shipping_app,
):
# given
- target_url = shipping_app.webhooks.first().target_url
+ mocked_webhook_response = [
+ {
+ "id": "method-1",
+ "name": "Standard Shipping",
+ "amount": Decimal("5.5"),
+ "currency": "GBP",
+ }
+ ]
+ mocked_webhook.return_value = mocked_webhook_response
+ mocked_cache_get.return_value = None
payload = generate_checkout_payload(checkout_with_item)
- cache_key = generate_cache_key_for_shipping_list_methods_for_checkout(
- payload, target_url
+ key_data = get_cache_data_for_shipping_list_methods_for_checkout(payload)
+ target_url = shipping_app.webhooks.first().target_url
+ cache_key = generate_cache_key_for_webhook(
+ key_data,
+ target_url,
+ WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ shipping_app.id,
)
+ plugin = webhook_plugin()
# when
checkout_with_item.last_change = timezone.now() + timedelta(seconds=30)
checkout_with_item.save(update_fields=["last_change"])
-
new_payload = generate_checkout_payload(checkout_with_item)
- new_payload_data = json.loads(new_payload)
- new_payload_data[0]["meta"]["issued_at"] = timezone.now().isoformat()
- new_payload = json.dumps(new_payload_data)
- new_cache_key = generate_cache_key_for_shipping_list_methods_for_checkout(
- new_payload, target_url
+ new_key_data = get_cache_data_for_shipping_list_methods_for_checkout(new_payload)
+ new_cache_key = generate_cache_key_for_webhook(
+ new_key_data,
+ target_url,
+ WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ shipping_app.id,
)
+ plugin.get_shipping_methods_for_checkout(checkout_with_item, None)
# then
assert cache_key == new_cache_key
-
-
-def test_different_target_urls_produce_different_cache_key(checkout_with_item):
- # given
- target_url_1 = "http://example.com/1"
- target_url_2 = "http://example.com/2"
-
- payload = generate_checkout_payload(checkout_with_item)
-
- # when
- cache_key_1 = generate_cache_key_for_shipping_list_methods_for_checkout(
- payload, target_url_1
+ mocked_cache_get.assert_called_once_with(new_cache_key)
+ mocked_cache_set.assert_called_once_with(
+ new_cache_key,
+ mocked_webhook_response,
+ timeout=CACHE_TIME_SHIPPING_LIST_METHODS_FOR_CHECKOUT,
)
- cache_key_2 = generate_cache_key_for_shipping_list_methods_for_checkout(
- payload, target_url_2
- )
-
- # then
- assert cache_key_1 != cache_key_2
diff --git a/saleor/plugins/webhook/tests/test_list_stored_payment_methods_webhook.py b/saleor/plugins/webhook/tests/test_list_stored_payment_methods_webhook.py
new file mode 100644
index 0000000000..0874f955e1
--- /dev/null
+++ b/saleor/plugins/webhook/tests/test_list_stored_payment_methods_webhook.py
@@ -0,0 +1,247 @@
+import graphene
+import mock
+
+from ....core.models import EventDelivery
+from ....payment.interface import ListStoredPaymentMethodsRequestData
+from ....settings import WEBHOOK_SYNC_TIMEOUT
+from ....webhook.event_types import WebhookEventSyncType
+from ..const import WEBHOOK_CACHE_DEFAULT_TIMEOUT
+from ..list_stored_payment_methods import get_list_stored_payment_methods_from_response
+from ..utils import generate_cache_key_for_webhook
+
+LIST_STORED_PAYMENT_METHODS = """
+subscription {
+ event {
+ ... on ListStoredPaymentMethods{
+ user{
+ id
+ }
+ channel{
+ id
+ }
+ }
+ }
+}
+"""
+
+
[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_list_stored_payment_methods_with_static_payload(
+ mock_request,
+ mocked_cache_get,
+ mocked_cache_set,
+ channel_USD,
+ customer_user,
+ webhook_plugin,
+ list_stored_payment_methods_app,
+ webhook_list_stored_payment_methods_response,
+):
+ # given
+ mock_request.return_value = webhook_list_stored_payment_methods_response
+ mocked_cache_get.return_value = None
+ webhook = list_stored_payment_methods_app.webhooks.first()
+
+ plugin = webhook_plugin()
+
+ 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,
+ list_stored_payment_methods_app.id,
+ )
+
+ # when
+ response = plugin.list_stored_payment_methods(data, [])
+
+ # then
+ delivery = EventDelivery.objects.get()
+ mock_request.assert_called_once_with(delivery, timeout=WEBHOOK_SYNC_TIMEOUT)
+
+ mocked_cache_get.assert_called_once_with(expected_cache_key)
+ mocked_cache_set.assert_called_once_with(
+ expected_cache_key,
+ webhook_list_stored_payment_methods_response,
+ timeout=WEBHOOK_CACHE_DEFAULT_TIMEOUT,
+ )
+
+ assert response
+ assert response == get_list_stored_payment_methods_from_response(
+ list_stored_payment_methods_app,
+ webhook_list_stored_payment_methods_response,
+ channel_USD.currency_code,
+ )
+
+
[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_list_stored_payment_methods_with_subscription_payload(
+ mock_request,
+ mocked_cache_get,
+ mocked_cache_set,
+ channel_USD,
+ customer_user,
+ webhook_plugin,
+ list_stored_payment_methods_app,
+ webhook_list_stored_payment_methods_response,
+):
+ # given
+ mock_request.return_value = webhook_list_stored_payment_methods_response
+ mocked_cache_get.return_value = None
+
+ webhook = list_stored_payment_methods_app.webhooks.first()
+ webhook.subscription_query = LIST_STORED_PAYMENT_METHODS
+ webhook.save()
+
+ plugin = webhook_plugin()
+
+ 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,
+ list_stored_payment_methods_app.id,
+ )
+
+ # when
+ response = plugin.list_stored_payment_methods(data, [])
+
+ # then
+ delivery = EventDelivery.objects.get()
+ mock_request.assert_called_once_with(delivery, timeout=WEBHOOK_SYNC_TIMEOUT)
+
+ mocked_cache_get.assert_called_once_with(expected_cache_key)
+ mocked_cache_set.assert_called_once_with(
+ expected_cache_key,
+ webhook_list_stored_payment_methods_response,
+ timeout=WEBHOOK_CACHE_DEFAULT_TIMEOUT,
+ )
+
+ assert response
+ assert response == get_list_stored_payment_methods_from_response(
+ list_stored_payment_methods_app,
+ webhook_list_stored_payment_methods_response,
+ channel_USD.currency_code,
+ )
+
+
[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_list_stored_payment_methods_uses_cache_if_available(
+ mock_request,
+ mocked_cache_get,
+ mocked_cache_set,
+ channel_USD,
+ customer_user,
+ webhook_plugin,
+ list_stored_payment_methods_app,
+ webhook_list_stored_payment_methods_response,
+):
+ # given
+ mock_request.return_value = webhook_list_stored_payment_methods_response
+ mocked_cache_get.return_value = webhook_list_stored_payment_methods_response
+
+ webhook = list_stored_payment_methods_app.webhooks.first()
+ webhook.subscription_query = LIST_STORED_PAYMENT_METHODS
+ webhook.save()
+
+ plugin = webhook_plugin()
+
+ 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,
+ list_stored_payment_methods_app.id,
+ )
+
+ # when
+ response = plugin.list_stored_payment_methods(data, [])
+
+ # then
+ mocked_cache_get.assert_called_once_with(expected_cache_key)
+ assert not mock_request.called
+ assert not mocked_cache_set.called
+
+ assert response
+ assert response == get_list_stored_payment_methods_from_response(
+ list_stored_payment_methods_app,
+ webhook_list_stored_payment_methods_response,
+ channel_USD.currency_code,
+ )
+
+
[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_list_stored_payment_methods_app_returns_incorrect_response(
+ mock_request,
+ mocked_cache_get,
+ mocked_cache_set,
+ channel_USD,
+ customer_user,
+ webhook_plugin,
+ list_stored_payment_methods_app,
+ webhook_list_stored_payment_methods_response,
+):
+ # given
+ mock_request.return_value = None
+ mocked_cache_get.return_value = None
+
+ webhook = list_stored_payment_methods_app.webhooks.first()
+ webhook.subscription_query = LIST_STORED_PAYMENT_METHODS
+ webhook.save()
+
+ plugin = webhook_plugin()
+ 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,
+ list_stored_payment_methods_app.id,
+ )
+
+ # when
+ response = plugin.list_stored_payment_methods(data, [])
+
+ # then
+ delivery = EventDelivery.objects.get()
+ mock_request.assert_called_once_with(delivery, timeout=WEBHOOK_SYNC_TIMEOUT)
+
+ mocked_cache_get.assert_called_once_with(expected_cache_key)
+ assert not mocked_cache_set.called
+
+ assert response == []
diff --git a/saleor/plugins/webhook/tests/test_utils.py b/saleor/plugins/webhook/tests/test_utils.py
new file mode 100644
index 0000000000..a7227b932f
--- /dev/null
+++ b/saleor/plugins/webhook/tests/test_utils.py
@@ -0,0 +1,400 @@
+import copy
+
+import pytest
+
+from ....payment.interface import PaymentGateway
+from ....webhook.event_types import WebhookEventSyncType
+from ..list_stored_payment_methods import (
+ get_credit_card_info,
+ get_list_stored_payment_methods_from_response,
+ get_payment_method_from_response,
+)
+from ..utils import generate_cache_key_for_webhook, to_payment_app_id
+
+
+def payment_method_response():
+ return {
+ "id": "method-1",
+ "supportedPaymentFlows": ["INTERACTIVE"],
+ "type": "Credit Card",
+ "creditCardInfo": {
+ "brand": "visa",
+ "lastDigits": "1234",
+ "expMonth": 1,
+ "expYear": 2023,
+ "firstDigits": "123456",
+ },
+ "name": "***1234",
+ "data": {"some": "data"},
+ }
+
+
+def test_different_target_urls_produce_different_cache_key(checkout_with_item):
+ # given
+ target_url_1 = "http://example.com/1"
+ target_url_2 = "http://example.com/2"
+
+ payload = {"field": "1", "field2": "2"}
+
+ # when
+ cache_key_1 = generate_cache_key_for_webhook(
+ payload,
+ target_url_1,
+ WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ 1,
+ )
+ cache_key_2 = generate_cache_key_for_webhook(
+ payload,
+ target_url_2,
+ WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ 1,
+ )
+
+ # then
+ assert cache_key_1 != cache_key_2
+
+
+def test_different_payload_produce_different_cache_key(checkout_with_item):
+ # given
+ target_url = "http://example.com/1"
+
+ payload_1 = {"field": "1", "field2": "2"}
+ payload_2 = {"field": "1", "field2": "3"}
+
+ # when
+ cache_key_1 = generate_cache_key_for_webhook(
+ payload_1,
+ target_url,
+ WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ 1,
+ )
+ cache_key_2 = generate_cache_key_for_webhook(
+ payload_2,
+ target_url,
+ WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ 1,
+ )
+
+ # then
+ assert cache_key_1 != cache_key_2
+
+
+def test_different_event_produce_different_cache_key(checkout_with_item):
+ # given
+ target_url = "http://example.com/1"
+
+ payload = {"field": "1", "field2": "2"}
+
+ # when
+ cache_key_1 = generate_cache_key_for_webhook(
+ payload, target_url, WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT, 1
+ )
+ cache_key_2 = generate_cache_key_for_webhook(
+ payload, target_url, WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS, 1
+ )
+
+ # then
+ assert cache_key_1 != cache_key_2
+
+
+def test_different_app_produce_different_cache_key():
+ # given
+ target_url = "http://example.com/1"
+ first_app_id = 1
+ second_app_id = 2
+ payload = {"field": "1", "field2": "2"}
+
+ # when
+ cache_key_1 = generate_cache_key_for_webhook(
+ payload,
+ target_url,
+ WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ first_app_id,
+ )
+ cache_key_2 = generate_cache_key_for_webhook(
+ payload,
+ target_url,
+ WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ second_app_id,
+ )
+
+ # then
+ assert cache_key_1 != cache_key_2
+
+
+def test_get_credit_card_info(app):
+ # given
+ brand = "VISA"
+ last_digits = "1234"
+ exp_year = "2023"
+ exp_month = 1
+ first_digits = "4321"
+
+ credit_card_info = {
+ "brand": brand,
+ "lastDigits": last_digits,
+ "expYear": exp_year,
+ "expMonth": exp_month,
+ "firstDigits": first_digits,
+ }
+
+ # when
+ response = get_credit_card_info(app, credit_card_info)
+
+ # then
+ assert response.brand == brand
+ assert response.last_digits == last_digits
+ assert response.exp_year == int(exp_year)
+ assert response.exp_month == exp_month
+ assert response.first_digits == first_digits
+
+
+def test_get_credit_card_info_without_first_digits_field(app):
+ # given
+ brand = "VISA"
+ last_digits = "1234"
+ exp_year = 2023
+ exp_month = 1
+
+ credit_card_info = {
+ "brand": brand,
+ "lastDigits": last_digits,
+ "expYear": exp_year,
+ "expMonth": exp_month,
+ }
+
+ # when
+ response = get_credit_card_info(app, credit_card_info)
+
+ # then
+ assert response.brand == brand
+ assert response.last_digits == last_digits
+ assert response.exp_year == exp_year
+ assert response.exp_month == exp_month
+ assert response.first_digits is None
+
+
+ "field",
+ [
+ "brand",
+ "lastDigits",
+ "expYear",
+ "expMonth",
+ ],
+)
+def test_get_credit_card_info_missing_required_field(field, app):
+ # given
+ brand = "VISA"
+ last_digits = "1234"
+ exp_year = 2023
+ exp_month = 1
+ first_digits = "4321"
+
+ credit_card_info = {
+ "brand": brand,
+ "lastDigits": last_digits,
+ "expYear": exp_year,
+ "expMonth": exp_month,
+ "firstDigits": first_digits,
+ }
+ del credit_card_info[field]
+
+ # when
+ response = get_credit_card_info(app, credit_card_info)
+
+ # then
+ assert response is None
+
+
+ "field",
+ [
+ "brand",
+ "lastDigits",
+ "expYear",
+ "expMonth",
+ ],
+)
+def test_get_credit_card_info_required_field_is_none(field, app):
+ # given
+ brand = "VISA"
+ last_digits = "1234"
+ exp_year = 2023
+ exp_month = 1
+ first_digits = "4321"
+
+ credit_card_info = {
+ "brand": brand,
+ "lastDigits": last_digits,
+ "expYear": exp_year,
+ "expMonth": exp_month,
+ "firstDigits": first_digits,
+ }
+ credit_card_info[field] = None
+
+ # when
+ response = get_credit_card_info(app, credit_card_info)
+
+ # then
+ assert response is None
+
+
[email protected]("exp_year", [None, "", "str"])
+def test_get_credit_card_info_incorrect_exp_year(exp_year, app):
+ # given
+ brand = "VISA"
+ last_digits = "1234"
+ exp_month = 1
+ first_digits = "4321"
+
+ credit_card_info = {
+ "brand": brand,
+ "lastDigits": last_digits,
+ "expYear": exp_year,
+ "expMonth": exp_month,
+ "firstDigits": first_digits,
+ }
+
+ # when
+ response = get_credit_card_info(app, credit_card_info)
+
+ # then
+ assert response is None
+
+
[email protected]("exp_month", [None, "", "str"])
+def test_get_credit_card_info_incorrect_exp_month(exp_month, app):
+ # given
+ brand = "VISA"
+ last_digits = "1234"
+ exp_year = 2023
+ first_digits = "4321"
+
+ credit_card_info = {
+ "brand": brand,
+ "lastDigits": last_digits,
+ "expYear": exp_year,
+ "expMonth": exp_month,
+ "firstDigits": first_digits,
+ }
+
+ # when
+ response = get_credit_card_info(app, credit_card_info)
+
+ # then
+ assert response is None
+
+
+def test_get_payment_method_from_response(payment_method_response, app):
+ # when
+ payment_method = get_payment_method_from_response(
+ app, payment_method_response, "usd"
+ )
+
+ # then
+ assert payment_method.id == to_payment_app_id(app, payment_method_response["id"])
+ assert payment_method.external_id == payment_method_response["id"]
+ assert payment_method.type == payment_method_response["type"]
+ assert payment_method.gateway == PaymentGateway(
+ id=app.identifier, name=app.name, currencies=["usd"], config=[]
+ )
+ assert payment_method.supported_payment_flows == [
+ flow.lower() for flow in payment_method_response["supportedPaymentFlows"]
+ ]
+ assert payment_method.credit_card_info == get_credit_card_info(
+ app, payment_method_response["creditCardInfo"]
+ )
+ assert payment_method.name == payment_method_response["name"]
+ assert payment_method.data == payment_method_response["data"]
+
+
[email protected]("field", ["id", "type", "supportedPaymentFlows"])
+def test_get_payment_method_from_response_missing_required_field(
+ field, payment_method_response, app
+):
+ # given
+ del payment_method_response[field]
+
+ # when
+ payment_method = get_payment_method_from_response(
+ app, payment_method_response, "usd"
+ )
+
+ # then
+ assert payment_method is None
+
+
[email protected]("field", ["creditCardInfo", "name", "data"])
+def test_get_payment_method_from_response_optional_field(
+ field, payment_method_response, app
+):
+ del payment_method_response[field]
+
+ # when
+ payment_method = get_payment_method_from_response(
+ app, payment_method_response, "usd"
+ )
+
+ # then
+ assert payment_method.id == to_payment_app_id(app, payment_method_response["id"])
+ assert payment_method.external_id == payment_method_response["id"]
+ assert payment_method.type == payment_method_response["type"]
+ assert payment_method.gateway == PaymentGateway(
+ id=app.identifier, name=app.name, currencies=["usd"], config=[]
+ )
+ assert payment_method.supported_payment_flows == [
+ flow.lower() for flow in payment_method_response["supportedPaymentFlows"]
+ ]
+
+
[email protected]("field", ["id", "type", "supportedPaymentFlows"])
+def test_get_payment_method_from_response_required_field_is_none(
+ field, payment_method_response, app
+):
+ # given
+ payment_method_response[field] = None
+
+ # when
+ payment_method = get_payment_method_from_response(
+ app, payment_method_response, "usd"
+ )
+
+ # then
+ assert payment_method is None
+
+
+def test_get_payment_method_from_response_incorrect_payment_flow_choices(
+ payment_method_response, app
+):
+ # given
+ payment_method_response["supportedPaymentFlows"] = ["incorrect", "INTERACTIVE"]
+
+ # when
+ payment_method = get_payment_method_from_response(
+ app, payment_method_response, "usd"
+ )
+
+ # then
+ assert payment_method is None
+
+
+def test_get_list_stored_payment_methods_from_response(payment_method_response, app):
+ # given
+ second_payment_method = copy.deepcopy(payment_method_response)
+ del second_payment_method["id"]
+ list_stored_payment_methods_response = {
+ "paymentMethods": [payment_method_response, second_payment_method]
+ }
+
+ # when
+ response = get_list_stored_payment_methods_from_response(
+ app, list_stored_payment_methods_response, "usd"
+ )
+
+ # then
+ assert len(response) == 1
+ assert response == [
+ get_payment_method_from_response(app, payment_method_response, "usd")
+ ]
diff --git a/saleor/plugins/webhook/utils.py b/saleor/plugins/webhook/utils.py
index ff0b5e00f5..ff19c51b7a 100644
--- a/saleor/plugins/webhook/utils.py
+++ b/saleor/plugins/webhook/utils.py
@@ -1,4 +1,5 @@
import decimal
+import hashlib
import json
import logging
from contextlib import contextmanager
@@ -34,9 +35,9 @@ class PaymentAppData:
name: str
-def to_payment_app_id(app: "App", gateway_id: str) -> "str":
+def to_payment_app_id(app: "App", external_id: str) -> "str":
app_identifier = app.identifier or app.id
- return f"{APP_ID_PREFIX}:{app_identifier}:{gateway_id}"
+ return f"{APP_ID_PREFIX}:{app_identifier}:{external_id}"
def from_payment_app_id(app_gateway_id: str) -> Optional["PaymentAppData"]:
@@ -289,3 +290,20 @@ def get_meta_code_key(app: App) -> str:
def get_meta_description_key(app: App) -> str:
return f"{app.identifier}.description"
+
+
+def generate_cache_key_for_webhook(
+ key_data: dict, webhook_url: str, event: str, app_id: int
+) -> str:
+ """Generate cache key for webhook.
+
+ Cache key takes into account the webhook url, event type, and app id.
+ The response from webhook_url can be different for different events.
+ Apps can have assigned different permissions, so the response can vary for
+ different apps.
+ """
+ key = json.dumps(key_data)
+ return (
+ f"{app_id}-{webhook_url}-{event}-"
+ f"{hashlib.sha256(key.encode('utf-8')).hexdigest()}"
+ )
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 8e529f7347..9209c1808b 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -6481,6 +6481,27 @@ def shipping_app(db, permission_manage_shipping):
return app
+def list_stored_payment_methods_app(db, permission_manage_payments):
+ app = App.objects.create(
+ name="List payment methods app",
+ is_active=True,
+ identifier="saleor.payment.app.list.stored.method",
+ )
+ app.tokens.create(name="Default")
+ app.permissions.add(permission_manage_payments)
+
+ webhook = Webhook.objects.create(
+ name="list_stored_payment_methods",
+ app=app,
+ target_url="http://localhost:8000/endpoint/",
+ )
+ webhook.events.create(
+ event_type=WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS,
+ )
+ return app
+
+
@pytest.fixture
def tax_app(db, permission_handle_taxes):
app = App.objects.create(name="Tax App", is_active=True)
@@ -7226,6 +7247,28 @@ def event_attempt(event_delivery):
)
+def webhook_list_stored_payment_methods_response():
+ return {
+ "paymentMethods": [
+ {
+ "id": "method-1",
+ "supportedPaymentFlows": ["INTERACTIVE"],
+ "type": "Credit Card",
+ "creditCardInfo": {
+ "brand": "visa",
+ "lastDigits": "1234",
+ "expMonth": 1,
+ "expYear": 2023,
+ "firstDigits": "123456",
+ },
+ "name": "***1234",
+ "data": {"some": "data"},
+ }
+ ]
+ }
+
+
@pytest.fixture
def webhook_response():
return WebhookResponse(
diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.py
index 2ce3f6ae38..f8073d39ab 100644
--- a/saleor/webhook/event_types.py
+++ b/saleor/webhook/event_types.py
@@ -732,6 +732,8 @@ class WebhookEventSyncType:
TRANSACTION_INITIALIZE_SESSION = "transaction_initialize_session"
TRANSACTION_PROCESS_SESSION = "transaction_process_session"
+ LIST_STORED_PAYMENT_METHODS = "list_stored_payment_methods"
+
EVENT_MAP: dict[str, dict[str, Any]] = {
PAYMENT_LIST_GATEWAYS: {
"name": "List payment gateways",
@@ -805,6 +807,10 @@ class WebhookEventSyncType:
"name": "Process transaction session",
"permission": PaymentPermissions.HANDLE_PAYMENTS,
},
+ LIST_STORED_PAYMENT_METHODS: {
+ "name": "List tokenized payment methods that can be used by the customer.",
+ "permission": PaymentPermissions.HANDLE_PAYMENTS,
+ },
}
CHOICES = [