Skip to content

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

Add endpoint handler for plugins

Maciej Korycinski8402fdde14f0
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index 9e2345ee58..48b5963ed5 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -2,6 +2,8 @@ from copy import copy
from decimal import Decimal
from typing import TYPE_CHECKING, Any, List, Optional, Union
+from django.core.handlers.wsgi import WSGIRequest
+from django.http import HttpResponse
from django_countries.fields import Country
from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
@@ -57,6 +59,13 @@ class BasePlugin:
def __str__(self):
return self.PLUGIN_NAME
+ def webhook(self, request: WSGIRequest, path: str, previous_value) -> HttpResponse:
+ """Handle received http request.
+
+ Overwrite this method if the plugin expects the incoming requests.
+ """
+ return NotImplemented
+
def change_user_address(
self,
address: "Address",
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index a43a1ae2d2..02ff51ce4d 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -3,6 +3,8 @@ from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Union
import opentracing
from django.conf import settings
+from django.core.handlers.wsgi import WSGIRequest
+from django.http import HttpResponse, HttpResponseNotFound
from django.utils.module_loading import import_string
from django_countries.fields import Country
from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
@@ -461,6 +463,20 @@ class PluginsManager(PaymentInterface):
default_value = False
return self.__run_method_on_plugins("fetch_taxes_data", default_value)
+ def webhook(self, request: WSGIRequest, plugin_id: str) -> 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)
+ if not plugin:
+ return default_value
+ return self.__run_method_on_single_plugin(
+ plugin, "webhook", default_value, request, path
+ )
+
def get_plugins_manager(
manager_path: str = None, plugins: List[str] = None
diff --git a/saleor/plugins/tests/sample_plugins.py b/saleor/plugins/tests/sample_plugins.py
index 3f0dd7e787..4d432ed705 100644
--- a/saleor/plugins/tests/sample_plugins.py
+++ b/saleor/plugins/tests/sample_plugins.py
@@ -1,6 +1,8 @@
from decimal import Decimal
from typing import TYPE_CHECKING, Union
+from django.core.handlers.wsgi import WSGIRequest
+from django.http import HttpResponse, HttpResponseNotFound, JsonResponse
from django_countries.fields import Country
from prices import Money, TaxedMoney
@@ -47,6 +49,13 @@ class PluginSample(BasePlugin):
},
}
+ def webhook(self, request: WSGIRequest, path: str, previous_value) -> HttpResponse:
+ if path == "/webhook/paid":
+ return JsonResponse(data={"received": True, "paid": True})
+ if path == "/webhook/failed":
+ return JsonResponse(data={"received": True, "paid": False})
+ return HttpResponseNotFound()
+
def calculate_checkout_total(self, checkout, lines, discounts, previous_value):
total = Money("1.0", currency=checkout.currency)
return TaxedMoney(total, total)
diff --git a/saleor/plugins/tests/test_manager.py b/saleor/plugins/tests/test_manager.py
index 4669ccdae6..c7096ed5e2 100644
--- a/saleor/plugins/tests/test_manager.py
+++ b/saleor/plugins/tests/test_manager.py
@@ -1,6 +1,8 @@
+import json
from decimal import Decimal
import pytest
+from django.http import HttpResponseNotFound, JsonResponse
from django_countries.fields import Country
from prices import Money, TaxedMoney
@@ -340,3 +342,44 @@ def test_manager_serve_list_all_payment_gateways_specified_currency_two_gateways
manager.list_payment_gateways(currency="USD", active_only=False)
== expected_gateways
)
+
+
+def test_manager_webhook(rf):
+ plugins = [
+ "saleor.plugins.tests.sample_plugins.PluginSample",
+ "saleor.plugins.tests.sample_plugins.PluginInactive",
+ ]
+ manager = PluginsManager(plugins=plugins)
+ plugin_path = "/webhook/paid"
+ request = rf.post(path=f"/plugins/{PluginSample.PLUGIN_ID}{plugin_path}")
+
+ response = manager.webhook(request, PluginSample.PLUGIN_ID)
+ assert isinstance(response, JsonResponse)
+ assert response.status_code == 200
+ assert response.content.decode() == json.dumps({"received": True, "paid": True})
+
+
+def test_manager_webhook_plugin_doesnt_have_webhook_support(rf):
+ plugins = [
+ "saleor.plugins.tests.sample_plugins.PluginInactive",
+ ]
+
+ manager = PluginsManager(plugins=plugins)
+ plugin_path = "/webhook/paid"
+ request = rf.post(path=f"/plugins/{PluginInactive.PLUGIN_ID}{plugin_path}")
+ response = manager.webhook(request, PluginSample.PLUGIN_ID)
+ assert isinstance(response, HttpResponseNotFound)
+ assert response.status_code == 404
+
+
+def test_manager_inncorrect_plugin(rf):
+ plugins = [
+ "saleor.plugins.tests.sample_plugins.PluginSample",
+ "saleor.plugins.tests.sample_plugins.PluginInactive",
+ ]
+ manager = PluginsManager(plugins=plugins)
+ plugin_path = "/webhook/paid"
+ request = rf.post(path=f"/plugins/incorrect.plugin.id{plugin_path}")
+ response = manager.webhook(request, "incorrect.plugin.id")
+ assert isinstance(response, HttpResponseNotFound)
+ assert response.status_code == 404
diff --git a/saleor/plugins/tests/test_views.py b/saleor/plugins/tests/test_views.py
new file mode 100644
index 0000000000..1a67ec8030
--- /dev/null
+++ b/saleor/plugins/tests/test_views.py
@@ -0,0 +1,23 @@
+import pytest
+
+from .sample_plugins import PluginInactive, PluginSample
+
+
+ "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_webhook_view(
+ plugin_id, plugin_path, status_code, client, settings, monkeypatch
+):
+ settings.PLUGINS = [
+ "saleor.plugins.tests.sample_plugins.PluginSample",
+ "saleor.plugins.tests.sample_plugins.PluginInactive",
+ ]
+
+ response = client.post(f"/plugins/{plugin_id}{plugin_path}")
+ assert response.status_code == status_code
diff --git a/saleor/plugins/views.py b/saleor/plugins/views.py
new file mode 100644
index 0000000000..7b0f859fcc
--- /dev/null
+++ b/saleor/plugins/views.py
@@ -0,0 +1,9 @@
+from django.core.handlers.wsgi import WSGIRequest
+from django.http import HttpResponse
+
+from .manager import get_plugins_manager
+
+
+def handle_plugin_webhook(request: WSGIRequest, plugin_id: str) -> HttpResponse:
+ manager = get_plugins_manager()
+ return manager.webhook(request, plugin_id)
diff --git a/saleor/urls.py b/saleor/urls.py
index c95fcb3dea..8589b4d398 100644
--- a/saleor/urls.py
+++ b/saleor/urls.py
@@ -7,6 +7,7 @@ from django.views.decorators.csrf import csrf_exempt
from .data_feeds.urls import urlpatterns as feed_urls
from .graphql.api import schema
from .graphql.views import GraphQLView
+from .plugins.views import handle_plugin_webhook
from .product.views import digital_product
urlpatterns = [
@@ -17,6 +18,11 @@ urlpatterns = [
digital_product,
name="digital-product",
),
+ url(
+ r"plugins/(?P<plugin_id>[.0-9A-Za-z_\-]+)/",
+ handle_plugin_webhook,
+ name="plugins",
+ ),
]
if settings.DEBUG: