Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add pre-generated payload for transaction sync webhooks (#17177) (#17181)
Marcin Gębala4800fa0beb60
diff --git a/saleor/app/tests/fixtures/webhooks/payment_app.py b/saleor/app/tests/fixtures/webhooks/payment_app.pyindex b8092567e4..64cd47b921 100644--- a/saleor/app/tests/fixtures/webhooks/payment_app.py+++ b/saleor/app/tests/fixtures/webhooks/payment_app.py@@ -175,3 +175,128 @@ def payment_gateway_initialize_session_app(db, permission_manage_payments):event_type=WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_SESSION)return app+++def transaction_process_session_app(db, permission_manage_payments):+ app = App.objects.create(+ name="Transaction process session",+ is_active=True,+ identifier="saleor.payment.app.transaction.process.session",+ )+ app.tokens.create(name="Default")+ app.permissions.add(permission_manage_payments)++ webhook = Webhook.objects.create(+ name="transaction_process_session",+ app=app,+ target_url="http://localhost:8000/endpoint/",+ subscription_query="""+ subscription TransactionProcessSession {+ event {+ ... on TransactionProcessSession {+ recipient {+ id+ }+ data+ merchantReference+ action {+ amount+ currency+ actionType+ }+ transaction {+ id+ token+ pspReference+ events {+ pspReference+ }+ }+ sourceObject {+ ... on Checkout {+ id+ token+ totalPrice {+ gross {+ currency+ amount+ }+ }+ shippingMethods {+ id+ name+ }+ }+ ... on Order {+ id+ total {+ gross {+ currency+ amount+ }+ }+ }+ }+ }+ }+ }+ """,+ )+ webhook.events.create(event_type=WebhookEventSyncType.TRANSACTION_PROCESS_SESSION)+ return app+++def transaction_initialize_session_app(db, permission_manage_payments):+ app = App.objects.create(+ name="Transaction initialize session",+ is_active=True,+ identifier="saleor.payment.app.transaction.initialize.session",+ )+ app.tokens.create(name="Default")+ app.permissions.add(permission_manage_payments)++ webhook = Webhook.objects.create(+ name="Webhook",+ app=app,+ target_url="http://www.example.com",+ subscription_query="""+ subscription TransactionInitializeSession {+ event {+ ... on TransactionInitializeSession {+ transaction {+ id+ }+ sourceObject {+ ... on Checkout {+ id+ shippingMethods {+ id+ name+ }+ totalPrice {+ gross {+ amount+ currency+ }+ }+ }+ ... on Order {+ total {+ gross {+ amount+ currency+ }+ }+ }+ }+ }+ }+ }+ """,+ )+ webhook.events.create(+ event_type=WebhookEventSyncType.TRANSACTION_INITIALIZE_SESSION+ )+ return appdiff --git a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.pyindex 04fe42684b..671250df91 100644--- a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py+++ b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py@@ -24,6 +24,7 @@ from .....payment.interface import (TransactionSessionResult,)from .....payment.models import Payment, TransactionItem+from .....webhook.event_types import WebhookEventSyncTypefrom ....channel.enums import TransactionFlowStrategyEnumfrom ....core.enums import TransactionInitializeErrorCodefrom ....core.utils import to_global_id_or_none@@ -2782,3 +2783,184 @@ def test_for_checkout_empty_message()assert checkout.charge_status == CheckoutChargeStatus.PARTIALassert checkout.authorize_status == CheckoutAuthorizeStatus.PARTIAL++[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,+ app_api_client,+ checkout_with_prices,+ permission_manage_payments,+ shipping_app_with_subscription,+ transaction_initialize_session_app,+ transaction_session_response,+ caplog,+):+ # given+ mocked_send_webhook_request_sync.return_value = transaction_session_response++ shipping_webhook = shipping_app_with_subscription.webhooks.first()+ shipping_webhook.subscription_query = """+ subscription {+ event {+ ... on ShippingListMethodsForCheckout {+ checkout {+ token+ }+ }+ }+ }+ """+ shipping_webhook.save(update_fields=["subscription_query"])++ checkout = checkout_with_prices++ variables = {+ "action": TransactionFlowStrategyEnum.AUTHORIZATION.name,+ "amount": Decimal("10.00"),+ "id": to_global_id_or_none(checkout),+ "paymentGateway": {+ "id": transaction_initialize_session_app.identifier,+ "data": None,+ },+ }++ # when+ response = app_api_client.post_graphql(+ TRANSACTION_INITIALIZE, variables, permissions=[permission_manage_payments]+ )++ # then+ content = get_graphql_content(response)+ assert not content["data"]["transactionInitialize"]["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.SHIPPING_LIST_METHODS_FOR_CHECKOUT in event_types+ assert WebhookEventSyncType.TRANSACTION_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"],+ CHECKOUT_PRICES_TTL=datetime.timedelta(0),+)+def test_for_checkout_with_tax_app(+ mocked_send_webhook_request_sync,+ app_api_client,+ checkout_with_prices,+ permission_manage_payments,+ transaction_initialize_session_app,+ tax_app,+ transaction_session_response,+ caplog,+):+ # given+ mocked_send_webhook_request_sync.return_value = transaction_session_response++ checkout = checkout_with_prices+ variables = {+ "action": TransactionFlowStrategyEnum.AUTHORIZATION.name,+ "amount": Decimal("10.00"),+ "id": to_global_id_or_none(checkout),+ "paymentGateway": {+ "id": transaction_initialize_session_app.identifier,+ "data": None,+ },+ }++ # when+ response = app_api_client.post_graphql(+ TRANSACTION_INITIALIZE, variables, permissions=[permission_manage_payments]+ )++ # then+ content = get_graphql_content(response)+ assert not content["data"]["transactionInitialize"]["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.TRANSACTION_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,+ app_api_client,+ permission_manage_payments,+ draft_order,+ tax_app,+ transaction_initialize_session_app,+ transaction_session_response,+ caplog,+):+ # given+ mocked_send_webhook_request_sync.return_value = transaction_session_response++ order = draft_order+ order.should_refresh_prices = True+ order.save(update_fields=["should_refresh_prices"])++ variables = {+ "action": TransactionFlowStrategyEnum.AUTHORIZATION.name,+ "amount": Decimal("10.00"),+ "id": to_global_id_or_none(draft_order),+ "paymentGateway": {+ "id": transaction_initialize_session_app.identifier,+ "data": None,+ },+ }++ # when+ response = app_api_client.post_graphql(+ TRANSACTION_INITIALIZE,+ variables,+ permissions=[permission_manage_payments],+ check_no_permissions=False,+ )++ # then+ content = get_graphql_content(response)+ assert not content["data"]["transactionInitialize"]["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.TRANSACTION_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/graphql/payment/tests/mutations/test_transaction_process.py b/saleor/graphql/payment/tests/mutations/test_transaction_process.pyindex f331100e35..c8eaec48f2 100644--- a/saleor/graphql/payment/tests/mutations/test_transaction_process.py+++ b/saleor/graphql/payment/tests/mutations/test_transaction_process.py@@ -4,6 +4,7 @@ from unittest import mockimport grapheneimport pytest+from django.test import override_settingsfrom django.utils import timezonefrom freezegun import freeze_time@@ -23,6 +24,7 @@ from .....payment.interface import (TransactionSessionResult,)from .....payment.models import Payment, TransactionEvent+from .....webhook.event_types import WebhookEventSyncTypefrom ....core.enums import TransactionProcessErrorCodefrom ....core.utils import to_global_id_or_nonefrom ....tests.utils import assert_no_permission, get_graphql_content@@ -2366,3 +2368,205 @@ def test_for_order_empty_message(returned_data=None,expected_message=expected_response["message"],)++[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,+ app_api_client,+ checkout_with_prices,+ permission_manage_payments,+ shipping_app_with_subscription,+ transaction_process_session_app,+ transaction_item_generator,+ transaction_session_response,+ caplog,+):+ # given+ mocked_send_webhook_request_sync.return_value = transaction_session_response++ shipping_webhook = shipping_app_with_subscription.webhooks.first()+ shipping_webhook.subscription_query = """+ subscription {+ event {+ ... on ShippingListMethodsForCheckout {+ checkout {+ token+ }+ }+ }+ }+ """+ shipping_webhook.save(update_fields=["subscription_query"])++ transaction_item = transaction_item_generator(+ checkout_id=checkout_with_prices.pk, app=transaction_process_session_app+ )+ TransactionEvent.objects.create(+ transaction=transaction_item,+ amount_value=Decimal("10.00"),+ currency=transaction_item.currency,+ type=TransactionEventType.CHARGE_REQUEST,+ )++ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token),+ "data": None,+ }++ # when+ response = app_api_client.post_graphql(+ TRANSACTION_PROCESS,+ variables,+ permissions=[permission_manage_payments],+ check_no_permissions=False,+ )++ # then+ content = get_graphql_content(response)+ assert not content["data"]["transactionProcess"]["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.SHIPPING_LIST_METHODS_FOR_CHECKOUT in event_types+ assert WebhookEventSyncType.TRANSACTION_PROCESS_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"],+ CHECKOUT_PRICES_TTL=datetime.timedelta(0),+)+def test_for_checkout_with_tax_app(+ mocked_send_webhook_request_sync,+ app_api_client,+ checkout_with_prices,+ permission_manage_payments,+ tax_app,+ transaction_process_session_app,+ transaction_item_generator,+ transaction_session_response,+ caplog,+):+ # given+ mocked_send_webhook_request_sync.return_value = transaction_session_response++ transaction_item = transaction_item_generator(+ checkout_id=checkout_with_prices.pk, app=transaction_process_session_app+ )+ TransactionEvent.objects.create(+ transaction=transaction_item,+ amount_value=Decimal("10.00"),+ currency=transaction_item.currency,+ type=TransactionEventType.CHARGE_REQUEST,+ )++ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token),+ "data": None,+ }++ # when+ response = app_api_client.post_graphql(+ TRANSACTION_PROCESS,+ variables,+ permissions=[permission_manage_payments],+ check_no_permissions=False,+ )++ # then+ content = get_graphql_content(response)+ assert not content["data"]["transactionProcess"]["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.TRANSACTION_PROCESS_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,+ app_api_client,+ permission_manage_payments,+ draft_order,+ tax_app,+ transaction_process_session_app,+ transaction_item_generator,+ transaction_session_response,+ caplog,+):+ # given+ mocked_send_webhook_request_sync.return_value = transaction_session_response++ order = draft_order+ order.should_refresh_prices = True+ order.save(update_fields=["should_refresh_prices"])++ transaction_item = transaction_item_generator(+ order_id=order.pk, app=transaction_process_session_app+ )+ TransactionEvent.objects.create(+ transaction=transaction_item,+ amount_value=Decimal("10.00"),+ currency=transaction_item.currency,+ type=TransactionEventType.CHARGE_REQUEST,+ )++ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token),+ "data": None,+ }++ # when+ response = app_api_client.post_graphql(+ TRANSACTION_PROCESS,+ variables,+ permissions=[permission_manage_payments],+ check_no_permissions=False,+ )++ # then+ content = get_graphql_content(response)+ assert not content["data"]["transactionProcess"]["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.TRANSACTION_PROCESS_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.pyindex 0f36452af3..1cca7e7236 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -3194,6 +3194,22 @@ class WebhookPlugin(BasePlugin):transaction_session_data.payment_gateway_data,)+ pregenerated_subscription_payload: dict[str, Any] = {}+ if webhook.subscription_query:+ app = webhook.app+ request = initialize_request(+ self.requestor, sync_event=True, event_type=webhook_event+ )+ promise_payload = generate_payload_promise_from_subscription(+ event_type=webhook_event,+ subscribable_object=transaction_session_data,+ subscription_query=webhook.subscription_query,+ request=request,+ app=app,+ )+ if promise_payload:+ pregenerated_subscription_payload = promise_payload.get() or {}+response_data = trigger_webhook_sync(event_type=webhook_event,payload=payload,@@ -3201,6 +3217,7 @@ class WebhookPlugin(BasePlugin):allow_replica=False,subscribable_object=transaction_session_data,requestor=self.requestor,+ pregenerated_subscription_payload=pregenerated_subscription_payload,)error_msg = Noneif response_data is None: