Skip to content

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

Add pre-generated payload for PAYMENT_GATEWAY_INITIALIZE_SESSION (#17173)

Marcin Gębalafd17e46ad0fb
diff --git a/saleor/app/tests/fixtures/webhooks/payment_app.py b/saleor/app/tests/fixtures/webhooks/payment_app.py
index 18f4a97e97..b8092567e4 100644
--- a/saleor/app/tests/fixtures/webhooks/payment_app.py
+++ b/saleor/app/tests/fixtures/webhooks/payment_app.py
@@ -154,3 +154,24 @@ def payment_method_process_tokenization_app(db, permission_manage_payments):
event_type=WebhookEventSyncType.PAYMENT_METHOD_PROCESS_TOKENIZATION_SESSION,
)
return app
+
+
+def payment_gateway_initialize_session_app(db, permission_manage_payments):
+ app = App.objects.create(
+ name="Payment gateway initialize session",
+ is_active=True,
+ identifier="saleor.payment.app.payment.gateway.initialize.session",
+ )
+ app.tokens.create(name="Default")
+ app.permissions.add(permission_manage_payments)
+
+ webhook = Webhook.objects.create(
+ name="payment_gateway_initialize_session",
+ app=app,
+ target_url="http://localhost:8000/endpoint/",
+ )
+ webhook.events.create(
+ event_type=WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_SESSION
+ )
+ return app
diff --git a/saleor/app/tests/fixtures/webhooks/tax_app.py b/saleor/app/tests/fixtures/webhooks/tax_app.py
index ca68b7cbab..74b4b28af5 100644
--- a/saleor/app/tests/fixtures/webhooks/tax_app.py
+++ b/saleor/app/tests/fixtures/webhooks/tax_app.py
@@ -9,11 +9,12 @@ from .....webhook.tests.subscription_webhooks import subscription_queries
@pytest.fixture
-def tax_app(db, permission_handle_taxes):
+def tax_app(db, permission_handle_taxes, permission_manage_users):
app = App.objects.create(name="Tax App", is_active=True)
app.identifier = to_global_id_or_none(app)
app.save()
app.permissions.add(permission_handle_taxes)
+ app.permissions.add(permission_manage_users)
webhook = Webhook.objects.create(
name="tax-webhook-1",
@@ -67,26 +68,3 @@ def external_tax_app(db, permission_handle_taxes):
]
)
return app
-
-
-def tax_app_with_subscription_webhooks(db, permission_handle_taxes):
- app = App.objects.create(name="Tax App with subscription", is_active=True)
- app.permissions.add(permission_handle_taxes)
-
- webhook = Webhook.objects.create(
- name="tax-subscription-webhook-1",
- app=app,
- target_url="https://tax-app.com/api/",
- subscription_query=subscription_queries.CALCULATE_TAXES_SUBSCRIPTION_QUERY,
- )
- webhook.events.bulk_create(
- [
- WebhookEvent(event_type=event_type, webhook=webhook)
- for event_type in [
- WebhookEventSyncType.ORDER_CALCULATE_TAXES,
- WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
- ]
- ]
- )
- return app
diff --git a/saleor/checkout/tests/test_calculations.py b/saleor/checkout/tests/test_calculations.py
index af2306d7c2..b76681ad5f 100644
--- a/saleor/checkout/tests/test_calculations.py
+++ b/saleor/checkout/tests/test_calculations.py
@@ -649,7 +649,7 @@ def test_external_shipping_method_called_only_once_during_tax_calculations(
mock_send_webhook_request_sync,
checkout_with_single_item,
settings,
- tax_app_with_subscription_webhooks,
+ tax_app,
shipping_app_with_subscription,
address,
):
diff --git a/saleor/graphql/payment/tests/mutations/test_payment_gateway_initialize.py b/saleor/graphql/payment/tests/mutations/test_payment_gateway_initialize.py
index 90f716d26f..699befe642 100644
--- a/saleor/graphql/payment/tests/mutations/test_payment_gateway_initialize.py
+++ b/saleor/graphql/payment/tests/mutations/test_payment_gateway_initialize.py
@@ -1,3 +1,4 @@
+import datetime
from decimal import Decimal
from unittest import mock
@@ -8,6 +9,8 @@ from .....checkout.calculations import fetch_checkout_data
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....payment.interface import PaymentGatewayData
from .....payment.models import TransactionItem
+from .....plugins.manager import get_plugins_manager
+from .....webhook.event_types import WebhookEventSyncType
from ....core.enums import PaymentGatewayConfigErrorCode, TransactionInitializeErrorCode
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
@@ -860,3 +863,269 @@ def test_with_payment_gateways_and_amount_with_lot_of_decimal_places(
],
order,
)
+
+
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
+def test_for_checkout_with_shipping_app(
+ mocked_send_webhook_request_sync,
+ user_api_client,
+ checkout_with_prices,
+ plugins_manager,
+ shipping_app_with_subscription,
+ payment_gateway_initialize_session_app,
+ caplog,
+):
+ # given
+ mocked_send_webhook_request_sync.return_value = []
+
+ shipping_webhook = shipping_app_with_subscription.webhooks.first()
+ shipping_webhook.subscription_query = """
+ subscription {
+ event {
+ ... on ShippingListMethodsForCheckout {
+ checkout {
+ email
+ token
+ }
+ }
+ }
+ }
+ """
+ shipping_webhook.save(update_fields=["subscription_query"])
+
+ webhook_initialize_session = payment_gateway_initialize_session_app.webhooks.first()
+ webhook_initialize_session.subscription_query = """
+ subscription PaymentGatewayInitializeSession {
+ event {
+ ... on PaymentGatewayInitializeSession {
+ data
+ amount
+ sourceObject {
+ ... on Checkout {
+ id
+ token
+ shippingMethods {
+ id
+ name
+ }
+ totalPrice {
+ gross {
+ currency
+ amount
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ """
+ webhook_initialize_session.save(update_fields=["subscription_query"])
+
+ checkout = checkout_with_prices
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout = checkout_info.checkout
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "paymentGateways": [
+ {"id": payment_gateway_initialize_session_app.identifier, "data": {}}
+ ],
+ }
+
+ # when
+ response = user_api_client.post_graphql(PAYMENT_GATEWAY_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["paymentGatewayInitialize"]["errors"]
+
+ assert "No payload was generated with subscription for event" not in "".join(
+ caplog.messages
+ )
+
+ # Expect two sync calls: first to fetch external shipping methods, second to
+ # initialize payment gateway session.
+ assert mocked_send_webhook_request_sync.call_count == 2
+
+ shipping_list_call = mocked_send_webhook_request_sync.mock_calls[0]
+ shipping_list_delivery = shipping_list_call.args[0]
+ assert shipping_list_delivery.event_type == "shipping_list_methods_for_checkout"
+ assert shipping_list_delivery.payload.get_payload()
+
+ gateway_session_initialize_call = mocked_send_webhook_request_sync.mock_calls[1]
+ gateway_session_initialize_delivery = gateway_session_initialize_call.args[0]
+ assert (
+ gateway_session_initialize_delivery.event_type
+ == WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_SESSION
+ )
+ assert gateway_session_initialize_delivery.payload.get_payload()
+
+
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+@override_settings(
+ PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"],
+ CHECKOUT_PRICES_TTL=datetime.timedelta(0),
+)
+def test_for_checkout_with_tax_app(
+ mocked_send_webhook_request_sync,
+ channel_USD,
+ user_api_client,
+ checkout_with_items,
+ tax_app,
+ payment_gateway_initialize_session_app,
+ caplog,
+):
+ # given
+ mocked_send_webhook_request_sync.return_value = []
+
+ webhook_initialize_session = payment_gateway_initialize_session_app.webhooks.first()
+ webhook_initialize_session.subscription_query = """
+ subscription PaymentGatewayInitializeSession {
+ event {
+ ... on PaymentGatewayInitializeSession {
+ data
+ amount
+ sourceObject {
+ ... on Checkout {
+ id
+ token
+ totalPrice {
+ gross {
+ currency
+ amount
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ """
+ webhook_initialize_session.save(update_fields=["subscription_query"])
+
+ checkout = checkout_with_items
+ checkout.refresh_from_db()
+ lines, _ = fetch_checkout_lines(checkout)
+ manager = get_plugins_manager(allow_replica=False)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, manager, lines, force_update=True
+ )
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "paymentGateways": [
+ {"id": payment_gateway_initialize_session_app.identifier, "data": {}}
+ ],
+ }
+
+ # when
+ response = user_api_client.post_graphql(PAYMENT_GATEWAY_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["paymentGatewayInitialize"]["errors"]
+
+ assert "No payload was generated with subscription for event" not in "".join(
+ caplog.messages
+ )
+
+ # gather called event types
+ event_types = {
+ call.args[0].event_type for call in mocked_send_webhook_request_sync.mock_calls
+ }
+ assert len(event_types) == 2
+ assert WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES in event_types
+ assert WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_SESSION in event_types
+
+ for call in mocked_send_webhook_request_sync.mock_calls:
+ delivery = call.args[0]
+ assert delivery.payload.get_payload()
+
+
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
+def test_for_order_with_tax_app(
+ mocked_send_webhook_request_sync,
+ user_api_client,
+ permission_manage_payments,
+ draft_order,
+ plugins_manager,
+ tax_app,
+ payment_gateway_initialize_session_app,
+ caplog,
+):
+ # given
+ mocked_send_webhook_request_sync.return_value = []
+
+ webhook_initialize_session = payment_gateway_initialize_session_app.webhooks.first()
+ webhook_initialize_session.subscription_query = """
+ subscription PaymentGatewayInitializeSession {
+ event {
+ ... on PaymentGatewayInitializeSession {
+ data
+ amount
+ sourceObject {
+ ... on Order {
+ id
+ token
+ shippingMethods {
+ id
+ name
+ }
+ total {
+ gross {
+ currency
+ amount
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ """
+ webhook_initialize_session.save(update_fields=["subscription_query"])
+
+ order = draft_order
+ order.should_refresh_prices = True
+ order.save(update_fields=["should_refresh_prices"])
+
+ variables = {
+ "id": to_global_id_or_none(order),
+ "paymentGateways": [
+ {"id": payment_gateway_initialize_session_app.identifier, "data": {}}
+ ],
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ PAYMENT_GATEWAY_INITIALIZE,
+ variables,
+ permissions=[permission_manage_payments],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["paymentGatewayInitialize"]["errors"]
+
+ assert "No payload was generated with subscription for event" not in "".join(
+ caplog.messages
+ )
+
+ # gather called event types
+ event_types = {
+ call.args[0].event_type for call in mocked_send_webhook_request_sync.mock_calls
+ }
+ assert len(event_types) == 2
+ assert WebhookEventSyncType.ORDER_CALCULATE_TAXES in event_types
+ assert WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_SESSION in event_types
+
+ for call in mocked_send_webhook_request_sync.mock_calls:
+ delivery = call.args[0]
+ assert delivery.payload.get_payload()
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 9e3a5bb157..0f36452af3 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -21,8 +21,14 @@ from ...core.utils import build_absolute_uri
from ...core.utils.json_serializer import CustomJsonEncoder
from ...csv.notifications import get_default_export_payload
from ...graphql.core.context import SaleorContext
-from ...graphql.webhook.subscription_payload import initialize_request
-from ...graphql.webhook.utils import get_pregenerated_subscription_payload
+from ...graphql.webhook.subscription_payload import (
+ generate_payload_promise_from_subscription,
+ initialize_request,
+)
+from ...graphql.webhook.utils import (
+ get_pregenerated_subscription_payload,
+ get_subscription_query_hash,
+)
from ...payment import PaymentError, TransactionKind
from ...payment.interface import (
GatewayResponse,
@@ -3030,13 +3036,18 @@ class WebhookPlugin(BasePlugin):
amount: Decimal,
source_object: Union["Order", "Checkout"],
request: SaleorContext,
+ pregenerated_subscription_payloads: Optional[dict] = None,
):
+ if pregenerated_subscription_payloads is None:
+ pregenerated_subscription_payloads = {}
+
if not webhook.app.identifier:
logger.debug(
"Skipping app with id %s as identifier is not provided.",
webhook.app.pk,
)
return
+
if webhook.app.identifier in response_gateway:
logger.debug(
"Skipping next call for %s as app has been already processed.",
@@ -3054,6 +3065,10 @@ class WebhookPlugin(BasePlugin):
)
payload = {"id": source_object_id, "data": gateway_data, "amount": amount}
subscribable_object = (source_object, gateway_data, amount)
+
+ pregenerated_subscription_payload = get_pregenerated_subscription_payload(
+ webhook, pregenerated_subscription_payloads
+ )
response_data = trigger_webhook_sync(
event_type=WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_SESSION,
payload=json.dumps(payload, cls=CustomJsonEncoder),
@@ -3062,6 +3077,7 @@ class WebhookPlugin(BasePlugin):
subscribable_object=subscribable_object,
request=request,
requestor=self.requestor,
+ pregenerated_subscription_payload=pregenerated_subscription_payload,
)
error_msg = None
if response_data is None:
@@ -3081,6 +3097,8 @@ class WebhookPlugin(BasePlugin):
) -> list[PaymentGatewayData]:
if not self.active:
return previous_value
+
+ event_type = WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_SESSION
response_gateway: dict[str, PaymentGatewayData] = {}
apps_identifiers = None
@@ -3089,17 +3107,49 @@ class WebhookPlugin(BasePlugin):
gateways = {gateway.app_identifier: gateway for gateway in payment_gateways}
apps_identifiers = list(gateways.keys())
- webhooks = get_webhooks_for_event(
- WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_SESSION,
- apps_identifier=apps_identifiers,
+ webhooks = get_webhooks_for_event(event_type, apps_identifier=apps_identifiers)
+ request = initialize_request(
+ self.requestor, sync_event=True, event_type=event_type
)
- request = initialize_request(
- self.requestor,
- sync_event=True,
- event_type=WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_SESSION,
+ pregenerated_subscription_payloads: dict[int, dict[str, dict[str, Any]]] = (
+ defaultdict(lambda: defaultdict(dict))
)
+ promises = []
+ for webhook in webhooks:
+ if not webhook.subscription_query:
+ continue
+
+ query_hash = get_subscription_query_hash(webhook.subscription_query)
+ app = webhook.app
+
+ gateway = gateways.get(app.identifier)
+ gateway_data = None
+ if gateway:
+ gateway_data = gateway.data
+
+ subscribable_object = (source_object, gateway_data, amount)
+
+ promise_payload = generate_payload_promise_from_subscription(
+ event_type=event_type,
+ subscribable_object=subscribable_object,
+ subscription_query=webhook.subscription_query,
+ request=request,
+ app=app,
+ )
+ promises.append(promise_payload)
+
+ def store_payload(
+ payload,
+ app_id=app.pk,
+ query_hash=query_hash,
+ ):
+ if payload:
+ pregenerated_subscription_payloads[app_id][query_hash] = payload
+
+ promise_payload.then(store_payload)
+
for webhook in webhooks:
self._payment_gateway_initialize_session_for_single_webhook(
webhook=webhook,
@@ -3108,6 +3158,7 @@ class WebhookPlugin(BasePlugin):
amount=amount,
source_object=source_object,
request=request,
+ pregenerated_subscription_payloads=pregenerated_subscription_payloads,
)
return list(response_gateway.values())