Skip to content

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

Fix sending sync webhooks (#10756)

Iga Karbowiakb5dedabeb05f
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index c055f6ee65..1c74596ddd 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -1191,6 +1191,11 @@ class WebhookPlugin(BasePlugin):
previous_value,
**kwargs
) -> "GatewayResponse":
+ """Trigger payment webhook event.
+
+ Only one app should have defined the webhook for payment event.
+ If more than one app has, the webhook is sent only for the first one.
+ """
if not self.active:
return previous_value
@@ -1221,8 +1226,9 @@ class WebhookPlugin(BasePlugin):
raise PaymentError(
f"Payment with id: {payment_information.payment_id} not found."
)
+ webhook = get_webhooks_for_event(event_type, app.webhooks.all()).first()
response_data = trigger_webhook_sync(
- event_type, webhook_payload, app, subscribable_object=payment
+ event_type, webhook_payload, webhook, subscribable_object=payment
)
if response_data is None:
raise PaymentError(
@@ -1245,18 +1251,19 @@ class WebhookPlugin(BasePlugin):
**kwargs
) -> List["PaymentGateway"]:
gateways = []
- apps = App.objects.for_event_type(
- WebhookEventSyncType.PAYMENT_LIST_GATEWAYS
- ).prefetch_related("webhooks")
- for app in apps:
+ event_type = WebhookEventSyncType.PAYMENT_LIST_GATEWAYS
+ webhooks = get_webhooks_for_event(event_type)
+ for webhook in webhooks:
response_data = trigger_webhook_sync(
- event_type=WebhookEventSyncType.PAYMENT_LIST_GATEWAYS,
+ event_type=event_type,
data=generate_list_gateways_payload(currency, checkout),
- app=app,
+ webhook=webhook,
subscribable_object=checkout,
)
if response_data:
- app_gateways = parse_list_payment_gateways_response(response_data, app)
+ app_gateways = parse_list_payment_gateways_response(
+ response_data, webhook.app_id
+ )
if currency:
app_gateways = [
gtw for gtw in app_gateways if currency in gtw.currencies
@@ -1359,22 +1366,20 @@ class WebhookPlugin(BasePlugin):
self, checkout: "Checkout", previous_value: Any
) -> List["ShippingMethodData"]:
methods = []
- apps = App.objects.for_event_type(
- WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT
- ).prefetch_related("webhooks")
- if apps:
- # consider lazy loading
+ event_type = WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT
+ webhooks = get_webhooks_for_event(event_type)
+ if webhooks:
payload = generate_checkout_payload(checkout, self.requestor)
- for app in apps:
+ for webhook in webhooks:
response_data = trigger_webhook_sync(
event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
data=payload,
- app=app,
+ webhook=webhook,
subscribable_object=checkout,
)
if response_data:
shipping_methods = parse_list_shipping_methods_response(
- response_data, app
+ response_data, webhook.app_id
)
methods.extend(shipping_methods)
return methods
diff --git a/saleor/plugins/webhook/shipping.py b/saleor/plugins/webhook/shipping.py
index d5910ba1bc..5a908fdda5 100644
--- a/saleor/plugins/webhook/shipping.py
+++ b/saleor/plugins/webhook/shipping.py
@@ -2,7 +2,7 @@ import base64
import json
import logging
from collections import defaultdict
-from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Union
+from typing import Any, Callable, Dict, List, Optional, Union
from django.core.cache import cache
from django.db.models import QuerySet
@@ -20,21 +20,17 @@ from .const import CACHE_EXCLUDED_SHIPPING_TIME, EXCLUDED_SHIPPING_REQUEST_TIMEO
from .tasks import trigger_webhook_sync
from .utils import APP_ID_PREFIX
-if TYPE_CHECKING:
- from ...app.models import App
-
-
logger = logging.getLogger(__name__)
-def to_shipping_app_id(app: "App", shipping_method_id: str) -> "str":
+def to_shipping_app_id(app_id: int, shipping_method_id: str) -> "str":
return base64.b64encode(
- str.encode(f"{APP_ID_PREFIX}:{app.pk}:{shipping_method_id}")
+ str.encode(f"{APP_ID_PREFIX}:{app_id}:{shipping_method_id}")
).decode("utf-8")
def parse_list_shipping_methods_response(
- response_data: Any, app: "App"
+ response_data: Any, app_id: int
) -> List["ShippingMethodData"]:
shipping_methods = []
for shipping_method_data in response_data:
@@ -46,7 +42,7 @@ def parse_list_shipping_methods_response(
shipping_methods.append(
ShippingMethodData(
- id=to_shipping_app_id(app, method_id),
+ id=to_shipping_app_id(app_id, method_id),
name=method_name,
price=Money(method_amount, method_currency),
maximum_delivery_days=method_maximum_delivery_days,
@@ -94,7 +90,7 @@ def get_excluded_shipping_methods_or_fetch(
response_data = trigger_webhook_sync(
event_type,
payload,
- webhook.app,
+ webhook,
subscribable_object=subscribable_object,
timeout=EXCLUDED_SHIPPING_REQUEST_TIMEOUT,
)
diff --git a/saleor/plugins/webhook/tasks.py b/saleor/plugins/webhook/tasks.py
index e61bc805bd..4042800bb6 100644
--- a/saleor/plugins/webhook/tasks.py
+++ b/saleor/plugins/webhook/tasks.py
@@ -42,7 +42,7 @@ from .utils import (
)
if TYPE_CHECKING:
- from ...app.models import App
+ from ...webhook.models import Webhook
logger = logging.getLogger(__name__)
task_logger = get_task_logger(__name__)
@@ -212,13 +212,11 @@ def group_webhooks_by_subscription(webhooks):
def trigger_webhook_sync(
event_type: str,
data: str,
- app: "App",
+ webhook: Optional["Webhook"],
subscribable_object=None,
timeout=None,
) -> Optional[Dict[Any, Any]]:
"""Send a synchronous webhook request."""
- webhooks = get_webhooks_for_event(event_type, app.webhooks.all())
- webhook = webhooks.first()
if not webhook:
raise PaymentError(f"No payment webhook found for event: {event_type}.")
if webhook.subscription_query:
@@ -240,7 +238,7 @@ def trigger_webhook_sync(
kwargs = {}
if timeout:
kwargs = {"timeout": timeout}
- return send_webhook_request_sync(app.name, delivery, **kwargs)
+ return send_webhook_request_sync(webhook.app.name, delivery, **kwargs)
R = TypeVar("R")
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_webhook.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_webhook.py
index 31134a6701..e6b5a00128 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_webhook.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_webhook.py
@@ -41,7 +41,10 @@ def test_trigger_webhook_sync_with_subscription(
expected_payment_payload = generate_payment_payload(payment)
# when
trigger_webhook_sync(
- WebhookEventSyncType.PAYMENT_AUTHORIZE, data, payment_app, payment
+ WebhookEventSyncType.PAYMENT_AUTHORIZE,
+ data,
+ payment_app.webhooks.first(),
+ payment,
)
event_delivery = EventDelivery.objects.first()
diff --git a/saleor/plugins/webhook/tests/test_payment_webhook.py b/saleor/plugins/webhook/tests/test_payment_webhook.py
index bf4fe04106..8f18fd43f2 100644
--- a/saleor/plugins/webhook/tests/test_payment_webhook.py
+++ b/saleor/plugins/webhook/tests/test_payment_webhook.py
@@ -29,7 +29,7 @@ from .utils import generate_request_headers
def payment_invalid_app(payment_dummy):
app = App.objects.create(name="Dummy app", is_active=True)
gateway_id = "credit-card"
- gateway = to_payment_app_id(app, gateway_id)
+ gateway = to_payment_app_id(app.id, gateway_id)
payment_dummy.gateway = gateway
payment_dummy.save()
return payment_dummy
@@ -50,7 +50,9 @@ def webhook_data():
@mock.patch("saleor.plugins.webhook.tasks.send_webhook_request_sync")
def test_trigger_webhook_sync(mock_request, payment_app):
data = '{"key": "value"}'
- trigger_webhook_sync(WebhookEventSyncType.PAYMENT_CAPTURE, data, payment_app)
+ trigger_webhook_sync(
+ WebhookEventSyncType.PAYMENT_CAPTURE, data, payment_app.webhooks.first()
+ )
event_delivery = EventDelivery.objects.first()
mock_request.assert_called_once_with(payment_app.name, event_delivery)
@@ -68,38 +70,21 @@ def test_trigger_webhook_sync_with_subscription(
fake_delivery = "fake_delivery"
mock_delivery_create.return_value = fake_delivery
trigger_webhook_sync(
- WebhookEventSyncType.PAYMENT_CAPTURE, data, payment_app, payment
+ WebhookEventSyncType.PAYMENT_CAPTURE,
+ data,
+ payment_app.webhooks.first(),
+ payment,
)
mock_request.assert_called_once_with(payment_app.name, fake_delivery)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
-def test_trigger_webhook_sync_use_first_webhook(mock_request, payment_app):
- webhook_1 = payment_app.webhooks.first()
-
- # create additional webhook for the same event; check that always the first one will
- # be used if there are multiple webhooks for the same event.
- webhook_2 = Webhook.objects.create(
- app=payment_app,
- name="payment-webhook-2",
- target_url="https://dont-use-this-gateway.com/api/",
- )
- webhook_2.events.create(event_type=WebhookEventSyncType.PAYMENT_CAPTURE)
-
- data = '{"key": "value"}'
- trigger_webhook_sync(WebhookEventSyncType.PAYMENT_CAPTURE, data, payment_app)
- event_delivery = EventDelivery.objects.first()
- mock_request.assert_called_once_with(payment_app.name, event_delivery)
-
- assert event_delivery.webhook.target_url == webhook_1.target_url
- assert event_delivery.webhook.secret_key == webhook_1.secret_key
-
-
def test_trigger_webhook_sync_no_webhook_available():
app = App.objects.create(name="Dummy app", is_active=True)
# should raise an error for app with no payment webhooks
with pytest.raises(PaymentError):
- trigger_webhook_sync(WebhookEventSyncType.PAYMENT_REFUND, {}, app)
+ trigger_webhook_sync(
+ WebhookEventSyncType.PAYMENT_REFUND, {}, app.webhooks.first()
+ )
@mock.patch("saleor.plugins.webhook.tasks.observability.report_event_delivery_attempt")
@@ -311,10 +296,54 @@ def test_get_payment_gateways(
mock_send_request.return_value = mock_json_response
response_data = plugin.get_payment_gateways("USD", None, None)
expected_response_1 = parse_list_payment_gateways_response(
- mock_json_response, payment_app
+ mock_json_response, payment_app.id
+ )
+ expected_response_2 = parse_list_payment_gateways_response(
+ mock_json_response, app_2.id
+ )
+ assert len(response_data) == 2
+ assert response_data[0] == expected_response_1[0]
+ assert response_data[1] == expected_response_2[0]
+
+
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_get_payment_gateways_multiple_webhooks_in_the_same_app(
+ mock_send_request, payment_app, permission_manage_payments, webhook_plugin
+):
+ # given
+ # create the second webhook with the same event
+ webhook = Webhook.objects.create(
+ name="payment-webhook-2",
+ app=payment_app,
+ target_url="https://payment-gateway-2.com/api/",
+ )
+ webhook.events.bulk_create(
+ [
+ WebhookEvent(event_type=event_type, webhook=webhook)
+ for event_type in WebhookEventSyncType.PAYMENT_EVENTS
+ ]
+ )
+
+ plugin = webhook_plugin()
+ mock_json_response = [
+ {
+ "id": "credit-card",
+ "name": "Credit Card",
+ "currencies": ["USD", "EUR"],
+ "config": [],
+ }
+ ]
+ mock_send_request.return_value = mock_json_response
+
+ # when
+ response_data = plugin.get_payment_gateways("USD", None, None)
+
+ # then
+ expected_response_1 = parse_list_payment_gateways_response(
+ mock_json_response, payment_app.id
)
expected_response_2 = parse_list_payment_gateways_response(
- mock_json_response, app_2
+ mock_json_response, payment_app.id
)
assert len(response_data) == 2
assert response_data[0] == expected_response_1[0]
@@ -466,7 +495,7 @@ def test_run_payment_webhook_empty_response(mock_send_request, payment, webhook_
def test_check_plugin_id(payment_app, webhook_plugin):
plugin = webhook_plugin()
assert not plugin.check_plugin_id("dummy")
- valid_id = to_payment_app_id(payment_app, "credit-card")
+ valid_id = to_payment_app_id(payment_app.id, "credit-card")
assert plugin.check_plugin_id(valid_id)
diff --git a/saleor/plugins/webhook/tests/test_payment_webhook_utils.py b/saleor/plugins/webhook/tests/test_payment_webhook_utils.py
index cf83c077c8..13fc59e319 100644
--- a/saleor/plugins/webhook/tests/test_payment_webhook_utils.py
+++ b/saleor/plugins/webhook/tests/test_payment_webhook_utils.py
@@ -15,7 +15,7 @@ from ..utils import (
def test_to_payment_app_id(app):
gateway_id = "example-gateway"
- payment_app_id = to_payment_app_id(app, gateway_id)
+ payment_app_id = to_payment_app_id(app.id, gateway_id)
assert payment_app_id == f"{APP_ID_PREFIX}:{app.pk}:{gateway_id}"
@@ -53,8 +53,8 @@ def test_parse_list_payment_gateways_response(app):
"config": [{"field": "example-key", "value": "example-value"}],
},
]
- gateways = parse_list_payment_gateways_response(response_data, app)
- assert gateways[0].id == to_payment_app_id(app, response_data[0]["id"])
+ gateways = parse_list_payment_gateways_response(response_data, app.id)
+ assert gateways[0].id == to_payment_app_id(app.id, response_data[0]["id"])
assert gateways[0].name == response_data[0]["name"]
assert gateways[0].currencies == response_data[0]["currencies"]
assert gateways[0].config == response_data[0]["config"]
@@ -67,7 +67,7 @@ def test_parse_list_payment_gateways_response_no_id(app):
"currencies": ["USD", "EUR"],
},
]
- gateways = parse_list_payment_gateways_response(response_data, app)
+ gateways = parse_list_payment_gateways_response(response_data, app.id)
assert gateways == []
@@ -80,7 +80,7 @@ def test_parse_list_payment_gateways_response_dict_response(app):
"currencies": ["USD", "EUR"],
"config": [{"field": "example-key", "value": "example-value"}],
}
- gateways = parse_list_payment_gateways_response(response_data, app)
+ gateways = parse_list_payment_gateways_response(response_data, app.id)
assert gateways == []
diff --git a/saleor/plugins/webhook/tests/test_shipping_webhook.py b/saleor/plugins/webhook/tests/test_shipping_webhook.py
index 0431348cdd..618b2ea3f8 100644
--- a/saleor/plugins/webhook/tests/test_shipping_webhook.py
+++ b/saleor/plugins/webhook/tests/test_shipping_webhook.py
@@ -8,6 +8,7 @@ from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ....core.models import EventDelivery
from ....graphql.tests.utils import get_graphql_content
from ....webhook.event_types import WebhookEventSyncType
+from ....webhook.models import Webhook
from ....webhook.payloads import (
generate_excluded_shipping_methods_for_checkout_payload,
generate_excluded_shipping_methods_for_order_payload,
@@ -115,10 +116,11 @@ def test_excluded_shipping_methods_for_order(
assert em.id == "1"
assert webhook_reason in em.reason
assert other_reason in em.reason
+ event_type = WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS
mocked_webhook.assert_called_once_with(
WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,
payload,
- shipping_app,
+ shipping_app.webhooks.get(events__event_type=event_type),
subscribable_object=order_with_lines,
timeout=EXCLUDED_SHIPPING_REQUEST_TIMEOUT,
)
@@ -195,17 +197,18 @@ def test_multiple_app_with_excluded_shipping_methods_for_order(
assert em.id == "1"
assert webhook_reason in em.reason
assert webhook_second_reason in em.reason
+ event_type = WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS
mocked_webhook.assert_any_call(
- WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,
+ event_type,
payload,
- shipping_app,
+ shipping_app.webhooks.get(events__event_type=event_type),
subscribable_object=order_with_lines,
timeout=EXCLUDED_SHIPPING_REQUEST_TIMEOUT,
)
mocked_webhook.assert_any_call(
- WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,
+ event_type,
payload,
- second_shipping_app,
+ second_shipping_app.webhooks.get(events__event_type=event_type),
subscribable_object=order_with_lines,
timeout=EXCLUDED_SHIPPING_REQUEST_TIMEOUT,
)
@@ -224,6 +227,106 @@ def test_multiple_app_with_excluded_shipping_methods_for_order(
)
[email protected]("saleor.plugins.webhook.shipping.cache.set")
[email protected]("saleor.plugins.webhook.shipping.trigger_webhook_sync")
+ "saleor.plugins.webhook.plugin.generate_excluded_shipping_methods_for_order_payload"
+)
+def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_order(
+ mocked_payload,
+ mocked_webhook,
+ mocked_cache_set,
+ webhook_plugin,
+ order_with_lines,
+ available_shipping_methods_factory,
+ shipping_app_factory,
+):
+ # given
+ shipping_app = shipping_app_factory()
+ event_type = WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS
+
+ # create the second webhook with the same event
+ second_webhook = Webhook.objects.create(
+ name="shipping-webhook-1",
+ app=shipping_app,
+ target_url="https://shipping-gateway.com/api/",
+ )
+ second_webhook.events.create(
+ event_type=event_type,
+ webhook=second_webhook,
+ )
+
+ webhook_reason = "Order contains dangerous products."
+ webhook_second_reason = "Shipping is not applicable for this order."
+
+ mocked_webhook.side_effect = [
+ {
+ "excluded_methods": [
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),
+ "reason": webhook_reason,
+ }
+ ]
+ },
+ {
+ "excluded_methods": [
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),
+ "reason": webhook_second_reason,
+ },
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "2"),
+ "reason": webhook_second_reason,
+ },
+ ]
+ },
+ ]
+
+ payload = mock.MagicMock()
+ mocked_payload.return_value = payload
+ plugin = webhook_plugin()
+ available_shipping_methods = available_shipping_methods_factory(num_methods=2)
+ previous_value = []
+
+ # when
+ excluded_methods = plugin.excluded_shipping_methods_for_order(
+ order=order_with_lines,
+ available_shipping_methods=available_shipping_methods,
+ previous_value=previous_value,
+ )
+
+ # then
+ assert len(excluded_methods) == 2
+ em = excluded_methods[0]
+ assert em.id == "1"
+ assert webhook_reason in em.reason
+ assert webhook_second_reason in em.reason
+ webhooks = shipping_app.webhooks.filter(events__event_type=event_type)
+ assert len(webhooks) > 1
+ for webhook in webhooks:
+ mocked_webhook.assert_any_call(
+ event_type,
+ payload,
+ webhook,
+ subscribable_object=order_with_lines,
+ timeout=EXCLUDED_SHIPPING_REQUEST_TIMEOUT,
+ )
+
+ expected_cache_key = CACHE_EXCLUDED_SHIPPING_KEY + str(order_with_lines.id)
+
+ expected_excluded_shipping_method = [
+ {"id": "1", "reason": webhook_reason},
+ {"id": "1", "reason": webhook_second_reason},
+ {"id": "2", "reason": webhook_second_reason},
+ ]
+
+ mocked_cache_set.assert_called_once_with(
+ expected_cache_key,
+ (payload, expected_excluded_shipping_method),
+ CACHE_EXCLUDED_SHIPPING_TIME,
+ )
+
+
def test_parse_excluded_shipping_methods_response(app):
# given
external_id = to_shipping_app_id(app, "test-1234")
@@ -408,8 +511,9 @@ def test_checkout_shipping_methods_webhook_called_once(
@mock.patch("saleor.plugins.webhook.tasks.send_webhook_request_sync")
def test_trigger_webhook_sync(mock_request, shipping_app):
data = '{"key": "value"}'
+ webhook = shipping_app.webhooks.first()
trigger_webhook_sync(
- WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT, data, shipping_app
+ WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT, data, webhook
)
event_delivery = EventDelivery.objects.first()
mock_request.assert_called_once_with(shipping_app.name, event_delivery)
@@ -463,10 +567,11 @@ def test_excluded_shipping_methods_for_checkout(
assert em.id == "1"
assert webhook_reason in em.reason
assert other_reason in em.reason
+ event_type = WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
mocked_webhook.assert_called_once_with(
- WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ event_type,
payload,
- shipping_app,
+ shipping_app.webhooks.get(events__event_type=event_type),
subscribable_object=checkout_with_items,
timeout=EXCLUDED_SHIPPING_REQUEST_TIMEOUT,
)
@@ -544,17 +649,18 @@ def test_multiple_app_with_excluded_shipping_methods_for_checkout(
assert em.id == "1"
assert webhook_reason in em.reason
assert webhook_second_reason in em.reason
+ event_type = WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
mocked_webhook.assert_any_call(
- WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ event_type,
payload,
- shipping_app,
+ shipping_app.webhooks.get(events__event_type=event_type),
subscribable_object=checkout_with_items,
timeout=EXCLUDED_SHIPPING_REQUEST_TIMEOUT,
)
mocked_webhook.assert_any_call(
- WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ event_type,
payload,
- second_shipping_app,
+ second_shipping_app.webhooks.get(events__event_type=event_type),
subscribable_object=checkout_with_items,
timeout=EXCLUDED_SHIPPING_REQUEST_TIMEOUT,
)
@@ -574,6 +680,106 @@ def test_multiple_app_with_excluded_shipping_methods_for_checkout(
)
[email protected]("saleor.plugins.webhook.shipping.cache.set")
[email protected]("saleor.plugins.webhook.shipping.trigger_webhook_sync")
+ "saleor.plugins.webhook.plugin."
+ "generate_excluded_shipping_methods_for_checkout_payload"
+)
+def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_checkout(
+ mocked_payload,
+ mocked_webhook,
+ mocked_cache_set,
+ webhook_plugin,
+ checkout_with_items,
+ available_shipping_methods_factory,
+ shipping_app_factory,
+):
+ # given
+ shipping_app = shipping_app_factory()
+ event_type = WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
+
+ # create the second webhook with the same event
+ second_webhook = Webhook.objects.create(
+ name="shipping-webhook-1",
+ app=shipping_app,
+ target_url="https://shipping-gateway.com/api/",
+ )
+ second_webhook.events.create(
+ event_type=event_type,
+ webhook=second_webhook,
+ )
+
+ webhook_reason = "Checkout contains dangerous products."
+ webhook_second_reason = "Shipping is not applicable for this checkout."
+
+ mocked_webhook.side_effect = [
+ {
+ "excluded_methods": [
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),
+ "reason": webhook_reason,
+ }
+ ]
+ },
+ {
+ "excluded_methods": [
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),
+ "reason": webhook_second_reason,
+ },
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "2"),
+ "reason": webhook_second_reason,
+ },
+ ]
+ },
+ ]
+ payload = mock.MagicMock()
+ mocked_payload.return_value = payload
+ plugin = webhook_plugin()
+ available_shipping_methods = available_shipping_methods_factory(num_methods=2)
+ previous_value = []
+
+ # when
+ excluded_methods = plugin.excluded_shipping_methods_for_checkout(
+ checkout=checkout_with_items,
+ available_shipping_methods=available_shipping_methods,
+ previous_value=previous_value,
+ )
+
+ # then
+ assert len(excluded_methods) == 2
+ em = excluded_methods[0]
+ assert em.id == "1"
+ assert webhook_reason in em.reason
+ assert webhook_second_reason in em.reason
+ webhooks = shipping_app.webhooks.filter(events__event_type=event_type)
+ assert len(webhooks) > 1
+ for webhook in webhooks:
+ mocked_webhook.assert_any_call(
+ event_type,
+ payload,
+ webhook,
+ subscribable_object=checkout_with_items,
+ timeout=EXCLUDED_SHIPPING_REQUEST_TIMEOUT,
+ )
+
+ expected_cache_key = CACHE_EXCLUDED_SHIPPING_KEY + str(checkout_with_items.token)
+
+ expected_excluded_shipping_method = [
+ {"id": "1", "reason": webhook_reason},
+ {"id": "1", "reason": webhook_second_reason},
+ {"id": "2", "reason": webhook_second_reason},
+ ]
+
+ mocked_cache_set.assert_called_once_with(
+ expected_cache_key,
+ (payload, expected_excluded_shipping_method),
+ CACHE_EXCLUDED_SHIPPING_TIME,
+ )
+
+
def test_generate_excluded_shipping_methods_for_order_payload(
webhook_plugin,
order_with_lines,
diff --git a/saleor/plugins/webhook/utils.py b/saleor/plugins/webhook/utils.py
index 08f912b80e..6cfd6406e8 100644
--- a/saleor/plugins/webhook/utils.py
+++ b/saleor/plugins/webhook/utils.py
@@ -42,8 +42,8 @@ class ShippingAppData:
shipping_method_id: str
-def to_payment_app_id(app: App, gateway_id: str) -> "str":
- return f"{APP_ID_PREFIX}:{app.pk}:{gateway_id}"
+def to_payment_app_id(app_id: int, gateway_id: str) -> "str":
+ return f"{APP_ID_PREFIX}:{app_id}:{gateway_id}"
def from_payment_app_id(app_gateway_id: str) -> Optional["PaymentAppData"]:
@@ -59,7 +59,7 @@ def from_payment_app_id(app_gateway_id: str) -> Optional["PaymentAppData"]:
def parse_list_payment_gateways_response(
- response_data: Any, app: App
+ response_data: Any, app_id: int
) -> List["PaymentGateway"]:
gateways: List[PaymentGateway] = []
if not isinstance(response_data, list):
@@ -74,7 +74,7 @@ def parse_list_payment_gateways_response(
if gateway_id:
gateways.append(
PaymentGateway(
- id=to_payment_app_id(app, gateway_id),
+ id=to_payment_app_id(app_id, gateway_id),
name=gateway_name,
currencies=gateway_currencies,
config=gateway_config,
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index e2dfb2c01f..1398232d47 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -4594,7 +4594,7 @@ def dummy_address_data(address):
@pytest.fixture
def dummy_webhook_app_payment_data(dummy_payment_data, payment_app):
- dummy_payment_data.gateway = to_payment_app_id(payment_app, "credit-card")
+ dummy_payment_data.gateway = to_payment_app_id(payment_app.id, "credit-card")
return dummy_payment_data
@@ -5182,7 +5182,7 @@ def payment_dummy(db, order_with_lines):
@pytest.fixture
def payment(payment_dummy, payment_app):
gateway_id = "credit-card"
- gateway = to_payment_app_id(payment_app, gateway_id)
+ gateway = to_payment_app_id(payment_app.id, gateway_id)
payment_dummy.gateway = gateway
payment_dummy.save()
return payment_dummy