Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Payment webhooks (#7044)
Marcin Gębala21925c3ba082
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 556b21385a..775d71f929 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -97,6 +97,7 @@ All notable, unreleased changes to this project will be documented in this file.- `undiscounted_total_price_net_amount`- `undiscounted_total_price_gross_amount`- Copy metadata fields when creating reissue - #7358 by @IKarbowiak+- Add payment webhooks - #7044 by @maarcingebala- Fix invoice generation - #7376 by @tomaszszymanski129- Allow defining only one field in translations - #7363 by @IKarbowiak- Trigger `checkout_updated` hook for checkout meta mutations - #7392 by @maarcingebaladiff --git a/saleor/app/models.py b/saleor/app/models.pyindex 865eb13750..bc3728df96 100644--- a/saleor/app/models.py+++ b/saleor/app/models.py@@ -6,9 +6,26 @@ from oauthlib.common import generate_tokenfrom ..core.models import Job, ModelWithMetadatafrom ..core.permissions import AppPermission+from ..webhook.event_types import WebhookEventTypefrom .types import AppType+class AppQueryset(models.QuerySet):+ def for_event_type(self, event_type: str):+ permissions = {}+ required_permission = WebhookEventType.PERMISSIONS.get(event_type)+ if required_permission:+ app_label, codename = required_permission.value.split(".")+ permissions["permissions__content_type__app_label"] = app_label+ permissions["permissions__codename"] = codename+ return self.filter(+ is_active=True,+ webhooks__is_active=True,+ webhooks__events__event_type=event_type,+ **permissions,+ )++class App(ModelWithMetadata):name = models.CharField(max_length=60)created = models.DateTimeField(auto_now_add=True)@@ -33,6 +50,8 @@ class App(ModelWithMetadata):app_url = models.URLField(blank=True, null=True)version = models.CharField(max_length=60, blank=True, null=True)+ objects = AppQueryset.as_manager()+class Meta(ModelWithMetadata.Meta):ordering = ("name", "pk")permissions = (@@ -42,6 +61,9 @@ class App(ModelWithMetadata):),)+ def __str__(self):+ return self.name+def get_permissions(self) -> Set[str]:"""Return the permissions of the app."""if not self.is_active:diff --git a/saleor/app/tests/test_models.py b/saleor/app/tests/test_models.pynew file mode 100644index 0000000000..f013b73782--- /dev/null+++ b/saleor/app/tests/test_models.py@@ -0,0 +1,37 @@+from ...app.models import App+from ...webhook.event_types import WebhookEventType+++def test_qs_for_event_type(payment_app):+ qs = App.objects.for_event_type(WebhookEventType.PAYMENT_AUTHORIZE)+ assert len(qs) == 1+ assert qs[0] == payment_app+++def test_qs_for_event_type_no_payment_permissions(payment_app):+ payment_app.permissions.first().delete()+ qs = App.objects.for_event_type(WebhookEventType.PAYMENT_AUTHORIZE)+ assert len(qs) == 0+++def test_qs_for_event_type_inactive_app(payment_app):+ payment_app.is_active = False+ payment_app.save()+ qs = App.objects.for_event_type(WebhookEventType.PAYMENT_AUTHORIZE)+ assert len(qs) == 0+++def test_qs_for_event_type_no_webhook_event(payment_app):+ webhook = payment_app.webhooks.first()+ event = webhook.events.filter(event_type=WebhookEventType.PAYMENT_AUTHORIZE).first()+ event.delete()+ qs = App.objects.for_event_type(WebhookEventType.PAYMENT_AUTHORIZE)+ assert len(qs) == 0+++def test_qs_for_event_type_inactive_webhook(payment_app):+ webhook = payment_app.webhooks.first()+ webhook.is_active = False+ webhook.save()+ qs = App.objects.for_event_type(WebhookEventType.PAYMENT_AUTHORIZE)+ assert len(qs) == 0diff --git a/saleor/core/permissions.py b/saleor/core/permissions.pyindex 5ce97ec09a..a077d0cdc6 100644--- a/saleor/core/permissions.py+++ b/saleor/core/permissions.py@@ -47,6 +47,10 @@ class OrderPermissions(BasePermissionEnum):MANAGE_ORDERS = "order.manage_orders"+class PaymentPermissions(BasePermissionEnum):+ HANDLE_PAYMENTS = "payment.handle_payments"++class PagePermissions(BasePermissionEnum):MANAGE_PAGES = "page.manage_pages"@@ -83,6 +87,7 @@ PERMISSIONS_ENUMS = [OrderPermissions,PagePermissions,PageTypePermissions,+ PaymentPermissions,ProductPermissions,ProductTypePermissions,ShippingPermissions,diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.pyindex 2231503b3a..c5cf8634b2 100644--- a/saleor/graphql/payment/mutations.py+++ b/saleor/graphql/payment/mutations.py@@ -81,11 +81,17 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):@classmethoddef validate_gateway(cls, manager, gateway_id, currency):+ """Validate if given gateway can be used for this checkout.++ Check if provided gateway_id is on the list of available payment gateways.+ Gateway will be rejected if gateway_id is invalid or a gateway doesn't support+ checkout's currency.+ """if not is_currency_supported(currency, gateway_id, manager):raise ValidationError({"gateway": ValidationError(- f"The gateway {gateway_id} does not support checkout currency.",+ f"The gateway {gateway_id} is not available for this checkout.",code=PaymentErrorCode.NOT_SUPPORTED_GATEWAY.value,)}diff --git a/saleor/graphql/payment/types.py b/saleor/graphql/payment/types.pyindex 28654f29ef..1e566f2422 100644--- a/saleor/graphql/payment/types.py+++ b/saleor/graphql/payment/types.py@@ -157,8 +157,11 @@ class Payment(CountableDjangoObjectType):@traced_resolverdef resolve_credit_card(root: models.Payment, _info):data = {- "last_digits": root.cc_last_digits,"brand": root.cc_brand,+ "exp_month": root.cc_exp_month,+ "exp_year": root.cc_exp_year,+ "first_digits": root.cc_first_digits,+ "last_digits": root.cc_last_digits,}if not any(data.values()):return Nonediff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 18777a2e71..c049f530e4 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -3917,6 +3917,7 @@ enum PermissionEnum {MANAGE_ORDERSMANAGE_PAGESMANAGE_PAGE_TYPES_AND_ATTRIBUTES+ HANDLE_PAYMENTSMANAGE_PRODUCTSMANAGE_PRODUCT_TYPES_AND_ATTRIBUTESMANAGE_SHIPPING@@ -6096,6 +6097,13 @@ enum WebhookEventTypeEnum {PAGE_CREATEDPAGE_UPDATEDPAGE_DELETED+ PAYMENT_AUTHORIZE+ PAYMENT_CAPTURE+ PAYMENT_CONFIRM+ PAYMENT_LIST_GATEWAYS+ PAYMENT_PROCESS+ PAYMENT_REFUND+ PAYMENT_VOID}enum WebhookSampleEventTypeEnum {@@ -6123,6 +6131,13 @@ enum WebhookSampleEventTypeEnum {PAGE_CREATEDPAGE_UPDATEDPAGE_DELETED+ PAYMENT_AUTHORIZE+ PAYMENT_CAPTURE+ PAYMENT_CONFIRM+ PAYMENT_LIST_GATEWAYS+ PAYMENT_PROCESS+ PAYMENT_REFUND+ PAYMENT_VOID}type WebhookUpdate {diff --git a/saleor/payment/gateways/authorize_net/tests/test_authorize_net.py b/saleor/payment/gateways/authorize_net/tests/test_authorize_net.pyindex 00986bed1a..e72b5f329c 100644--- a/saleor/payment/gateways/authorize_net/tests/test_authorize_net.py+++ b/saleor/payment/gateways/authorize_net/tests/test_authorize_net.py@@ -113,6 +113,7 @@ def test_process_payment_error_response_null(@pytest.mark.vcr()def test_refund(authorize_net_payment, authorize_net_gateway_config):payment_data = PaymentData(+ authorize_net_payment.gateway,REFUND_AMOUNT,"USD",None,@@ -138,6 +139,7 @@ def test_refund(authorize_net_payment, authorize_net_gateway_config):@pytest.mark.vcr()def test_refund_error(authorize_net_payment, authorize_net_gateway_config):payment_data = PaymentData(+ authorize_net_payment.gateway,REFUND_AMOUNT,"USD",None,@@ -188,6 +190,7 @@ def test_authorize_and_capture(dummy_payment_data, authorize_net_gateway_config)@pytest.mark.vcr()def test_void(authorize_net_payment, authorize_net_gateway_config):payment_data = PaymentData(+ authorize_net_payment.gateway,None,None,None,@@ -216,6 +219,7 @@ def test_void_duplicate(authorize_net_payment, authorize_net_gateway_config):Authorize.net considers this a successful transaction"""payment_data = PaymentData(+ authorize_net_payment.gateway,None,None,None,@@ -241,6 +245,7 @@ def test_void_duplicate(authorize_net_payment, authorize_net_gateway_config):def test_void_failure(authorize_net_payment, authorize_net_gateway_config):"""Test with invalid transaction id"""payment_data = PaymentData(+ authorize_net_payment.gateway,None,None,None,diff --git a/saleor/payment/interface.py b/saleor/payment/interface.pyindex abd61b2073..dff6f001d6 100644--- a/saleor/payment/interface.py+++ b/saleor/payment/interface.py@@ -66,6 +66,7 @@ class PaymentData:It is required to communicate between Saleor and given payment gateway."""+ gateway: stramount: Decimalcurrency: strbilling: Optional[AddressData]diff --git a/saleor/payment/migrations/0029_alter_payment_options.py b/saleor/payment/migrations/0029_alter_payment_options.pynew file mode 100644index 0000000000..149e313095--- /dev/null+++ b/saleor/payment/migrations/0029_alter_payment_options.py@@ -0,0 +1,35 @@+# Generated by Django 3.2.2 on 2021-05-19 09:50++from django.core.management.sql import emit_post_migrate_signal+from django.db import migrations+++def assing_permissions(apps, schema_editor):+ # force post signal as permissions are created in post migrate signals+ # related Django issue https://code.djangoproject.com/ticket/23422+ emit_post_migrate_signal(2, False, "default")+ Group = apps.get_model("auth", "Group")+ Permission = apps.get_model("auth", "Permission")+ handle_payments = Permission.objects.filter(+ codename="handle_payments", content_type__app_label="payment"+ ).first()+ for group in Group.objects.iterator():+ group.permissions.add(handle_payments)+++class Migration(migrations.Migration):++ dependencies = [+ ("payment", "0028_drop_searchable_key"),+ ]++ operations = [+ migrations.AlterModelOptions(+ name="payment",+ options={+ "ordering": ("pk",),+ "permissions": (("handle_payments", "Handle payments"),),+ },+ ),+ migrations.RunPython(assing_permissions, migrations.RunPython.noop),+ ]diff --git a/saleor/payment/models.py b/saleor/payment/models.pyindex 4422887a42..03b4bf47c6 100644--- a/saleor/payment/models.py+++ b/saleor/payment/models.py@@ -10,6 +10,7 @@ from django.db.models import JSONField # type: ignorefrom prices import Moneyfrom ..checkout.models import Checkout+from ..core.permissions import PaymentPermissionsfrom ..core.taxes import zero_moneyfrom . import ChargeStatus, CustomPaymentChoices, TransactionKind@@ -92,6 +93,12 @@ class Payment(models.Model):class Meta:ordering = ("pk",)+ permissions = (+ (+ PaymentPermissions.HANDLE_PAYMENTS.codename,+ "Handle payments",+ ),+ )indexes = [# Orders filtering by status indexGinIndex(fields=["order_id", "is_active", "charge_status"]),diff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex bb16c9f4c1..4026c40d01 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -53,6 +53,7 @@ def create_payment_information(graphql_payment_id = graphene.Node.to_global_id("Payment", payment.pk)return PaymentData(+ gateway=payment.gateway,token=payment_token,amount=amount or payment.total,currency=payment.currency,diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.pyindex 3f09cfafb7..520f2e62c5 100644--- a/saleor/plugins/base_plugin.py+++ b/saleor/plugins/base_plugin.py@@ -77,6 +77,11 @@ class BasePlugin:DEFAULT_CONFIGURATION = []DEFAULT_ACTIVE = False+ @classmethod+ def check_plugin_id(cls, plugin_id: str) -> bool:+ """Check if given plugin_id matches with the PLUGIN_ID of this plugin."""+ return cls.PLUGIN_ID == plugin_id+def __init__(self,*,diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex e9879267e4..5cc5dae75b 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -32,7 +32,6 @@ from .models import PluginConfigurationif TYPE_CHECKING:# flake8: noqafrom ..account.models import Address, User- from ..channel.models import Channelfrom ..checkout.fetch import CheckoutInfo, CheckoutLineInfofrom ..checkout.models import Checkoutfrom ..invoice.models import Invoice@@ -46,13 +45,7 @@ if TYPE_CHECKING:PaymentGateway,TokenConfig,)- from ..product.models import (- Collection,- Product,- ProductType,- ProductVariant,- ProductVariantChannelListing,- )+ from ..product.models import Product, ProductType, ProductVariantfrom .base_plugin import BasePlugin@@ -654,49 +647,43 @@ class PluginsManager(PaymentInterface):def authorize_payment(self, gateway: str, payment_information: "PaymentData", channel_slug: str) -> "GatewayResponse":- method_name = "authorize_payment"return self.__run_payment_method(- gateway, method_name, payment_information, channel_slug=channel_slug+ gateway, "authorize_payment", payment_information, channel_slug=channel_slug)def capture_payment(self, gateway: str, payment_information: "PaymentData", channel_slug: str) -> "GatewayResponse":- method_name = "capture_payment"return self.__run_payment_method(- gateway, method_name, payment_information, channel_slug=channel_slug+ gateway, "capture_payment", payment_information, channel_slug=channel_slug)def refund_payment(self, gateway: str, payment_information: "PaymentData", channel_slug: str) -> "GatewayResponse":- method_name = "refund_payment"return self.__run_payment_method(- gateway, method_name, payment_information, channel_slug=channel_slug+ gateway, "refund_payment", payment_information, channel_slug=channel_slug)def void_payment(self, gateway: str, payment_information: "PaymentData", channel_slug: str) -> "GatewayResponse":- method_name = "void_payment"return self.__run_payment_method(- gateway, method_name, payment_information, channel_slug=channel_slug+ gateway, "void_payment", payment_information, channel_slug=channel_slug)def confirm_payment(self, gateway: str, payment_information: "PaymentData", channel_slug: str) -> "GatewayResponse":- method_name = "confirm_payment"return self.__run_payment_method(- gateway, method_name, payment_information, channel_slug=channel_slug+ gateway, "confirm_payment", payment_information, channel_slug=channel_slug)def process_payment(self, gateway: str, payment_information: "PaymentData", channel_slug: str) -> "GatewayResponse":- method_name = "process_payment"return self.__run_payment_method(- gateway, method_name, payment_information, channel_slug=channel_slug+ gateway, "process_payment", payment_information, channel_slug=channel_slug)def token_is_required_as_payment_input(@@ -753,19 +740,6 @@ class PluginsManager(PaymentInterface):plugins = [plugin for plugin in plugins if plugin.active]return plugins- def list_payment_plugin(- self, active_only: bool = False, channel_slug: Optional["str"] = None- ) -> Dict[str, "BasePlugin"]:- payment_method = "process_payment"-- plugins = self.get_plugins(channel_slug=channel_slug, active_only=active_only)-- return {- plugin.PLUGIN_ID: plugin- for plugin in plugins- if payment_method in type(plugin).__dict__- }-def list_payment_gateways(self,currency: Optional[str] = None,@@ -774,13 +748,14 @@ class PluginsManager(PaymentInterface):active_only: bool = True,) -> List["PaymentGateway"]:channel_slug = checkout.channel.slug if checkout else channel_slug+ plugins = self.get_plugins(channel_slug=channel_slug, active_only=active_only)+ payment_plugins = [+ plugin for plugin in plugins if "process_payment" in type(plugin).__dict__+ ]- payment_plugins = self.list_payment_plugin(- active_only=active_only, channel_slug=channel_slug- )# if currency is given return only gateways which support given currencygateways = []- for plugin in payment_plugins.values():+ for plugin in payment_plugins:gateways.extend(plugin.get_payment_gateways(currency=currency, checkout=checkout, previous_value=None@@ -806,10 +781,10 @@ class PluginsManager(PaymentInterface):**kwargs,) -> "GatewayResponse":default_value = None- gtw = self.get_plugin(gateway, channel_slug)- if gtw is not None:+ plugin = self.get_plugin(gateway, channel_slug)+ if plugin is not None:resp = self.__run_method_on_single_plugin(- gtw,+ plugin,method_name,previous_value=default_value,payment_information=payment_information,@@ -898,7 +873,7 @@ class PluginsManager(PaymentInterface):) -> Optional["BasePlugin"]:plugins = self.get_plugins(channel_slug=channel_slug)for plugin in plugins:- if plugin.PLUGIN_ID == plugin_id:+ if plugin.check_plugin_id(plugin_id):return pluginreturn Nonediff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex 7f21d9fa34..058da08a70 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -1,21 +1,31 @@import json+import loggingfrom typing import TYPE_CHECKING, Any, List, Optional+from ...app.models import Appfrom ...core.utils.json_serializer import CustomJsonEncoder+from ...payment import PaymentError, TransactionKindfrom ...webhook.event_types import WebhookEventTypefrom ...webhook.payloads import (generate_checkout_payload,generate_customer_payload,generate_fulfillment_payload,generate_invoice_payload,+ generate_list_gateways_payload,generate_order_payload,generate_page_payload,+ generate_payment_payload,generate_product_deleted_payload,generate_product_payload,generate_product_variant_payload,)from ..base_plugin import BasePlugin-from .tasks import trigger_webhooks_for_event+from .tasks import trigger_webhook_sync, trigger_webhooks_for_event+from .utils import (+ from_payment_app_id,+ parse_list_payment_gateways_response,+ parse_payment_action_response,+)if TYPE_CHECKING:from ...account.models import User@@ -24,15 +34,27 @@ if TYPE_CHECKING:from ...invoice.models import Invoicefrom ...order.models import Fulfillment, Orderfrom ...page.models import Page+ from ...payment.interface import GatewayResponse, PaymentData, PaymentGatewayfrom ...product.models import Product, ProductVariant+logger = logging.getLogger(__name__)++class WebhookPlugin(BasePlugin):PLUGIN_ID = "mirumee.webhooks"PLUGIN_NAME = "Webhooks"DEFAULT_ACTIVE = TrueCONFIGURATION_PER_CHANNEL = False+ @classmethod+ def check_plugin_id(cls, plugin_id: str) -> bool:+ is_webhook_plugin = super().check_plugin_id(plugin_id)+ if not is_webhook_plugin:+ payment_app_data = from_payment_app_id(plugin_id)+ return payment_app_data is not None+ return is_webhook_plugin+def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)self.active = True@@ -214,3 +236,142 @@ class WebhookPlugin(BasePlugin):return previous_valuepage_data = generate_page_payload(page)trigger_webhooks_for_event.delay(WebhookEventType.PAGE_DELETED, page_data)++ def __run_payment_webhook(+ self,+ event_type: str,+ transaction_kind: str,+ payment_information: "PaymentData",+ previous_value,+ **kwargs+ ) -> "GatewayResponse":+ if not self.active:+ return previous_value++ app = None+ payment_app_data = from_payment_app_id(payment_information.gateway)++ if payment_app_data is not None:+ app = (+ App.objects.for_event_type(event_type)+ .filter(pk=payment_app_data.app_pk)+ .first()+ )++ if not app:+ logger.warning(+ "Payment webhook for event %r failed - no active app found: %r",+ event_type,+ payment_information.gateway,+ )+ raise PaymentError(+ f"Payment method {payment_information.gateway} is not available: "+ "app not found."+ )++ webhook_payload = generate_payment_payload(payment_information)+ response_data = trigger_webhook_sync(event_type, webhook_payload, app)+ if response_data is None:+ raise PaymentError(+ f"Payment method {payment_information.gateway} is not available: "+ "no response from the app."+ )++ return parse_payment_action_response(+ payment_information, response_data, transaction_kind+ )++ def token_is_required_as_payment_input(self, previous_value):+ return False++ def get_payment_gateways(+ self,+ currency: Optional[str],+ checkout: Optional["Checkout"],+ previous_value,+ **kwargs+ ) -> List["PaymentGateway"]:+ gateways = []+ apps = App.objects.for_event_type(+ WebhookEventType.PAYMENT_LIST_GATEWAYS+ ).prefetch_related("webhooks")+ for app in apps:+ response_data = trigger_webhook_sync(+ event_type=WebhookEventType.PAYMENT_LIST_GATEWAYS,+ data=generate_list_gateways_payload(currency, checkout),+ app=app,+ )+ if response_data:+ app_gateways = parse_list_payment_gateways_response(response_data, app)+ if currency:+ app_gateways = [+ gtw for gtw in app_gateways if currency in gtw.currencies+ ]+ gateways.extend(app_gateways)+ return gateways++ def authorize_payment(+ self, payment_information: "PaymentData", previous_value, **kwargs+ ) -> "GatewayResponse":+ return self.__run_payment_webhook(+ WebhookEventType.PAYMENT_AUTHORIZE,+ TransactionKind.AUTH,+ payment_information,+ previous_value,+ **kwargs,+ )++ def capture_payment(+ self, payment_information: "PaymentData", previous_value, **kwargs+ ) -> "GatewayResponse":+ return self.__run_payment_webhook(+ WebhookEventType.PAYMENT_CAPTURE,+ TransactionKind.CAPTURE,+ payment_information,+ previous_value,+ **kwargs,+ )++ def refund_payment(+ self, payment_information: "PaymentData", previous_value, **kwargs+ ) -> "GatewayResponse":+ return self.__run_payment_webhook(+ WebhookEventType.PAYMENT_REFUND,+ TransactionKind.REFUND,+ payment_information,+ previous_value,+ **kwargs,+ )++ def void_payment(+ self, payment_information: "PaymentData", previous_value, **kwargs+ ) -> "GatewayResponse":+ return self.__run_payment_webhook(+ WebhookEventType.PAYMENT_VOID,+ TransactionKind.VOID,+ payment_information,+ previous_value,+ **kwargs,+ )++ def confirm_payment(+ self, payment_information: "PaymentData", previous_value, **kwargs+ ) -> "GatewayResponse":+ return self.__run_payment_webhook(+ WebhookEventType.PAYMENT_CONFIRM,+ TransactionKind.CONFIRM,+ payment_information,+ previous_value,+ **kwargs,+ )++ def process_payment(+ self, payment_information: "PaymentData", previous_value, **kwargs+ ) -> "GatewayResponse":+ return self.__run_payment_webhook(+ WebhookEventType.PAYMENT_PROCESS,+ TransactionKind.CAPTURE,+ payment_information,+ previous_value,+ **kwargs,+ )diff --git a/saleor/plugins/webhook/tasks.py b/saleor/plugins/webhook/tasks.pyindex 52fb3bd3b4..6d192bd9c0 100644--- a/saleor/plugins/webhook/tasks.py+++ b/saleor/plugins/webhook/tasks.py@@ -1,5 +1,7 @@import loggingfrom enum import Enum+from json import JSONDecodeError+from typing import TYPE_CHECKINGfrom urllib.parse import urlparse, urlunparseimport boto3@@ -8,11 +10,15 @@ from google.cloud import pubsub_v1from requests.exceptions import RequestExceptionfrom ...celeryconf import app+from ...payment import PaymentErrorfrom ...site.models import Sitefrom ...webhook.event_types import WebhookEventTypefrom ...webhook.models import Webhookfrom . import signature_for_payload+if TYPE_CHECKING:+ from ...app.models import App+logger = logging.getLogger(__name__)WEBHOOK_TIMEOUT = 10@@ -25,16 +31,19 @@ class WebhookSchemes(str, Enum):GOOGLE_CLOUD_PUBSUB = "gcpubsub"-def trigger_webhooks_for_event(event_type, data):+def _get_webhooks_for_event(event_type, webhooks=None):+ """Get active webhooks from the database for an event."""permissions = {}- required_permission = WebhookEventType.PERMISSIONS[event_type].value+ required_permission = WebhookEventType.PERMISSIONS.get(event_type)if required_permission:- app_label, codename = required_permission.split(".")+ app_label, codename = required_permission.value.split(".")permissions["app__permissions__content_type__app_label"] = app_labelpermissions["app__permissions__codename"] = codename- webhooks = Webhook.objects.filter(+ if webhooks is None:+ webhooks = Webhook.objects.all()++ webhooks = webhooks.filter(is_active=True,app__is_active=True,events__event_type__in=[event_type, WebhookEventType.ANY],@@ -43,13 +52,31 @@ def trigger_webhooks_for_event(event_type, data):webhooks = webhooks.select_related("app").prefetch_related("app__permissions__content_type")+ return webhooks++def trigger_webhooks_for_event(event_type, data):+ """Send a webhook request for an event as an async task."""+ webhooks = _get_webhooks_for_event(event_type)for webhook in webhooks:send_webhook_request.delay(webhook.pk, webhook.target_url, webhook.secret_key, event_type, data)+def trigger_webhook_sync(event_type: str, data: str, app: "App"):+ """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}.")++ return send_webhook_request_sync(+ webhook.target_url, webhook.secret_key, event_type, data+ )++def send_webhook_using_http(target_url, message, domain, signature, event_type):headers = {"Content-Type": "application/json",@@ -62,6 +89,7 @@ def send_webhook_using_http(target_url, message, domain, signature, event_type):target_url, data=message, headers=headers, timeout=WEBHOOK_TIMEOUT)response.raise_for_status()+ return responsedef send_webhook_using_aws_sqs(target_url, message, domain, signature, event_type):@@ -139,3 +167,32 @@ def send_webhook_request(webhook_id, target_url, secret, event_type, data):target_url,event_type,)+++def send_webhook_request_sync(target_url, secret, event_type, data: str):+ parts = urlparse(target_url)+ domain = Site.objects.get_current().domain+ message = data.encode("utf-8")+ signature = signature_for_payload(message, secret)++ response_data = None+ if parts.scheme.lower() in [WebhookSchemes.HTTP, WebhookSchemes.HTTPS]:+ logger.debug(+ "[Webhook] Sending payload to %r for event %r.", target_url, event_type+ )+ try:+ response = send_webhook_using_http(+ target_url, message, domain, signature, event_type+ )+ response_data = response.json()+ except RequestException as e:+ logger.debug("[Webhook] Failed request to %r: %r.", target_url, e)+ except JSONDecodeError as e:+ logger.debug(+ "[Webhook] Failed parsing JSON response from %r: %r.", target_url, e+ )+ else:+ logger.debug("[Webhook] Success response from %r.", target_url)+ else:+ raise ValueError("Unknown webhook scheme: %r" % (parts.scheme,))+ return response_datadiff --git a/saleor/plugins/webhook/tests/test_payment_webhook.py b/saleor/plugins/webhook/tests/test_payment_webhook.pynew file mode 100644index 0000000000..ca063f0a86--- /dev/null+++ b/saleor/plugins/webhook/tests/test_payment_webhook.py@@ -0,0 +1,316 @@+import json+from unittest import mock++import pytest++from ....app.models import App+from ....payment import PaymentError, TransactionKind+from ....payment.utils import create_payment_information+from ....webhook.event_types import WebhookEventType+from ....webhook.models import Webhook, WebhookEvent+from ...manager import get_plugins_manager+from ..tasks import (+ send_webhook_request_sync,+ signature_for_payload,+ trigger_webhook_sync,+)+from ..utils import (+ parse_list_payment_gateways_response,+ parse_payment_action_response,+ to_payment_app_id,+)+++def payment(payment_dummy, payment_app):+ gateway_id = "credit-card"+ gateway = to_payment_app_id(payment_app, gateway_id)+ payment_dummy.gateway = gateway+ payment_dummy.save()+ return payment_dummy+++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)+ payment_dummy.gateway = gateway+ payment_dummy.save()+ return payment_dummy+++def webhook_plugin(settings):+ def factory():+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]+ manager = get_plugins_manager()+ return manager.global_plugins[0]++ return factory++[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")+def test_trigger_webhook_sync(mock_request, payment_app):+ data = {"key": "value"}+ trigger_webhook_sync(WebhookEventType.PAYMENT_CAPTURE, data, payment_app)+ webhook = payment_app.webhooks.first()+ mock_request.assert_called_once_with(+ webhook.target_url,+ webhook.secret_key,+ WebhookEventType.PAYMENT_CAPTURE,+ data,+ )++[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=WebhookEventType.PAYMENT_CAPTURE)++ data = {"key": "value"}+ trigger_webhook_sync(WebhookEventType.PAYMENT_CAPTURE, data, payment_app)+ mock_request.assert_called_once_with(+ webhook_1.target_url,+ webhook_1.secret_key,+ WebhookEventType.PAYMENT_CAPTURE,+ data,+ )+++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(WebhookEventType.PAYMENT_REFUND, {}, app)+++ "target_url",+ ("http://payment-gateway.com/api/", "https://payment-gateway.com/api/"),+)[email protected]("saleor.plugins.webhook.tasks.send_webhook_using_http")+def test_send_webhook_request_sync(mock_send_http, target_url, site_settings):+ secret = "secret"+ event_type = WebhookEventType.PAYMENT_CAPTURE+ data = json.dumps({"key": "value"})+ message = data.encode("utf-8")++ send_webhook_request_sync(target_url, secret, event_type, data)+ mock_send_http.assert_called_once_with(+ target_url,+ message,+ site_settings.site.domain,+ signature_for_payload(message, secret),+ event_type,+ )+++def test_send_webhook_request_sync_invalid_scheme():+ with pytest.raises(ValueError):+ target_url = "gcpubsub://cloud.google.com/projects/saleor/topics/test"+ send_webhook_request_sync(target_url, "", "", "")++[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")+def test_get_payment_gateways(+ mock_send_request, payment_app, permission_manage_payments, webhook_plugin+):+ # Create second app to test results from multiple apps.+ app_2 = App.objects.create(name="Payment App 2", is_active=True)+ app_2.tokens.create(name="Default")+ app_2.permissions.add(permission_manage_payments)+ webhook = Webhook.objects.create(+ name="payment-webhook-2",+ app=app_2,+ target_url="https://payment-gateway-2.com/api/",+ )+ webhook.events.bulk_create(+ [+ WebhookEvent(event_type=event_type, webhook=webhook)+ for event_type in WebhookEventType.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+ response_data = plugin.get_payment_gateways("USD", None, None)+ expected_response_1 = parse_list_payment_gateways_response(+ mock_json_response, payment_app+ )+ expected_response_2 = parse_list_payment_gateways_response(+ mock_json_response, app_2+ )+ 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_filters_out_unsupported_currencies(+ mock_send_request, payment_app, webhook_plugin+):+ plugin = webhook_plugin()+ mock_json_response = [+ {+ "id": "credit-card",+ "name": "Credit Card",+ "currencies": ["USD", "EUR"],+ "config": [],+ }+ ]+ mock_send_request.return_value = mock_json_response+ response_data = plugin.get_payment_gateways("PLN", None, None)+ assert response_data == []++[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")[email protected]("saleor.plugins.webhook.plugin.generate_list_gateways_payload")+def test_get_payment_gateways_for_checkout(+ mock_generate_payload, mock_send_request, checkout, payment_app, webhook_plugin+):+ plugin = webhook_plugin()+ mock_json_response = [+ {+ "id": "credit-card",+ "name": "Credit Card",+ "currencies": ["USD", "EUR"],+ "config": [],+ }+ ]+ mock_send_request.return_value = mock_json_response+ mock_generate_payload.return_value = ""+ plugin.get_payment_gateways("USD", checkout, None)+ assert mock_generate_payload.call_args[0][1] == checkout+++ "txn_kind, plugin_func_name",+ (+ (TransactionKind.AUTH, "authorize_payment"),+ (TransactionKind.CAPTURE, "capture_payment"),+ (TransactionKind.REFUND, "refund_payment"),+ (TransactionKind.VOID, "void_payment"),+ (TransactionKind.CONFIRM, "confirm_payment"),+ (TransactionKind.CAPTURE, "process_payment"),+ ),+)[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")+def test_run_payment_webhook(+ mock_send_request,+ txn_kind,+ plugin_func_name,+ payment,+ payment_app,+ webhook_plugin,+):+ plugin = webhook_plugin()+ payment_information = create_payment_information(payment, "token")+ payment_func = getattr(plugin, plugin_func_name)++ mock_json_response = {"transaction_id": f"fake-id-{txn_kind}"}+ mock_send_request.return_value = mock_json_response+ response_data = payment_func(payment_information, None)++ expected_response = parse_payment_action_response(+ payment_information, mock_json_response, txn_kind+ )+ assert response_data == expected_response+++def test_run_payment_webhook_invalid_app(payment_invalid_app, webhook_plugin):+ plugin = webhook_plugin()+ payment_information = create_payment_information(payment_invalid_app, "token")+ with pytest.raises(PaymentError):+ plugin._WebhookPlugin__run_payment_webhook(+ WebhookEventType.PAYMENT_AUTHORIZE,+ TransactionKind.AUTH,+ payment_information,+ None,+ )+++def test_run_payment_webhook_no_payment_app_data(payment, webhook_plugin):+ plugin = webhook_plugin()+ payment_information = create_payment_information(payment, "token")+ payment_information.gateway = "dummy"+ with pytest.raises(PaymentError):+ plugin._WebhookPlugin__run_payment_webhook(+ WebhookEventType.PAYMENT_AUTHORIZE,+ TransactionKind.AUTH,+ payment_information,+ None,+ )+++def test_run_payment_webhook_inactive_plugin(payment, webhook_plugin):+ plugin = webhook_plugin()+ plugin.active = False+ payment_information = create_payment_information(payment, "token")+ dummy_previous_value = {"key": "dummy"}+ response = plugin._WebhookPlugin__run_payment_webhook(+ WebhookEventType.PAYMENT_AUTHORIZE,+ TransactionKind.AUTH,+ payment_information,+ dummy_previous_value,+ )+ assert response == dummy_previous_value++[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")+def test_run_payment_webhook_no_response(mock_send_request, payment, webhook_plugin):+ # Should raise and error when response data is None.+ mock_send_request.return_value = None+ plugin = webhook_plugin()+ payment_information = create_payment_information(payment, "token")+ with pytest.raises(PaymentError):+ plugin._WebhookPlugin__run_payment_webhook(+ WebhookEventType.PAYMENT_AUTHORIZE,+ TransactionKind.AUTH,+ payment_information,+ {},+ )++[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")+def test_run_payment_webhook_empty_response(mock_send_request, payment, webhook_plugin):+ # Empty JSON response "{}"" is accepted; check that it doesn't fail.+ mock_send_request.return_value = {}+ plugin = webhook_plugin()+ payment_information = create_payment_information(payment, "token")+ response = plugin._WebhookPlugin__run_payment_webhook(+ WebhookEventType.PAYMENT_AUTHORIZE,+ TransactionKind.AUTH,+ payment_information,+ {},+ )+ assert response+ assert response.is_success+++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")+ assert plugin.check_plugin_id(valid_id)+++def test_webhook_plugin_token_is_not_required(webhook_plugin):+ plugin = webhook_plugin()+ assert not plugin.token_is_required_as_payment_input(None)diff --git a/saleor/plugins/webhook/tests/test_payment_webhook_utils.py b/saleor/plugins/webhook/tests/test_payment_webhook_utils.pynew file mode 100644index 0000000000..9d5e121bf2--- /dev/null+++ b/saleor/plugins/webhook/tests/test_payment_webhook_utils.py@@ -0,0 +1,162 @@+import pytest++from ....payment import TransactionKind+from ..utils import (+ APP_GATEWAY_ID_PREFIX,+ from_payment_app_id,+ parse_list_payment_gateways_response,+ parse_payment_action_response,+ to_payment_app_id,+)+++def test_to_payment_app_id(app):+ gateway_id = "example-gateway"+ payment_app_id = to_payment_app_id(app, gateway_id)+ assert payment_app_id == f"{APP_GATEWAY_ID_PREFIX}:{app.pk}:{gateway_id}"+++def test_from_payment_app_id():+ app_id = "app:1:credit-card"+ payment_app_data = from_payment_app_id(app_id)+ assert payment_app_data.app_pk == 1+ assert payment_app_data.name == "credit-card"+++ "app_id",+ [+ "",+ "::",+ "1",+ "name",+ "1:1:name",+ f"{APP_GATEWAY_ID_PREFIX}:1",+ f"{APP_GATEWAY_ID_PREFIX}:1:",+ f"{APP_GATEWAY_ID_PREFIX}:1a:name",+ ],+)+def test_from_payment_app_id_invalid(app_id):+ app_pk = from_payment_app_id(app_id)+ assert app_pk is None+++def test_parse_list_payment_gateways_response(app):+ response_data = [+ {+ "id": "credit-card",+ "name": "Credit Card",+ "currencies": ["USD", "EUR"],+ "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"])+ assert gateways[0].name == response_data[0]["name"]+ assert gateways[0].currencies == response_data[0]["currencies"]+ assert gateways[0].config == response_data[0]["config"]+++def test_parse_list_payment_gateways_response_no_id(app):+ response_data = [+ {+ "name": "Credit Card",+ "currencies": ["USD", "EUR"],+ },+ ]+ gateways = parse_list_payment_gateways_response(response_data, app)+ assert gateways == []+++def payment_action_response(dummy_webhook_app_payment_data):+ return {+ "action_required": False,+ "action_required_data": {},+ "amount": dummy_webhook_app_payment_data.amount,+ "currency": dummy_webhook_app_payment_data.currency,+ "customer_id": "1000",+ "kind": TransactionKind.AUTH,+ "payment_method": {+ "brand": "Visa",+ "exp_month": "05",+ "exp_year": "2025",+ "last_4": "4444",+ "name": "John Doe",+ "type": "card",+ },+ "psp_reference": "1000",+ "transaction_id": "1000",+ "transaction_already_processed": False,+ }+++def test_parse_payment_action_response(+ dummy_webhook_app_payment_data, payment_action_response+):+ gateway_response = parse_payment_action_response(+ dummy_webhook_app_payment_data, payment_action_response, TransactionKind.AUTH+ )+ assert gateway_response.error is None+ assert gateway_response.is_success+ assert gateway_response.raw_response == payment_action_response+ assert (+ gateway_response.action_required == payment_action_response["action_required"]+ )+ assert (+ gateway_response.action_required_data+ == payment_action_response["action_required_data"]+ )+ assert gateway_response.amount == payment_action_response["amount"]+ assert gateway_response.currency == payment_action_response["currency"]+ assert gateway_response.customer_id == payment_action_response["customer_id"]+ assert gateway_response.kind == payment_action_response["kind"]+ assert gateway_response.psp_reference == payment_action_response["psp_reference"]+ assert gateway_response.transaction_id == payment_action_response["transaction_id"]+ assert (+ gateway_response.transaction_already_processed+ == payment_action_response["transaction_already_processed"]+ )++ assert (+ gateway_response.payment_method_info.brand+ == payment_action_response["payment_method"]["brand"]+ )+ assert (+ gateway_response.payment_method_info.exp_month+ == payment_action_response["payment_method"]["exp_month"]+ )+ assert (+ gateway_response.payment_method_info.exp_year+ == payment_action_response["payment_method"]["exp_year"]+ )+ assert (+ gateway_response.payment_method_info.last_4+ == payment_action_response["payment_method"]["last_4"]+ )+ assert (+ gateway_response.payment_method_info.name+ == payment_action_response["payment_method"]["name"]+ )+ assert (+ gateway_response.payment_method_info.type+ == payment_action_response["payment_method"]["type"]+ )+++def test_parse_payment_action_response_parse_amount(+ dummy_webhook_app_payment_data, payment_action_response+):+ # test amount is not a decimal, should use amount from payment information+ payment_action_response["amount"] = "boom"+ gateway_response = parse_payment_action_response(+ dummy_webhook_app_payment_data, payment_action_response, TransactionKind.AUTH+ )+ assert gateway_response.amount == dummy_webhook_app_payment_data.amount++ # test amount not in webhook response, should use amount from payment information+ del payment_action_response["amount"]+ gateway_response = parse_payment_action_response(+ dummy_webhook_app_payment_data, payment_action_response, TransactionKind.AUTH+ )+ assert gateway_response.amount == dummy_webhook_app_payment_data.amountdiff --git a/saleor/plugins/webhook/utils.py b/saleor/plugins/webhook/utils.pynew file mode 100644index 0000000000..c021574a0a--- /dev/null+++ b/saleor/plugins/webhook/utils.py@@ -0,0 +1,106 @@+import decimal+from dataclasses import dataclass+from typing import TYPE_CHECKING, Any, List, Optional++from ...payment.interface import GatewayResponse, PaymentGateway, PaymentMethodInfo++if TYPE_CHECKING:+ from ...app.models import App+ from ...payment.interface import PaymentData+++APP_GATEWAY_ID_PREFIX = "app"+++@dataclass+class PaymentAppData:+ app_pk: int+ name: str+++def to_payment_app_id(app: "App", gateway_id: str) -> "str":+ return f"{APP_GATEWAY_ID_PREFIX}:{app.pk}:{gateway_id}"+++def from_payment_app_id(app_gateway_id: str) -> Optional["PaymentAppData"]:+ splitted_id = app_gateway_id.split(":")+ if (+ len(splitted_id) == 3+ and splitted_id[0] == APP_GATEWAY_ID_PREFIX+ and all(splitted_id)+ ):+ try:+ app_pk = int(splitted_id[1])+ except (TypeError, ValueError):+ return None+ else:+ return PaymentAppData(app_pk, name=splitted_id[2])+ return None+++def parse_list_payment_gateways_response(+ response_data: Any, app: "App"+) -> List["PaymentGateway"]:+ gateways = []+ for gateway_data in response_data:+ gateway_id = gateway_data.get("id")+ gateway_name = gateway_data.get("name")+ gateway_currencies = gateway_data.get("currencies")+ gateway_config = gateway_data.get("config")++ if gateway_id:+ gateways.append(+ PaymentGateway(+ id=to_payment_app_id(app, gateway_id),+ name=gateway_name,+ currencies=gateway_currencies,+ config=gateway_config,+ )+ )+ return gateways+++def parse_payment_action_response(+ payment_information: "PaymentData",+ response_data: Any,+ transaction_kind: "str",+) -> "GatewayResponse":+ error = response_data.get("error")+ is_success = not error++ payment_method_info = None+ payment_method_data = response_data.get("payment_method")+ if payment_method_data:+ payment_method_info = PaymentMethodInfo(+ brand=payment_method_data.get("brand"),+ exp_month=payment_method_data.get("exp_month"),+ exp_year=payment_method_data.get("exp_year"),+ last_4=payment_method_data.get("last_4"),+ name=payment_method_data.get("name"),+ type=payment_method_data.get("type"),+ )++ amount = payment_information.amount+ if "amount" in response_data:+ try:+ amount = decimal.Decimal(response_data["amount"])+ except decimal.DecimalException:+ pass++ return GatewayResponse(+ action_required=response_data.get("action_required", False),+ action_required_data=response_data.get("action_required_data"),+ amount=amount,+ currency=payment_information.currency,+ customer_id=response_data.get("customer_id"),+ error=error,+ is_success=is_success,+ kind=response_data.get("kind", transaction_kind),+ payment_method_info=payment_method_info,+ raw_response=response_data,+ psp_reference=response_data.get("psp_reference"),+ transaction_id=response_data.get("transaction_id", ""),+ transaction_already_processed=response_data.get(+ "transaction_already_processed", False+ ),+ )diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex f7e0cfee61..236c2d6ef5 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -73,6 +73,7 @@ from ..payment.models import Paymentfrom ..plugins.manager import get_plugins_managerfrom ..plugins.models import PluginConfigurationfrom ..plugins.vatlayer.plugin import VatlayerPlugin+from ..plugins.webhook.utils import to_payment_app_idfrom ..product import ProductMediaTypesfrom ..product.models import (Category,@@ -103,7 +104,7 @@ from ..shipping.models import (from ..site.models import SiteSettingsfrom ..warehouse.models import Allocation, Stock, Warehousefrom ..webhook.event_types import WebhookEventType-from ..webhook.models import Webhook+from ..webhook.models import Webhook, WebhookEventfrom ..wishlist.models import Wishlistfrom .utils import dummy_editorjs@@ -2892,6 +2893,7 @@ def dummy_gateway_config():@pytest.fixturedef dummy_payment_data(payment_dummy):return PaymentData(+ gateway=payment_dummy.gateway,amount=Decimal(10),currency="USD",graphql_payment_id=graphene.Node.to_global_id("Payment", payment_dummy.pk),@@ -2904,6 +2906,12 @@ def dummy_payment_data(payment_dummy):)+def dummy_webhook_app_payment_data(dummy_payment_data, payment_app):+ dummy_payment_data.gateway = to_payment_app_id(payment_app, "credit-card")+ return dummy_payment_data++@pytest.fixturedef new_sale(category, channel_USD):sale = Sale.objects.create(name="Sale")@@ -3025,6 +3033,11 @@ def permission_manage_channels():return Permission.objects.get(codename="manage_channels")+def permission_manage_payments():+ return Permission.objects.get(codename="handle_payments")++@pytest.fixturedef permission_group_manage_users(permission_manage_users, staff_users):group = Group.objects.create(name="Manage user groups.")@@ -3635,6 +3648,26 @@ def app(db):return app+def payment_app(db, permission_manage_payments):+ app = App.objects.create(name="Payment App", is_active=True)+ app.tokens.create(name="Default")+ app.permissions.add(permission_manage_payments)++ webhook = Webhook.objects.create(+ name="payment-webhook-1",+ app=app,+ target_url="https://payment-gateway.com/api/",+ )+ webhook.events.bulk_create(+ [+ WebhookEvent(event_type=event_type, webhook=webhook)+ for event_type in WebhookEventType.PAYMENT_EVENTS+ ]+ )+ return app++@pytest.fixturedef external_app(db):app = App.objects.create(diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.pyindex 784635eff0..e2bf9ac1dc 100644--- a/saleor/webhook/event_types.py+++ b/saleor/webhook/event_types.py@@ -3,6 +3,7 @@ from ..core.permissions import (CheckoutPermissions,OrderPermissions,PagePermissions,+ PaymentPermissions,ProductPermissions,)@@ -42,6 +43,14 @@ class WebhookEventType:PAGE_UPDATED = "page_updated"PAGE_DELETED = "page_deleted"+ PAYMENT_LIST_GATEWAYS = "payment_list_gateways"+ PAYMENT_AUTHORIZE = "payment_authorize"+ PAYMENT_CAPTURE = "payment_capture"+ PAYMENT_REFUND = "payment_refund"+ PAYMENT_VOID = "payment_void"+ PAYMENT_CONFIRM = "payment_confirm"+ PAYMENT_PROCESS = "payment_process"+DISPLAY_LABELS = {ANY: "Any events",ORDER_CREATED: "Order created",@@ -68,6 +77,13 @@ class WebhookEventType:PAGE_CREATED: "Page Created",PAGE_UPDATED: "Page Updated",PAGE_DELETED: "Page Deleted",+ PAYMENT_AUTHORIZE: "Authorize payment",+ PAYMENT_CAPTURE: "Capture payment",+ PAYMENT_CONFIRM: "Confirm payment",+ PAYMENT_LIST_GATEWAYS: "List payment gateways",+ PAYMENT_PROCESS: "Process payment",+ PAYMENT_REFUND: "Refund payment",+ PAYMENT_VOID: "Void payment",}CHOICES = [@@ -96,6 +112,23 @@ class WebhookEventType:(PAGE_CREATED, DISPLAY_LABELS[PAGE_CREATED]),(PAGE_UPDATED, DISPLAY_LABELS[PAGE_UPDATED]),(PAGE_DELETED, DISPLAY_LABELS[PAGE_DELETED]),+ (PAYMENT_AUTHORIZE, DISPLAY_LABELS[PAYMENT_AUTHORIZE]),+ (PAYMENT_CAPTURE, DISPLAY_LABELS[PAYMENT_CAPTURE]),+ (PAYMENT_CONFIRM, DISPLAY_LABELS[PAYMENT_CONFIRM]),+ (PAYMENT_LIST_GATEWAYS, DISPLAY_LABELS[PAYMENT_LIST_GATEWAYS]),+ (PAYMENT_PROCESS, DISPLAY_LABELS[PAYMENT_PROCESS]),+ (PAYMENT_REFUND, DISPLAY_LABELS[PAYMENT_REFUND]),+ (PAYMENT_VOID, DISPLAY_LABELS[PAYMENT_VOID]),+ ]++ PAYMENT_EVENTS = [+ PAYMENT_AUTHORIZE,+ PAYMENT_CAPTURE,+ PAYMENT_CONFIRM,+ PAYMENT_LIST_GATEWAYS,+ PAYMENT_PROCESS,+ PAYMENT_REFUND,+ PAYMENT_VOID,]PERMISSIONS = {@@ -123,4 +156,11 @@ class WebhookEventType:PAGE_CREATED: PagePermissions.MANAGE_PAGES,PAGE_UPDATED: PagePermissions.MANAGE_PAGES,PAGE_DELETED: PagePermissions.MANAGE_PAGES,+ PAYMENT_AUTHORIZE: PaymentPermissions.HANDLE_PAYMENTS,+ PAYMENT_CAPTURE: PaymentPermissions.HANDLE_PAYMENTS,+ PAYMENT_CONFIRM: PaymentPermissions.HANDLE_PAYMENTS,+ PAYMENT_LIST_GATEWAYS: PaymentPermissions.HANDLE_PAYMENTS,+ PAYMENT_PROCESS: PaymentPermissions.HANDLE_PAYMENTS,+ PAYMENT_REFUND: PaymentPermissions.HANDLE_PAYMENTS,+ PAYMENT_VOID: PaymentPermissions.HANDLE_PAYMENTS,}diff --git a/saleor/webhook/migrations/0007_auto_20210319_0945.py b/saleor/webhook/migrations/0007_auto_20210319_0945.pynew file mode 100644index 0000000000..48988dd569--- /dev/null+++ b/saleor/webhook/migrations/0007_auto_20210319_0945.py@@ -0,0 +1,17 @@+# Generated by Django 3.1.7 on 2021-03-19 09:45++from django.db import migrations+++class Migration(migrations.Migration):++ dependencies = [+ ("webhook", "0006_auto_20200731_1440"),+ ]++ operations = [+ migrations.AlterModelOptions(+ name="webhook",+ options={"ordering": ("pk",)},+ ),+ ]diff --git a/saleor/webhook/models.py b/saleor/webhook/models.pyindex b328442cef..56fbc2f70d 100644--- a/saleor/webhook/models.py+++ b/saleor/webhook/models.py@@ -17,6 +17,12 @@ class Webhook(models.Model):is_active = models.BooleanField(default=True)secret_key = models.CharField(max_length=255, null=True, blank=True)+ class Meta:+ ordering = ("pk",)++ def __str__(self):+ return self.name+class WebhookEvent(models.Model):webhook = models.ForeignKey(diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.pyindex f7bc5381ec..90d46b9b2c 100644--- a/saleor/webhook/payloads.py+++ b/saleor/webhook/payloads.py@@ -1,11 +1,11 @@import jsonimport uuid+from dataclasses import asdictfrom typing import TYPE_CHECKING, Iterable, Optionalimport graphenefrom django.db.models import F, QuerySet-from ..account.models import Userfrom ..checkout.models import Checkoutfrom ..core.utils import build_absolute_urifrom ..core.utils.anonymization import (@@ -13,12 +13,13 @@ from ..core.utils.anonymization import (anonymize_order,generate_fake_user,)-from ..invoice.models import Invoice+from ..core.utils.json_serializer import CustomJsonEncoderfrom ..order import FulfillmentStatus, OrderStatusfrom ..order.models import Fulfillment, FulfillmentLine, Order, OrderLinefrom ..order.utils import get_order_countryfrom ..page.models import Pagefrom ..payment import ChargeStatus+from ..plugins.webhook.utils import from_payment_app_idfrom ..product import ProductMediaTypesfrom ..product.models import Productfrom ..warehouse.models import Warehouse@@ -34,6 +35,12 @@ if TYPE_CHECKING:from ..product.models import ProductVariant+if TYPE_CHECKING:+ from ..account.models import User+ from ..invoice.models import Invoice+ from ..payment.interface import PaymentData++ADDRESS_FIELDS = ("first_name","last_name",@@ -498,6 +505,27 @@ def generate_page_payload(page: Page):return page_payload+def generate_payment_payload(payment_data: "PaymentData"):+ data = asdict(payment_data)+ payment_app_data = from_payment_app_id(data["gateway"])+ if payment_app_data:+ data["payment_method"] = payment_app_data.name+ return json.dumps(data, cls=CustomJsonEncoder)+++def generate_list_gateways_payload(+ currency: Optional[str], checkout: Optional["Checkout"]+):+ if checkout:+ # Deserialize checkout payload to dict and generate a new payload including+ # currency.+ checkout_data = json.loads(generate_checkout_payload(checkout))[0]+ else:+ checkout_data = None+ payload = {"checkout": checkout_data, "currency": currency}+ return json.dumps(payload)++def _get_sample_object(qs: QuerySet):"""Return random object from query."""random_object = qs.order_by("?").first()diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.pyindex 2b5593bae4..55bbfba6fe 100644--- a/saleor/webhook/tests/test_webhook_payloads.py+++ b/saleor/webhook/tests/test_webhook_payloads.py@@ -1,4 +1,5 @@import json+from dataclasses import asdictfrom decimal import Decimalfrom itertools import chainfrom unittest import mock@@ -6,17 +7,22 @@ from unittest.mock import ANYimport graphene+from ...core.utils.json_serializer import CustomJsonEncoderfrom ...discount import DiscountValueType, OrderDiscountTypefrom ...order import OrderLineData, OrderOriginfrom ...order.actions import fulfill_order_linesfrom ...order.models import Order+from ...plugins.webhook.utils import from_payment_app_idfrom ...product.models import ProductVariantfrom ..payloads import (ORDER_FIELDS,PRODUCT_VARIANT_FIELDS,+ generate_checkout_payload,generate_fulfillment_lines_payload,generate_invoice_payload,+ generate_list_gateways_payload,generate_order_payload,+ generate_payment_payload,generate_product_variant_payload,)@@ -349,3 +355,20 @@ def test_generate_invoice_payload(fulfilled_order):"created": ANY,"external_url": "http://www.example.com/invoice.pdf",}+++def test_generate_list_gateways_payload(checkout):+ currency = "USD"+ payload = generate_list_gateways_payload(currency, checkout)+ data = json.loads(payload)+ assert data["checkout"] == json.loads(generate_checkout_payload(checkout))[0]+ assert data["currency"] == currency+++def test_generate_payment_payload(dummy_webhook_app_payment_data):+ payload = generate_payment_payload(dummy_webhook_app_payment_data)+ expected_payload = asdict(dummy_webhook_app_payment_data)+ expected_payload["payment_method"] = from_payment_app_id(+ dummy_webhook_app_payment_data.gateway+ ).name+ assert payload == json.dumps(expected_payload, cls=CustomJsonEncoder)