Skip to content

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

Fix adyen notifications handling (#6343)

Iga Karbowiaka6600473eadf
diff --git a/saleor/payment/gateways/adyen/tests/webhooks/test_get_payment.py b/saleor/payment/gateways/adyen/tests/webhooks/test_get_payment.py
new file mode 100644
index 0000000000..da3ef80275
--- /dev/null
+++ b/saleor/payment/gateways/adyen/tests/webhooks/test_get_payment.py
@@ -0,0 +1,51 @@
+import logging
+
+import graphene
+import pytest
+
+from ...webhooks import get_payment
+
+logger = logging.getLogger(__name__)
+
+
[email protected]("payment_id", ["123", "Test payment ID"])
+def test_get_payment_invalid_payment_id(payment_id, caplog):
+ # given
+ caplog.set_level(logging.WARNING)
+
+ # when
+ result = get_payment(payment_id)
+
+ # then
+ assert result is None
+ assert f"Unable to decode the payment ID {payment_id}." in caplog.text
+
+
[email protected]("payment_id", [" ", None])
+def test_get_payment_missing_payment_id(payment_id, caplog):
+ # given
+ caplog.set_level(logging.WARNING)
+
+ # when
+ result = get_payment(payment_id)
+
+ # then
+ assert result is None
+ assert "Missing payment ID." in caplog.text
+
+
+def test_get_payment_not_active_payment(payment_dummy, caplog):
+ # given
+ caplog.set_level(logging.WARNING)
+
+ payment_dummy.is_active = False
+ payment_dummy.save(update_fields=["is_active"])
+
+ payment_id = graphene.Node.to_global_id("Payemnt", payment_dummy.pk)
+
+ # when
+ result = get_payment(payment_id)
+
+ # then
+ assert not result
+ assert f"Payment for {payment_id} was not found." in caplog.text
diff --git a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py b/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py
index 38135a2dd0..c7a41ee0ec 100644
--- a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py
+++ b/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py
@@ -1,3 +1,4 @@
+import logging
from decimal import Decimal
from unittest import mock
@@ -22,6 +23,8 @@ from ...webhooks import (
webhook_not_implemented,
)
+logger = logging.getLogger(__name__)
+
def test_handle_authorization_for_order(
notification, adyen_plugin, payment_adyen_for_order
@@ -45,6 +48,27 @@ def test_handle_authorization_for_order(
assert external_events.count() == 1
+def test_handle_authorization_for_order_invalid_payment_id(
+ notification, adyen_plugin, payment_adyen_for_order, caplog
+):
+ payment = payment_adyen_for_order
+ invalid_reference = "test invalid reference"
+ notification = notification(
+ merchant_reference=invalid_reference,
+ value=to_adyen_price(payment.total, payment.currency),
+ )
+ config = adyen_plugin().config
+ transaction_count = payment.transactions.count()
+
+ caplog.set_level(logging.WARNING)
+
+ handle_authorization(notification, config)
+
+ payment.refresh_from_db()
+ assert payment.transactions.count() == transaction_count
+ assert f"Unable to decode the payment ID {invalid_reference}." in caplog.text
+
+
def test_handle_multiple_authorization_notification(
notification, adyen_plugin, payment_adyen_for_order
):
@@ -272,6 +296,31 @@ def test_handle_cancel(notification, adyen_plugin, payment_adyen_for_order):
assert external_events.count() == 1
+def test_handle_cancel_invalid_payment_id(
+ notification, adyen_plugin, payment_adyen_for_order, caplog
+):
+ payment = payment_adyen_for_order
+ payment.charge_status = ChargeStatus.FULLY_CHARGED
+ invalid_reference = "test invalid reference"
+ notification = notification(
+ merchant_reference=invalid_reference,
+ value=to_adyen_price(payment.total, payment.currency),
+ )
+ config = adyen_plugin().config
+ transaction_count = payment.transactions.count()
+
+ caplog.set_level(logging.WARNING)
+
+ handle_cancellation(notification, config)
+
+ payment.order.refresh_from_db()
+ assert payment.transactions.count() == transaction_count
+
+ payment.refresh_from_db()
+ assert payment.transactions.count() == transaction_count
+ assert f"Unable to decode the payment ID {invalid_reference}." in caplog.text
+
+
def test_handle_cancel_already_canceled(
notification, adyen_plugin, payment_adyen_for_order
):
@@ -354,6 +403,27 @@ def test_handle_capture_for_checkout(
assert external_events.count() == 1
+def test_handle_capture_invalid_payment_id(
+ notification, adyen_plugin, payment_adyen_for_order, caplog
+):
+ payment = payment_adyen_for_order
+ invalid_reference = "test invalid reference"
+ notification = notification(
+ merchant_reference=invalid_reference,
+ value=to_adyen_price(payment.total, payment.currency),
+ )
+ config = adyen_plugin().config
+ transaction_count = payment.transactions.count()
+
+ caplog.set_level(logging.WARNING)
+
+ handle_capture(notification, config)
+
+ payment.refresh_from_db()
+ assert payment.transactions.count() == transaction_count
+ assert f"Unable to decode the payment ID {invalid_reference}." in caplog.text
+
+
def test_handle_capture_with_payment_already_charged(
notification, adyen_plugin, payment_adyen_for_order
):
@@ -409,6 +479,30 @@ def test_handle_failed_capture(
assert external_events.count() == 1
+def test_handle_failed_capture_invalid_payment_id(
+ notification, adyen_plugin, payment_adyen_for_order, caplog
+):
+ payment = payment_adyen_for_order
+ payment.charge_status = ChargeStatus.FULLY_CHARGED
+ payment.captured_amount = payment.total
+ payment.save()
+ invalid_reference = "test invalid reference"
+ notification = notification(
+ merchant_reference=invalid_reference,
+ value=to_adyen_price(payment.total, payment.currency),
+ )
+ config = adyen_plugin().config
+ transaction_count = payment.transactions.count()
+
+ caplog.set_level(logging.WARNING)
+
+ handle_failed_capture(notification, config)
+
+ payment.refresh_from_db()
+ assert payment.transactions.count() == transaction_count
+ assert f"Unable to decode the payment ID {invalid_reference}." in caplog.text
+
+
def test_handle_failed_capture_partial_charge(
notification, adyen_plugin, payment_adyen_for_order
):
@@ -458,6 +552,27 @@ def test_handle_pending(notification, adyen_plugin, payment_adyen_for_order):
assert external_events.count() == 1
+def test_handle_pending_invalid_payment_id(
+ notification, adyen_plugin, payment_adyen_for_order, caplog
+):
+ payment = payment_adyen_for_order
+ invalid_reference = "test invalid reference"
+ notification = notification(
+ merchant_reference=invalid_reference,
+ value=to_adyen_price(payment.total, payment.currency),
+ )
+ config = adyen_plugin().config
+ transaction_count = payment.transactions.count()
+
+ caplog.set_level(logging.WARNING)
+
+ handle_pending(notification, config)
+
+ payment.refresh_from_db()
+ assert payment.transactions.count() == transaction_count
+ assert f"Unable to decode the payment ID {invalid_reference}." in caplog.text
+
+
def test_handle_pending_with_adyen_auto_capture(
notification, adyen_plugin, payment_adyen_for_order
):
@@ -535,6 +650,30 @@ def test_handle_refund(
assert external_events.count() == 1
+def test_handle_refund_invalid_payment_id(
+ notification, adyen_plugin, payment_adyen_for_order, caplog
+):
+ payment = payment_adyen_for_order
+ payment.charge_status = ChargeStatus.FULLY_CHARGED
+ payment.captured_amount = payment.total
+ payment.save()
+ invalid_reference = "test invalid reference"
+ notification = notification(
+ merchant_reference=invalid_reference,
+ value=to_adyen_price(payment.total, payment.currency),
+ )
+ config = adyen_plugin().config
+ transaction_count = payment.transactions.count()
+
+ caplog.set_level(logging.WARNING)
+
+ handle_refund(notification, config)
+
+ payment.refresh_from_db()
+ assert payment.transactions.count() == transaction_count
+ assert f"Unable to decode the payment ID {invalid_reference}." in caplog.text
+
+
@mock.patch("saleor.payment.gateways.adyen.webhooks.order_refunded")
def test_handle_refund_already_refunded(
mock_order_refunded, notification, adyen_plugin, payment_adyen_for_order
@@ -580,6 +719,30 @@ def test_handle_failed_refund_missing_transaction(
assert external_events.count() == 1
+def test_handle_failed_refund_invalid_payment_id(
+ notification, adyen_plugin, payment_adyen_for_order, caplog
+):
+ payment = payment_adyen_for_order
+ payment.charge_status = ChargeStatus.FULLY_CHARGED
+ payment.captured_amount = payment.total
+ payment.save()
+ invalid_reference = "test invalid reference"
+ notification = notification(
+ merchant_reference=invalid_reference,
+ value=to_adyen_price(payment.total, payment.currency),
+ )
+ config = adyen_plugin().config
+ transaction_count = payment.transactions.count()
+
+ caplog.set_level(logging.WARNING)
+
+ handle_failed_refund(notification, config)
+
+ payment.refresh_from_db()
+ assert payment.transactions.count() == transaction_count
+ assert f"Unable to decode the payment ID {invalid_reference}." in caplog.text
+
+
def test_handle_failed_refund_with_transaction_refund_ongoing(
notification, adyen_plugin, payment_adyen_for_order
):
@@ -655,6 +818,30 @@ def test_handle_reversed_refund(notification, adyen_plugin, payment_adyen_for_or
assert external_events.count() == 1
+def test_handle_reversed_refund_invalid_payment_id(
+ notification, adyen_plugin, payment_adyen_for_order, caplog
+):
+ payment = payment_adyen_for_order
+ payment.charge_status = ChargeStatus.FULLY_REFUNDED
+ payment.captured_amount = Decimal("0.0")
+ payment.save()
+ invalid_reference = "test invalid reference"
+ notification = notification(
+ merchant_reference=invalid_reference,
+ value=to_adyen_price(payment.total, payment.currency),
+ )
+ config = adyen_plugin().config
+ transaction_count = payment.transactions.count()
+
+ caplog.set_level(logging.WARNING)
+
+ handle_reversed_refund(notification, config)
+
+ payment.refresh_from_db()
+ assert payment.transactions.count() == transaction_count
+ assert f"Unable to decode the payment ID {invalid_reference}." in caplog.text
+
+
def test_handle_reversed_refund_already_processed(
notification, adyen_plugin, payment_adyen_for_order
):
@@ -694,6 +881,30 @@ def test_webhook_not_implemented(notification, adyen_plugin, payment_adyen_for_o
assert external_events.count() == 1
+def test_webhook_not_implemented_invalid_payment_id(
+ notification, adyen_plugin, payment_adyen_for_order, caplog
+):
+ payment = payment_adyen_for_order
+ payment.charge_status = ChargeStatus.FULLY_CHARGED
+ payment.captured_amount = payment.total
+ payment.save()
+ invalid_reference = "test invalid reference"
+ notification = notification(
+ merchant_reference=invalid_reference,
+ value=to_adyen_price(payment.total, payment.currency),
+ )
+ config = adyen_plugin().config
+ transaction_count = payment.transactions.count()
+
+ caplog.set_level(logging.WARNING)
+
+ webhook_not_implemented(notification, config)
+
+ payment.refresh_from_db()
+ assert payment.transactions.count() == transaction_count
+ assert f"Unable to decode the payment ID {invalid_reference}." in caplog.text
+
+
@mock.patch("saleor.payment.gateways.adyen.webhooks.handle_refund")
def test_handle_cancel_or_refund_action_refund(
mock_handle_refund, notification, adyen_plugin, payment_adyen_for_order
@@ -729,3 +940,22 @@ def test_handle_cancel_or_refund_action_cancel(
handle_cancel_or_refund(notification, config)
mock_handle_cancellation.assert_called_once_with(notification, config)
+
+
+def test_handle_cancel_or_refund_action_cancel_invalid_payment_id(
+ notification, adyen_plugin, payment_adyen_for_order, caplog
+):
+ payment = payment_adyen_for_order
+ config = adyen_plugin().config
+ invalid_reference = "test invalid reference"
+ notification = notification(
+ merchant_reference=invalid_reference,
+ value=to_adyen_price(payment.total, payment.currency),
+ )
+ notification["additionalData"]["modification.action"] = "cancel"
+
+ caplog.set_level(logging.WARNING)
+
+ handle_cancel_or_refund(notification, config)
+
+ assert f"Unable to decode the payment ID {invalid_reference}." in caplog.text
diff --git a/saleor/payment/gateways/adyen/tests/webhooks/test_validate_notification.py b/saleor/payment/gateways/adyen/tests/webhooks/test_validate_notification.py
index 942087f5a4..339f1afb20 100644
--- a/saleor/payment/gateways/adyen/tests/webhooks/test_validate_notification.py
+++ b/saleor/payment/gateways/adyen/tests/webhooks/test_validate_notification.py
@@ -1,6 +1,10 @@
from django.contrib.auth.hashers import make_password
-from ...webhooks import validate_auth_user, validate_hmac_signature
+from ...webhooks import (
+ validate_auth_user,
+ validate_hmac_signature,
+ validate_merchant_account,
+)
def test_validate_hmac_signature(adyen_plugin, notification_with_hmac_signature):
@@ -73,3 +77,21 @@ def test_validate_auth_user_when_auth_is_disabled(adyen_plugin):
config = plugin.config
is_valid = validate_auth_user(headers={}, gateway_config=config)
assert is_valid is True
+
+
+def test_validate_merchant_account(adyen_plugin, notification_with_hmac_signature):
+ plugin = adyen_plugin()
+ config = plugin.config
+ notification_with_hmac_signature[
+ "merchantAccountCode"
+ ] = config.connection_params.get("merchant_account")
+ assert validate_merchant_account(notification_with_hmac_signature, config) is True
+
+
+def test_validate_merchant_account_invalid_merchant_account(
+ adyen_plugin, notification_with_hmac_signature
+):
+ plugin = adyen_plugin()
+ config = plugin.config
+ notification_with_hmac_signature["merchantAccountCode"] = "test"
+ assert validate_merchant_account(notification_with_hmac_signature, config) is False
diff --git a/saleor/payment/gateways/adyen/webhooks.py b/saleor/payment/gateways/adyen/webhooks.py
index 5a2e226bbc..9b6d0086e9 100644
--- a/saleor/payment/gateways/adyen/webhooks.py
+++ b/saleor/payment/gateways/adyen/webhooks.py
@@ -4,6 +4,7 @@ import hashlib
import hmac
import json
import logging
+from json.decoder import JSONDecodeError
from typing import Any, Callable, Dict, Optional
from urllib.parse import urlencode
@@ -49,12 +50,12 @@ def get_payment(
payment_id: Optional[str], transaction_id: Optional[str] = None
) -> Optional[Payment]:
transaction_id = transaction_id or ""
- if not payment_id:
+ if payment_id is None or not payment_id.strip():
logger.warning("Missing payment ID. Reference %s", transaction_id)
return None
try:
_type, db_payment_id = from_global_id(payment_id)
- except UnicodeDecodeError:
+ except (UnicodeDecodeError, binascii.Error):
logger.warning(
"Unable to decode the payment ID %s. Reference %s",
payment_id,
@@ -569,15 +570,31 @@ def validate_auth_user(headers: HttpHeaders, gateway_config: "GatewayConfig") ->
return False
+def validate_merchant_account(
+ notification: Dict[str, Any], gateway_config: "GatewayConfig"
+):
+ merchant_account_code = notification.get("merchantAccountCode")
+ return merchant_account_code == gateway_config.connection_params.get(
+ "merchant_account"
+ )
+
+
@transaction_with_commit_on_errors()
def handle_webhook(request: WSGIRequest, gateway_config: "GatewayConfig"):
- json_data = json.loads(request.body)
+ try:
+ json_data = json.loads(request.body)
+ except JSONDecodeError:
+ logger.warning("Cannot parse request body.")
+ return HttpResponse("[accepted]")
# JSON and HTTP POST notifications always contain a single NotificationRequestItem
# object.
notification = json_data.get("notificationItems")[0].get(
"NotificationRequestItem", {}
)
+ if not validate_merchant_account(notification, gateway_config):
+ logger.warning("Not supported merchant account.")
+ return HttpResponse("[accepted]")
if not validate_hmac_signature(notification, gateway_config):
return HttpResponseBadRequest("Invalid or missing hmac signature.")
if not validate_auth_user(request.headers, gateway_config):