Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Make pspReference optional in some webhooks responses (#16491)
Iga Karbowiak6f747ba8ade1
diff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.pyindex b7ab5c0b3e..e03553a37f 100644--- a/saleor/payment/__init__.py+++ b/saleor/payment/__init__.py@@ -253,6 +253,17 @@ FAILED_TRANSACTION_EVENTS = []+OPTIONAL_PSP_REFERENCE_EVENTS = [+ TransactionEventType.CHARGE_ACTION_REQUIRED,+ TransactionEventType.AUTHORIZATION_ACTION_REQUIRED,+ TransactionEventType.CHARGE_FAILURE,+ TransactionEventType.AUTHORIZATION_FAILURE,+ TransactionEventType.REFUND_FAILURE,+ TransactionEventType.CHARGE_FAILURE,+ TransactionEventType.CANCEL_FAILURE,+]++class TokenizedPaymentFlow:"""Represents possible tokenized payment flows that can be used to process payment.diff --git a/saleor/payment/tests/test_utils.py b/saleor/payment/tests/test_utils.pyindex f5245c9c8a..49e0901334 100644--- a/saleor/payment/tests/test_utils.py+++ b/saleor/payment/tests/test_utils.py@@ -391,7 +391,7 @@ def test_parse_transaction_action_data_with_event_only_mandatory_fields():@freeze_time("2018-05-31 12:00:01")-def test_parse_transaction_action_data_with_missin_psp_reference():+def test_parse_transaction_action_data_with_missing_psp_reference():# givenresponse_data = {}@@ -404,6 +404,20 @@ def test_parse_transaction_action_data_with_missin_psp_reference():assert parsed_data is None+def test_parse_transaction_action_data_with_missing_optional_psp_reference():+ # given+ response_data = {}++ # when+ parsed_data, _ = parse_transaction_action_data(+ response_data,+ TransactionEventType.AUTHORIZATION_ACTION_REQUIRED,+ )++ # then+ assert parsed_data++def test_parse_transaction_action_data_with_missing_mandatory_event_fields():# givenexpected_psp_reference = "psp:122:222"@@ -466,6 +480,115 @@ def test_create_transaction_event_from_request_and_webhook_response_with_psp_refassert TransactionEvent.objects.count() == 1+ ("event_type", "result_event_type"),+ [+ (+ TransactionEventType.REFUND_REQUEST,+ TransactionEventType.REFUND_FAILURE,+ ),+ (+ TransactionEventType.CHARGE_REQUEST,+ TransactionEventType.CHARGE_FAILURE,+ ),+ (+ TransactionEventType.CANCEL_REQUEST,+ TransactionEventType.CANCEL_FAILURE,+ ),+ ],+)+def test_create_transaction_event_from_request_and_webhook_response_with_no_psp_reference_valid_event(+ event_type, result_event_type, transaction_item_generator, app+):+ # given+ transaction = transaction_item_generator()+ event_amount = Decimal(11.00)+ request_event = TransactionEvent.objects.create(+ type=event_type,+ amount_value=Decimal(11.00),+ currency="USD",+ transaction_id=transaction.id,+ )+ event_count = transaction.events.count()+ response_data = {+ "amount": event_amount,+ "result": result_event_type.upper(),+ }++ # when+ event = create_transaction_event_from_request_and_webhook_response(+ request_event, app, response_data+ )++ # then+ request_event.refresh_from_db()+ transaction.refresh_from_db()+ assert request_event.psp_reference is None+ assert transaction.events.count() == event_count + 1+ assert event.psp_reference is None+ assert event.type == result_event_type+ assert not event.message+++ ("event_type", "result_event_type"),+ [+ (+ TransactionEventType.REFUND_REQUEST,+ TransactionEventType.REFUND_SUCCESS,+ ),+ (+ TransactionEventType.CHARGE_REQUEST,+ TransactionEventType.CHARGE_SUCCESS,+ ),+ (+ TransactionEventType.CANCEL_REQUEST,+ TransactionEventType.CANCEL_SUCCESS,+ ),+ (+ TransactionEventType.AUTHORIZATION_REQUEST,+ TransactionEventType.AUTHORIZATION_SUCCESS,+ ),+ ],+)+def test_create_transaction_event_from_request_and_webhook_response_with_no_psp_reference_invalid_event(+ event_type,+ result_event_type,+ transaction_item_generator,+ app,+):+ # given+ transaction = transaction_item_generator()+ event_amount = Decimal(11.00)+ request_event = TransactionEvent.objects.create(+ type=event_type,+ amount_value=event_amount,+ currency="USD",+ transaction_id=transaction.id,+ )+ event_count = transaction.events.count()+ response_data = {+ "amount": event_amount,+ "result": result_event_type.upper(),+ }++ # when+ event = create_transaction_event_from_request_and_webhook_response(+ request_event, app, response_data+ )++ # then+ request_event.refresh_from_db()+ transaction.refresh_from_db()+ assert request_event.psp_reference is None+ assert transaction.events.count() == event_count + 1+ assert event.psp_reference is None+ assert event.transaction_id == transaction.id+ assert event.message == (+ f"Providing `pspReference` is required for {result_event_type.upper()}."+ )++@freeze_time("2018-05-31 12:00:01")def test_create_transaction_event_from_request_and_webhook_response_part_event(transaction_item_generator,@@ -1686,18 +1809,33 @@ def test_create_transaction_event_for_transaction_session_not_success_events(@pytest.mark.parametrize(- "response_result",+ ("response_result", "message"),[- TransactionEventType.AUTHORIZATION_FAILURE,- TransactionEventType.AUTHORIZATION_SUCCESS,- TransactionEventType.AUTHORIZATION_REQUEST,- TransactionEventType.CHARGE_FAILURE,- TransactionEventType.CHARGE_SUCCESS,- TransactionEventType.CHARGE_REQUEST,+ (+ TransactionEventType.AUTHORIZATION_SUCCESS,+ "Providing `pspReference` is required for AUTHORIZATION_SUCCESS.",+ ),+ (+ TransactionEventType.CHARGE_SUCCESS,+ "Providing `pspReference` is required for CHARGE_SUCCESS.",+ ),+ (+ TransactionEventType.CHARGE_FAILURE,+ "Message related to the payment",+ ),+ (+ TransactionEventType.CHARGE_REQUEST,+ "Providing `pspReference` is required for CHARGE_REQUEST.",+ ),+ (+ TransactionEventType.AUTHORIZATION_REQUEST,+ "Providing `pspReference` is required for AUTHORIZATION_REQUEST.",+ ),],)def test_create_transaction_event_for_transaction_session_missing_psp_reference(response_result,+ message,transaction_item_generator,transaction_session_response,webhook_app,@@ -1727,6 +1865,7 @@ def test_create_transaction_event_for_transaction_session_missing_psp_reference(# thenassert response_event.amount_value == expected_amountassert response_event.type == TransactionEventType.CHARGE_FAILURE+ assert response_event.message == messagetransaction.refresh_from_db()assert transaction.authorized_value == Decimal("0")assert transaction.charged_value == Decimal("0")diff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex f4bade3712..0396f744e0 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -38,6 +38,7 @@ from ..order.utils import ()from ..plugins.manager import PluginsManager, get_plugins_managerfrom . import (+ OPTIONAL_PSP_REFERENCE_EVENTS,ChargeStatus,GatewayError,PaymentError,@@ -919,7 +920,6 @@ def parse_transaction_action_data(response_data: Any,request_type: str,event_is_optional: bool = True,- psp_reference_is_optional: bool = False,) -> tuple[Optional["TransactionRequestResponse"], Optional[error_msg]]:"""Parse response from transaction action webhook.@@ -928,11 +928,6 @@ def parse_transaction_action_data(If unable to parse, None will be returned."""psp_reference: str = response_data.get("pspReference")- if not psp_reference and not psp_reference_is_optional:- msg: str = "Missing `pspReference` field in the response."- logger.error(msg)- return None, msg-available_actions = response_data.get("actions", None)if available_actions is not None:possible_actions = {@@ -964,6 +959,12 @@ def parse_transaction_action_data(msg = msg[:509] + "..."return None, msg+ request_event_type = parsed_event_data.get("type", request_type)+ if not psp_reference and request_event_type not in OPTIONAL_PSP_REFERENCE_EVENTS:+ msg = f"Providing `pspReference` is required for {request_event_type.upper()}."+ logger.error(msg)+ return None, msg+return (TransactionRequestResponse(psp_reference=psp_reference,@@ -1145,7 +1146,6 @@ def _get_parsed_transaction_action_data(transaction_webhook_response: Optional[dict[str, Any]],event_type: str,event_is_optional: bool = True,- psp_reference_is_optional: bool = False,) -> tuple[Optional["TransactionRequestResponse"], Optional[error_msg]]:if transaction_webhook_response is None:return None, "Failed to delivery request."@@ -1154,7 +1154,6 @@ def _get_parsed_transaction_action_data(transaction_webhook_response,event_type,event_is_optional=event_is_optional,- psp_reference_is_optional=psp_reference_is_optional,)if not transaction_request_response:return None, error_msg or ""@@ -1190,7 +1189,6 @@ def create_transaction_event_for_transaction_session(transaction_webhook_response=transaction_webhook_response,event_type=request_event_type,event_is_optional=False,- psp_reference_is_optional=True,)if not transaction_request_response or not transaction_request_response.event:return create_failed_transaction_event(request_event, cause=error_msg or "")@@ -1198,18 +1196,7 @@ def create_transaction_event_for_transaction_session(event = Nonerequest_event_update_fields = []response_event = transaction_request_response.event- if not response_event.psp_reference and response_event.type not in [- TransactionEventType.AUTHORIZATION_ACTION_REQUIRED,- TransactionEventType.CHARGE_ACTION_REQUIRED,- ]:- return create_failed_transaction_event(- request_event,- cause=(- f"Providing `pspReference` is required for "- f"{response_event.type.upper()}"- ),- )- elif response_event.type in [+ if response_event.type in [TransactionEventType.AUTHORIZATION_REQUEST,TransactionEventType.CHARGE_REQUEST,]: