Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Rebuild webhooks logic to handle plugins with channel configuration (#7332)
Maciej Korycinskif0fcf02eae3c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6344fce65b..d2d47f6f92 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -138,6 +138,10 @@ All notable, unreleased changes to this project will be documented in this file.- add `statusInChannels` field- add `type` field- removed `active` field. Use `statusInChannels` instead+ - Change plugin webhook endpoint - #7332 by @korycins.+ - Use /plugins/channel/<channel_slug>/<plugin_id> for plugins with channel configuration+ - Use /plugins/global/<plugin_id> for plugins with global configuration+ - Remove /plugin/<plugin_id> endpoint- Add description to shipping method - #7116 by @IKarbowiak- `ShippingMethod` was extended with `description` field.diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 94b30e61a4..fd7b34b9a8 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -1301,6 +1301,7 @@ enum ConfigurationTypeFieldEnum {SECRETPASSWORDSECRETMULTILINE+ OUTPUT}type ConfirmAccount {diff --git a/saleor/payment/gateways/adyen/plugin.py b/saleor/payment/gateways/adyen/plugin.pyindex 75ff0c70d9..4edc9a3632 100644--- a/saleor/payment/gateways/adyen/plugin.py+++ b/saleor/payment/gateways/adyen/plugin.py@@ -1,6 +1,6 @@import jsonfrom typing import List, Optional-from urllib.parse import urlencode+from urllib.parse import urlencode, urljoinimport Adyenimport opentracing@@ -10,6 +10,7 @@ from django.contrib.sites.models import Sitefrom django.core.exceptions import ObjectDoesNotExist, ValidationErrorfrom django.core.handlers.wsgi import WSGIRequestfrom django.http import HttpResponse, HttpResponseNotFound+from django.urls import reversefrom requests.exceptions import SSLErrorfrom ....checkout.models import Checkout@@ -135,8 +136,7 @@ class AdyenGatewayPlugin(BasePlugin):"help_text": ("Provide secret key generated on Adyen side.""https://docs.adyen.com/development-resources/webhooks#set-up-notificat"- "ions-in-your-customer-area. The Saleor webhook url is "- "http(s)://<your-backend-url>/plugins/mirumee.payments.adyen/webhooks/"+ "ions-in-your-customer-area."),"label": "HMAC secret key",},@@ -146,8 +146,6 @@ class AdyenGatewayPlugin(BasePlugin):"Base User provided on the Adyen side to authenticate incoming ""notifications. https://docs.adyen.com/development-resources/webhooks#""set-up-notifications-in-your-customer-area "- "The Saleor webhook url is "- "http(s)://<your-backend-url>/plugins/mirumee.payments.adyen/webhooks/"),"label": "Notification user",},@@ -157,8 +155,6 @@ class AdyenGatewayPlugin(BasePlugin):"User password provided on the Adyen side for authenticate incoming ""notifications. https://docs.adyen.com/development-resources/webhooks#""set-up-notifications-in-your-customer-area "- "The Saleor webhook url is "- "http(s)://<your-backend-url>/plugins/mirumee.payments.adyen/webhooks/"),"label": "Notification password",},@@ -184,9 +180,23 @@ class AdyenGatewayPlugin(BasePlugin):),"label": "Apple Pay certificate",},+ "webhook-endpoint": {+ "type": ConfigurationTypeField.OUTPUT,+ "help_text": (+ "Endpoint which should be used to activate Adyen's webhooks. "+ "More details can be find here: "+ "https://docs.adyen.com/development-resources/webhooks"+ ),+ "label": "Webhook endpoint",+ },}def __init__(self, *args, **kwargs):+ channel = kwargs["channel"]+ raw_configuration = kwargs["configuration"].copy()+ self._insert_webhook_endpoint_to_configuration(raw_configuration, channel)+ kwargs["configuration"] = raw_configuration+super().__init__(*args, **kwargs)configuration = {item["name"]: item["value"] for item in self.configuration}self.config = GatewayConfig(@@ -214,6 +224,28 @@ class AdyenGatewayPlugin(BasePlugin):xapikey=api_key, live_endpoint_prefix=live_endpoint, platform=platform)+ def _insert_webhook_endpoint_to_configuration(self, raw_configuration, channel):+ updated = False+ for config in raw_configuration:+ if config["name"] == "webhook-endpoint":+ updated = True+ config["value"] = self._generate_webhook_url(channel)+ if not updated:+ raw_configuration.append(+ {+ "name": "webhook-endpoint",+ "value": self._generate_webhook_url(channel),+ }+ )++ def _generate_webhook_url(self, channel) -> str:+ api_path = reverse(+ "plugins-per-channel",+ kwargs={"plugin_id": self.PLUGIN_ID, "channel_slug": channel.slug},+ )+ base_url = build_absolute_uri(api_path)+ return urljoin(base_url, "webhooks") # type: ignore+def webhook(self, request: WSGIRequest, path: str, previous_value) -> HttpResponse:config = self._get_gateway_config()if path.startswith(WEBHOOK_PATH):@@ -315,8 +347,9 @@ class AdyenGatewayPlugin(BasePlugin):return_url = prepare_url(params,build_absolute_uri(- f"/plugins/{self.PLUGIN_ID}/additional-actions"- ), # type: ignore+ f"/plugins/channel/{self.channel.slug}/" # type: ignore+ f"{self.PLUGIN_ID}/additional-actions"+ ),)request_data = request_data_for_payment(payment_information,diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.pyindex ee16f7a504..3f09cfafb7 100644--- a/saleor/plugins/base_plugin.py+++ b/saleor/plugins/base_plugin.py@@ -41,6 +41,7 @@ class ConfigurationTypeField:SECRET = "Secret"SECRET_MULTILINE = "SecretMultiline"PASSWORD = "Password"+ OUTPUT = "OUTPUT"CHOICES = [(STRING, "Field is a String"),(MULTILINE, "Field is a Multiline"),@@ -48,6 +49,7 @@ class ConfigurationTypeField:(SECRET, "Field is a Secret"),(PASSWORD, "Field is a Password"),(SECRET_MULTILINE, "Field is a Secret multiline"),+ (OUTPUT, "Field is a read only"),]@@ -667,6 +669,9 @@ class BasePlugin:and not isinstance(new_value, bool)):new_value = new_value.lower() == "true"+ if item_type == ConfigurationTypeField.OUTPUT:+ # OUTPUT field is read only. No need to update it+ continueconfig_item.update([("value", new_value)])# Get new keys that don't exist in current_config and extend it.diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex 1cb95dc9f2..e9879267e4 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -837,7 +837,6 @@ class PluginsManager(PaymentInterface):self._global_plugin_configs[pc.identifier] = pcelse:self._plugin_configs_per_channel[channel][pc.identifier] = pc-return self._global_plugin_configs, self._plugin_configs_per_channel# FIXME these methods should be more generic@@ -907,13 +906,16 @@ class PluginsManager(PaymentInterface):default_value = Falsereturn self.__run_method_on_plugins("fetch_taxes_data", default_value)- def webhook(self, request: WSGIRequest, plugin_id: str) -> HttpResponse:+ def webhook_endpoint_without_channel(+ self, request: WSGIRequest, plugin_id: str+ ) -> HttpResponse:+ # This should be removed in 3.0.0-a.25 as we want to give a possibility to have+ # no downtime between RCssplit_path = request.path.split(plugin_id, maxsplit=1)path = Noneif len(split_path) == 2:path = split_path[1]- # FIXMEdefault_value = HttpResponseNotFound()plugin = self.get_plugin(plugin_id)if not plugin:@@ -922,6 +924,32 @@ class PluginsManager(PaymentInterface):plugin, "webhook", default_value, request, path)+ def webhook(+ self, request: WSGIRequest, plugin_id: str, channel_slug: Optional[str] = None+ ) -> HttpResponse:+ split_path = request.path.split(plugin_id, maxsplit=1)+ path = None+ if len(split_path) == 2:+ path = split_path[1]++ default_value = HttpResponseNotFound()+ plugin = self.get_plugin(plugin_id, channel_slug=channel_slug)+ if not plugin:+ return default_value++ if not plugin.active:+ return default_value++ if plugin.CONFIGURATION_PER_CHANNEL and not channel_slug:+ return HttpResponseNotFound(+ "Incorrect endpoint. Use /plugins/channel/<channel_slug>/"+ f"{plugin.PLUGIN_ID}/"+ )++ return self.__run_method_on_single_plugin(+ plugin, "webhook", default_value, request, path+ )+def notify(self,event: "NotifyEventTypeChoice",diff --git a/saleor/plugins/tests/sample_plugins.py b/saleor/plugins/tests/sample_plugins.pyindex db9af16bfa..4ad35df9e1 100644--- a/saleor/plugins/tests/sample_plugins.py+++ b/saleor/plugins/tests/sample_plugins.py@@ -238,6 +238,22 @@ class ChannelPluginSample(PluginSample):}+class InactiveChannelPluginSample(PluginSample):+ PLUGIN_ID = "channel.plugin.inactive.sample"+ PLUGIN_NAME = "Inactive Channel Plugin"+ PLUGIN_DESCRIPTION = "Test channel plugin"+ DEFAULT_ACTIVE = False+ CONFIGURATION_PER_CHANNEL = True+ DEFAULT_CONFIGURATION = [{"name": "input-per-channel", "value": None}]+ CONFIG_STRUCTURE = {+ "input-per-channel": {+ "type": ConfigurationTypeField.STRING,+ "help_text": "Test input",+ "label": "Input per channel",+ }+ }++class PluginInactive(BasePlugin):PLUGIN_ID = "mirumee.taxes.plugin.inactive"PLUGIN_NAME = "PluginInactive"diff --git a/saleor/plugins/tests/test_views.py b/saleor/plugins/tests/test_views.pyindex 1a67ec8030..6121f7a572 100644--- a/saleor/plugins/tests/test_views.py+++ b/saleor/plugins/tests/test_views.py@@ -1,6 +1,11 @@import pytest-from .sample_plugins import PluginInactive, PluginSample+from .sample_plugins import (+ ChannelPluginSample,+ InactiveChannelPluginSample,+ PluginInactive,+ PluginSample,+)@pytest.mark.parametrize(@@ -21,3 +26,47 @@ def test_plugin_webhook_view(response = client.post(f"/plugins/{plugin_id}{plugin_path}")assert response.status_code == status_code+++ "plugin_id, plugin_path, status_code",+ [+ (PluginSample.PLUGIN_ID, "/webhook/paid", 200),+ (ChannelPluginSample.PLUGIN_ID, "/webhook/paid", 200),+ (InactiveChannelPluginSample.PLUGIN_ID, "/webhook/paid", 404),+ ("wrong.id", "/webhook/", 404),+ ],+)+def test_plugin_per_channel_webhook_view(+ plugin_id, plugin_path, status_code, client, settings, monkeypatch, channel_PLN+):+ settings.PLUGINS = [+ "saleor.plugins.tests.sample_plugins.PluginSample",+ "saleor.plugins.tests.sample_plugins.ChannelPluginSample",+ "saleor.plugins.tests.sample_plugins.InactiveChannelPluginSample",+ ]++ response = client.post(+ f"/plugins/channel/{channel_PLN.slug}/{plugin_id}{plugin_path}"+ )+ assert response.status_code == status_code+++ "plugin_id, plugin_path, status_code",+ [+ (PluginSample.PLUGIN_ID, "/webhook/paid", 200),+ (PluginInactive.PLUGIN_ID, "/webhook/paid", 404),+ ("wrong.id", "/webhook/", 404),+ ],+)+def test_plugin_global_webhook_view(+ plugin_id, plugin_path, status_code, client, settings, monkeypatch, channel_PLN+):+ settings.PLUGINS = [+ "saleor.plugins.tests.sample_plugins.PluginSample",+ "saleor.plugins.tests.sample_plugins.PluginInactive",+ ]++ response = client.post(f"/plugins/global/{plugin_id}{plugin_path}")+ assert response.status_code == status_codediff --git a/saleor/plugins/views.py b/saleor/plugins/views.pyindex 7b0f859fcc..14f31fbaf3 100644--- a/saleor/plugins/views.py+++ b/saleor/plugins/views.py@@ -6,4 +6,16 @@ from .manager import get_plugins_managerdef handle_plugin_webhook(request: WSGIRequest, plugin_id: str) -> HttpResponse:manager = get_plugins_manager()- return manager.webhook(request, plugin_id)+ return manager.webhook_endpoint_without_channel(request, plugin_id)+++def handle_global_plugin_webhook(request: WSGIRequest, plugin_id: str) -> HttpResponse:+ manager = get_plugins_manager()+ return manager.webhook(request, plugin_id, channel_slug=None)+++def handle_plugin_per_channel_webhook(+ request: WSGIRequest, plugin_id: str, channel_slug: str+) -> HttpResponse:+ manager = get_plugins_manager()+ return manager.webhook(request, plugin_id, channel_slug=channel_slug)diff --git a/saleor/urls.py b/saleor/urls.pyindex 90e073579b..7cc90f8e9d 100644--- a/saleor/urls.py+++ b/saleor/urls.py@@ -6,7 +6,11 @@ from django.views.decorators.csrf import csrf_exemptfrom .graphql.api import schemafrom .graphql.views import GraphQLView-from .plugins.views import handle_plugin_webhook+from .plugins.views import (+ handle_global_plugin_webhook,+ handle_plugin_per_channel_webhook,+ handle_plugin_webhook,+)from .product.views import digital_producturlpatterns = [@@ -16,6 +20,17 @@ urlpatterns = [digital_product,name="digital-product",),+ url(+ r"plugins/channel/(?P<channel_slug>[.0-9A-Za-z_\-]+)/"+ r"(?P<plugin_id>[.0-9A-Za-z_\-]+)/",+ handle_plugin_per_channel_webhook,+ name="plugins-per-channel",+ ),+ url(+ r"plugins/global/(?P<plugin_id>[.0-9A-Za-z_\-]+)/",+ handle_global_plugin_webhook,+ name="plugins-global",+ ),url(r"plugins/(?P<plugin_id>[.0-9A-Za-z_\-]+)/",handle_plugin_webhook,