Skip to content

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

Simplify usage of synchronous webhooks in the Transaction API (#17690)

Maciej Korycinski9a72f1265e4f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3cba8f330b..494b55ae3e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -73,6 +73,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Introduce `useLegacyLineVoucherPropagation` flag to control legacy propagation behavior for specific voucher types - #17587 - by @korycins
- Add filterable subscriptions for checkout events (`checkoutCreated`, `checkoutUpdated`, `checkoutFullyPaid`, `checkoutMetadataUpdated`) - #17647 by @korycins
+
### Webhooks
- Fixed webhookTrigger payload type for events related to ProductVariant - #16956 by @delemeator
@@ -82,6 +83,9 @@ All notable, unreleased changes to this project will be documented in this file.
- Fixed webhook `PRODUCT_VARIANT_METADATA_UPDATED` not being sent when `productVariantUpdate` mutation was called. Now, when `metadata` or `privateMetadata` is included in `ProductVariantUpdateInput`, both `PRODUCT_VARIANT_METADATA_UPDATED` and `PRODUCT_VARIANT_UPDATED` will be emitted (if subscribed) - #17406 by @lkostrowski
- Update Draft Order shipping via `orderUpdateShipping` will emit `DRAFT_ORDER_UPDATED` webhook. Previously it was `ORDER_UPDATED` - #17480 by @lkostrowski
- Update editable Order shipping via `orderUpdateShipping` will emit `ORDER_UPDATED` webhook when `shippingMethod` will be cleared (by passing `null` to graphQL input). - #17480 by @lkostrowski
+- Webhook `TRANSACTION_CANCELATION_REQUESTED` now provides a decimal value in the action.amount field instead of null - #17690 by @korycins
+- `TransactionAction.amount` field in subscription payload for webhooks: `TransactionRefundRequested`, `TransactionChargeRequested`, `TransactionCancelationRequested`, is now a non-null field - #17690 by @korycins
+- Field `amount` in the response for synchronous webhooks: `TRANSACTION_CHARGE_REQUESTED`, `TRANSACTION_REFUND_REQUESTED`, `TRANSACTION_CANCELATION_REQUESTED`, `TRANSACTION_INITIALIZE_SESSION`, `TRANSACTION_PROCESS_SESSION` is now optional field. If omitted, the system will default to using the `action.amount` specified in the payload. - #17690 by @korycins
### Other changes
- Fixed outdated documentation links - #17675 by @krzysztofwolski
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_request_action.py b/saleor/graphql/payment/mutations/transaction/transaction_request_action.py
index 7eb136d81b..0255841064 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_request_action.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_request_action.py
@@ -56,9 +56,10 @@ class TransactionRequestAction(BaseMutation):
)
amount = PositiveDecimal(
description=(
- "Transaction request amount. If empty for refund or capture, maximal "
- "possible amount will be used."
- )
+ "Transaction request amount. If empty, maximal possible "
+ "amount will be used."
+ ),
+ required=False,
)
class Meta:
@@ -78,12 +79,14 @@ class TransactionRequestAction(BaseMutation):
):
if action == TransactionAction.CANCEL:
transaction = action_kwargs["transaction"]
+ action_value = action_value or transaction.authorized_value
+ action_value = min(action_value, transaction.authorized_value)
request_event = cls.create_transaction_event_requested(
- transaction, 0, action, user=user, app=app
+ transaction, action_value, action, user=user, app=app
)
request_cancelation_action(
**action_kwargs,
- cancel_value=None,
+ cancel_value=action_value,
request_event=request_event,
action=action,
)
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py b/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py
index 2cb647b38b..e14ee3c309 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py
@@ -553,7 +553,7 @@ def test_transaction_request_cancelation_for_order(
TransactionActionData(
transaction=transaction,
action_type=TransactionAction.CANCEL,
- action_value=None,
+ action_value=transaction.authorized_value,
event=request_event,
transaction_app_owner=transaction_request_webhook.app,
),
@@ -567,7 +567,7 @@ def test_transaction_request_cancelation_for_order(
assert TransactionEvent.objects.get(
transaction=transaction,
type=TransactionEventType.CANCEL_REQUEST,
- amount_value=0,
+ amount_value=transaction.authorized_value,
)
@@ -587,14 +587,14 @@ def test_transaction_request_cancelation_for_checkout(
transaction_request_webhook.events.create(
event_type=WebhookEventSyncType.TRANSACTION_CANCELATION_REQUESTED
)
-
+ expected_amount = Decimal("10")
transaction = TransactionItem.objects.create(
name="Credit card",
psp_reference="PSP ref",
available_actions=["charge", "cancel"],
currency="USD",
checkout_id=checkout.pk,
- authorized_value=Decimal("10"),
+ authorized_value=expected_amount,
app_identifier=transaction_request_webhook.app.identifier,
app=transaction_request_webhook.app,
)
@@ -623,7 +623,7 @@ def test_transaction_request_cancelation_for_checkout(
TransactionActionData(
transaction=transaction,
action_type=TransactionAction.CANCEL,
- action_value=None,
+ action_value=expected_amount,
event=request_event,
transaction_app_owner=transaction_request_webhook.app,
),
@@ -633,7 +633,7 @@ def test_transaction_request_cancelation_for_checkout(
assert TransactionEvent.objects.get(
transaction=transaction,
type=TransactionEventType.CANCEL_REQUEST,
- amount_value=0,
+ amount_value=expected_amount,
)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 6e4b362fe2..48f3e001eb 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -15384,7 +15384,7 @@ type Mutation {
actionType: TransactionActionEnum!
"""
- Transaction request amount. If empty for refund or capture, maximal possible amount will be used.
+ Transaction request amount. If empty, maximal possible amount will be used.
"""
amount: PositiveDecimal
@@ -33029,8 +33029,8 @@ type TransactionAction @doc(category: "Payments") {
"""Determines the action type."""
actionType: TransactionActionEnum!
- """Transaction request amount. Null when action type is VOID."""
- amount: PositiveDecimal
+ """Transaction request amount."""
+ amount: PositiveDecimal!
"""Currency code."""
currency: String!
diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.py
index b70dbfe4ca..6f0b368796 100644
--- a/saleor/graphql/webhook/subscription_types.py
+++ b/saleor/graphql/webhook/subscription_types.py
@@ -1767,7 +1767,8 @@ class TransactionAction(SubscriptionObjectType, AbstractType):
description="Determines the action type.",
)
amount = PositiveDecimal(
- description="Transaction request amount. Null when action type is VOID.",
+ description="Transaction request amount.",
+ required=True,
)
currency = graphene.String(
description="Currency code.",
@@ -1779,9 +1780,7 @@ class TransactionAction(SubscriptionObjectType, AbstractType):
@staticmethod
def resolve_amount(root: TransactionActionData, _info: ResolveInfo):
- if root.action_value is not None:
- return quantize_price(root.action_value, root.transaction.currency)
- return None
+ return quantize_price(root.action_value, root.transaction.currency)
@staticmethod
def resolve_currency(root: TransactionActionData, _info: ResolveInfo):
diff --git a/saleor/payment/gateway.py b/saleor/payment/gateway.py
index d374050c7e..24f28edf93 100644
--- a/saleor/payment/gateway.py
+++ b/saleor/payment/gateway.py
@@ -168,6 +168,9 @@ def request_cancelation_action(
app: App | None,
action: str,
):
+ if cancel_value is None:
+ cancel_value = transaction.authorized_value
+
transaction_action_data = _create_transaction_data(
transaction=transaction,
action_type=action,
@@ -195,7 +198,7 @@ def request_cancelation_action(
def _create_transaction_data(
transaction: TransactionItem,
action_type: str,
- action_value: Decimal | None,
+ action_value: Decimal,
request_event: TransactionEvent,
granted_refund: OrderGrantedRefund | None = None,
):
diff --git a/saleor/payment/interface.py b/saleor/payment/interface.py
index bbd05c103f..8ae0085b2d 100644
--- a/saleor/payment/interface.py
+++ b/saleor/payment/interface.py
@@ -114,7 +114,7 @@ class TransactionActionData:
transaction: TransactionItem
event: "TransactionEvent"
transaction_app_owner: Optional["App"]
- action_value: Decimal | None = None
+ action_value: Decimal
granted_refund: Optional["OrderGrantedRefund"] = None
diff --git a/saleor/payment/tests/test_gateway.py b/saleor/payment/tests/test_gateway.py
index c9fe7bc335..834e89e04d 100644
--- a/saleor/payment/tests/test_gateway.py
+++ b/saleor/payment/tests/test_gateway.py
@@ -1217,7 +1217,7 @@ def test_request_cancelation_action_on_order(
TransactionActionData(
transaction=transaction,
action_type=TransactionAction.CANCEL,
- action_value=None,
+ action_value=transaction.authorized_value,
event=requested_event,
transaction_app_owner=app,
),
@@ -1259,7 +1259,9 @@ def test_request_cancelation_action_by_app(
app=webhook_app,
)
requested_event = transaction.events.create(
- currency=transaction.currency, type=TransactionEventType.CANCEL_REQUEST
+ currency=transaction.currency,
+ type=TransactionEventType.CANCEL_REQUEST,
+ amount_value=transaction.authorized_value,
)
mocked_is_active.side_effect = [False, True]
@@ -1281,7 +1283,7 @@ def test_request_cancelation_action_by_app(
TransactionActionData(
transaction=transaction,
action_type=TransactionAction.CANCEL,
- action_value=None,
+ action_value=transaction.authorized_value,
event=requested_event,
transaction_app_owner=webhook_app,
),
@@ -1326,6 +1328,7 @@ def test_request_cancelation_action_on_checkout(
requested_event = transaction.events.create(
currency=transaction.currency,
type=TransactionEventType.CANCEL_REQUEST,
+ amount_value=transaction.authorized_value,
)
mocked_is_active.side_effect = [False, True]
@@ -1347,7 +1350,7 @@ def test_request_cancelation_action_on_checkout(
TransactionActionData(
transaction=transaction,
action_type=TransactionAction.CANCEL,
- action_value=None,
+ action_value=transaction.authorized_value,
event=requested_event,
transaction_app_owner=app,
),
diff --git a/saleor/payment/tests/test_utils.py b/saleor/payment/tests/test_utils.py
index 8e22415adf..ab7779c7a9 100644
--- a/saleor/payment/tests/test_utils.py
+++ b/saleor/payment/tests/test_utils.py
@@ -242,7 +242,7 @@ def test_parse_transaction_action_data_with_only_psp_reference():
# when
parsed_data, _ = parse_transaction_action_data(
- response_data, TransactionEventType.AUTHORIZATION_REQUEST
+ response_data, TransactionEventType.CHARGE_REQUEST, Decimal(10.00)
)
# then
@@ -294,6 +294,7 @@ def test_parse_transaction_action_data_with_provided_time(
event_time, expected_datetime
):
# given
+ request_event_amount = Decimal(10.00)
expected_psp_reference = "psp:122:222"
event_amount = 12.00
event_type = TransactionEventType.CHARGE_SUCCESS
@@ -311,7 +312,7 @@ def test_parse_transaction_action_data_with_provided_time(
# when
parsed_data, error_msg = parse_transaction_action_data(
- response_data, TransactionEventType.CHARGE_REQUEST
+ response_data, TransactionEventType.CHARGE_REQUEST, request_event_amount
)
# then
assert parsed_data.event.time == expected_datetime
@@ -319,6 +320,8 @@ def test_parse_transaction_action_data_with_provided_time(
def test_parse_transaction_action_data_with_event_all_fields_provided():
# given
+ request_event_amount = Decimal(10.00)
+
expected_psp_reference = "psp:122:222"
event_amount = 12.00
event_type = TransactionEventType.CHARGE_SUCCESS
@@ -337,7 +340,7 @@ def test_parse_transaction_action_data_with_event_all_fields_provided():
# when
parsed_data, error_msg = parse_transaction_action_data(
- response_data, TransactionEventType.CHARGE_REQUEST
+ response_data, TransactionEventType.CHARGE_REQUEST, request_event_amount
)
# then
assert isinstance(parsed_data, TransactionRequestResponse)
@@ -355,6 +358,7 @@ def test_parse_transaction_action_data_with_event_all_fields_provided():
def test_parse_transaction_action_data_with_incorrect_result():
# given
+ request_event_amount = Decimal(10.00)
expected_psp_reference = "psp:122:222"
event_amount = 12.00
event_type = TransactionEventType.CHARGE_SUCCESS
@@ -373,7 +377,7 @@ def test_parse_transaction_action_data_with_incorrect_result():
# when
parsed_data, error_msg = parse_transaction_action_data(
- response_data, TransactionEventType.REFUND_REQUEST
+ response_data, TransactionEventType.REFUND_REQUEST, request_event_amount
)
# then
@@ -389,12 +393,11 @@ def test_parse_transaction_action_data_with_event_only_mandatory_fields():
response_data = {
"pspReference": expected_psp_reference,
"result": TransactionEventType.CHARGE_SUCCESS.upper(),
- "amount": expected_amount,
}
# when
parsed_data, _ = parse_transaction_action_data(
- response_data, TransactionEventType.CHARGE_REQUEST
+ response_data, TransactionEventType.CHARGE_REQUEST, expected_amount
)
# then
@@ -410,6 +413,46 @@ def test_parse_transaction_action_data_with_event_only_mandatory_fields():
assert parsed_data.event.message == ""
+def test_parse_transaction_action_data_use_provided_amount_when_event_amount_is_missing():
+ # given
+ request_event_amount = Decimal(10.00)
+ response_data = {
+ "pspReference": "123",
+ "result": TransactionEventType.CHARGE_SUCCESS.upper(),
+ }
+
+ # when
+ parsed_data, _ = parse_transaction_action_data(
+ response_data, TransactionEventType.CHARGE_REQUEST, request_event_amount
+ )
+
+ # then
+ assert isinstance(parsed_data, TransactionRequestResponse)
+ assert parsed_data.event.amount == request_event_amount
+
+
+def test_parse_transaction_action_data_skips_input_amount_when_event_has_amount():
+ # given
+ request_event_amount = Decimal(10.00)
+ expected_amount = Decimal(12.00)
+
+ assert request_event_amount != expected_amount
+ response_data = {
+ "pspReference": "123",
+ "result": TransactionEventType.CHARGE_SUCCESS.upper(),
+ "amount": expected_amount,
+ }
+
+ # when
+ parsed_data, _ = parse_transaction_action_data(
+ response_data, TransactionEventType.CHARGE_REQUEST, request_event_amount
+ )
+
+ # then
+ assert isinstance(parsed_data, TransactionRequestResponse)
+ assert parsed_data.event.amount == expected_amount
+
+
@freeze_time("2018-05-31 12:00:01")
def test_parse_transaction_action_data_with_missing_psp_reference():
# given
@@ -417,7 +460,7 @@ def test_parse_transaction_action_data_with_missing_psp_reference():
# when
parsed_data, _ = parse_transaction_action_data(
- response_data, TransactionEventType.AUTHORIZATION_REQUEST
+ response_data, TransactionEventType.AUTHORIZATION_REQUEST, Decimal(10.00)
)
# then
@@ -426,12 +469,15 @@ def test_parse_transaction_action_data_with_missing_psp_reference():
def test_parse_transaction_action_data_with_missing_optional_psp_reference():
# given
- response_data = {}
+ response_data = {
+ "result": TransactionEventType.CHARGE_FAILURE.upper(),
+ }
# when
parsed_data, _ = parse_transaction_action_data(
response_data,
- TransactionEventType.AUTHORIZATION_ACTION_REQUIRED,
+ TransactionEventType.CHARGE_REQUEST,
+ Decimal("10.00"),
)
# then
@@ -442,11 +488,16 @@ def test_parse_transaction_action_data_with_missing_mandatory_event_fields():
# given
expected_psp_reference = "psp:122:222"
- response_data = {"pspReference": expected_psp_reference, "amount": Decimal("1")}
+ response_data = {
+ "pspReference": expected_psp_reference,
+ }
# when
parsed_data, _ = parse_transaction_action_data(
- response_data, TransactionEventType.AUTHORIZATION_REQUEST
+ response_data,
+ TransactionEventType.CHARGE_REQUEST,
+ Decimal("10.00"),
+ event_is_optional=False,
)
# then
@@ -613,6 +664,76 @@ def test_create_transaction_event_from_request_and_webhook_response_with_no_psp_
assert error_msg in caplog.records[0].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.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_amount_in_response(
+ event_type,
+ result_event_type,
+ transaction_item_generator,
+ app,
+):
+ # given
+ expected_amount = Decimal(11.00)
+ expected_psp_reference = "psp:122:222"
+
+ transaction = transaction_item_generator()
+ request_event = TransactionEvent.objects.create(
+ type=event_type,
+ amount_value=expected_amount,
+ currency="USD",
+ transaction_id=transaction.id,
+ )
+ event_count = transaction.events.count()
+ response_data = {
+ "pspReference": expected_psp_reference,
+ "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 == expected_psp_reference
+ assert request_event.include_in_calculations is True
+ assert transaction.events.count() == event_count + 1
+ assert event.psp_reference == expected_psp_reference
+ assert event.transaction_id == transaction.id
+ assert event.amount_value == expected_amount
+ assert event.type == result_event_type
+ assert not event.message
+
+
@freeze_time("2018-05-31 12:00:01")
def test_create_transaction_event_from_request_and_webhook_response_part_event(
transaction_item_generator,
@@ -1361,7 +1482,7 @@ def test_create_transaction_event_from_request_and_webhook_response_same_event(
@pytest.mark.parametrize(
"event_amount",
- [None, "NaN", "-Inf", "Inf", "One"],
+ ["NaN", "-Inf", "Inf", "One"],
)
@freeze_time("2018-05-31 12:00:01")
def test_create_transaction_event_from_request_handle_incorrect_values(
@@ -2134,6 +2255,52 @@ def test_create_transaction_event_for_transaction_session_success_response(
assert getattr(transaction, transaction_amount_field_name) == expected_amount
+ ("response_result", "transaction_amount_field_name"),
+ [
+ (TransactionEventType.AUTHORIZATION_REQUEST, "authorize_pending_value"),
+ (TransactionEventType.AUTHORIZATION_SUCCESS, "authorized_value"),
+ (TransactionEventType.CHARGE_REQUEST, "charge_pending_value"),
+ (TransactionEventType.CHARGE_SUCCESS, "charged_value"),
+ ],
+)
+def test_create_transaction_event_for_transaction_session_success_response_with_no_amount(
+ response_result,
+ transaction_amount_field_name,
+ transaction_item_generator,
+ transaction_session_response,
+ webhook_app,
+ plugins_manager,
+):
+ # given
+ request_event_amount = Decimal("12")
+ response = transaction_session_response.copy()
+ response["result"] = response_result.upper()
+
+ response["amount"] = None
+
+ transaction = transaction_item_generator()
+ request_event = TransactionEvent.objects.create(
+ transaction=transaction,
+ include_in_calculations=False,
+ amount_value=request_event_amount,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+ # when
+ response_event = create_transaction_event_for_transaction_session(
+ request_event,
+ webhook_app,
+ manager=plugins_manager,
+ transaction_webhook_response=response,
+ )
+
+ # then
+ assert response_event.include_in_calculations
+ assert response_event.amount_value == request_event_amount
+ transaction.refresh_from_db()
+ assert getattr(transaction, transaction_amount_field_name) == request_event_amount
+
+
@pytest.mark.parametrize(
("response_result", "transaction_amount_field_name"),
[
@@ -2223,6 +2390,55 @@ def test_create_transaction_event_for_transaction_session_not_success_events(
assert transaction.charge_pending_value == Decimal("0")
+ "response_result",
+ [
+ TransactionEventType.AUTHORIZATION_ACTION_REQUIRED,
+ TransactionEventType.CHARGE_ACTION_REQUIRED,
+ TransactionEventType.AUTHORIZATION_FAILURE,
+ TransactionEventType.CHARGE_FAILURE,
+ TransactionEventType.REFUND_FAILURE,
+ TransactionEventType.REFUND_SUCCESS,
+ ],
+)
+def test_create_transaction_event_for_transaction_session_not_success_events_with_no_amount(
+ response_result,
+ transaction_item_generator,
+ transaction_session_response,
+ webhook_app,
+ plugins_manager,
+):
+ # given
+ expected_amount = Decimal("15")
+ response = transaction_session_response.copy()
+ response["result"] = response_result.upper()
+ response["amount"] = None
+
+ transaction = transaction_item_generator()
+ request_event = TransactionEvent.objects.create(
+ transaction=transaction,
+ include_in_calculations=False,
+ amount_value=expected_amount,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+ # when
+ response_event = create_transaction_event_for_transaction_session(
+ request_event,
+ webhook_app,
+ manager=plugins_manager,
+ transaction_webhook_response=response,
+ )
+
+ # then
+ assert response_event.amount_value == expected_amount
+ assert response_event.type in [response_result, TransactionEventType.CHARGE_FAILURE]
+ transaction.refresh_from_db()
+ assert transaction.authorized_value == Decimal("0")
+ assert transaction.charged_value == Decimal("0")
+ assert transaction.authorize_pending_value == Decimal("0")
+ assert transaction.charge_pending_value == Decimal("0")
+
+
@pytest.mark.parametrize(
("response_result", "message"),
[
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 1a9637c5ee..38d71b6648 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -1,4 +1,3 @@
-import decimal
import json
import logging
from decimal import Decimal
@@ -41,10 +40,10 @@ from ..webhook.response_schemas.transaction import (
TransactionCancelRequestedSchema,
TransactionChargeRequestedSchema,
TransactionRefundRequestedSchema,
+ TransactionSchema,
TransactionSessionSchema,
)
from . import (
- OPTIONAL_PSP_REFERENCE_EVENTS,
ChargeStatus,
GatewayError,
PaymentError,
@@ -821,39 +820,13 @@ def get_correct_event_types_based_on_request_type(request_type: str) -> list[str
return type_map.get(request_type, [])
-def parse_transaction_event_amount(
- amount_data: str | int | float | None,
- parsed_event_data: dict,
- error_field_msg: list[str],
- invalid_msg: str,
- missing_msg: str,
-):
- if amount_data is not None:
- amount_valid = True
- try:
- amount = decimal.Decimal(amount_data).quantize(
- decimal.Decimal(10) ** (-settings.DEFAULT_DECIMAL_PLACES)
- )
- parsed_event_data["amount"] = amount
- if not amount.is_finite():
- amount_valid = False
- except decimal.DecimalException:
- amount_valid = False
-
- if not amount_valid:
- logger.warning(invalid_msg, "amount", amount_data)
- error_field_msg.append(invalid_msg % ("amount", amount_data))
- else:
- logger.warning(missing_msg, "amount")
- error_field_msg.append(missing_msg % "amount")
-
-
error_msg = str
def parse_transaction_action_data(
response_data: Any,
request_type: str,
+ request_event_amount: Decimal,
event_is_optional: bool = True,
) -> tuple[Optional["TransactionRequestResponse"], error_msg | None]:
"""Parse response from transaction action webhook.
@@ -862,30 +835,8 @@ def parse_transaction_action_data(
returns TransactionRequestResponse with all details.
If unable to parse, None will be returned.
"""
- skip_data_parsing = (
- event_is_optional
- and response_data.get("amount") is None
- and not response_data.get("result")
- )
- if skip_data_parsing:
- psp_reference = response_data.get("pspReference")
- if not psp_reference and request_type not in OPTIONAL_PSP_REFERENCE_EVENTS:
- msg = f"Providing `pspReference` is required for {request_type.upper()}."
- logger.warning(msg)
- return None, msg
- return (
- TransactionRequestResponse(
- psp_reference=psp_reference,
- available_actions=parse_available_actions(
- response_data.get("actions", None)
- ),
- event=None,
- ),
- None,
- )
- response_data_model = None
- request_type_to_schema_map = {
+ request_type_to_schema_map: dict[str, type[TransactionSchema]] = {
TransactionEventType.CHARGE_REQUEST: TransactionChargeRequestedSchema,
TransactionEventType.REFUND_REQUEST: TransactionRefundRequestedSchema,
TransactionEventType.CANCEL_REQUEST: TransactionCancelRequestedSchema,
@@ -901,33 +852,32 @@ def parse_transaction_action_data(
)
return None, "Request type not supported"
+ error_msg_response = None
try:
- response_data_model = (
- request_schema.model_validate(response_data) # type: ignore[attr-defined]
+ response_data_model = request_schema.model_validate(
+ response_data, context={"is_event_optional": event_is_optional}
)
- except ValidationError as error:
- error_msg = str(error)
- logger.warning(error_msg)
- msg = truncate_transaction_event_message(error_msg)
- return None, msg
-
- return (
- TransactionRequestResponse(
+ event = TransactionRequestEventResponse(
psp_reference=response_data_model.psp_reference,
- available_actions=response_data_model.actions,
- event=(
- TransactionRequestEventResponse(
- psp_reference=response_data_model.psp_reference,
- type=response_data_model.result,
- amount=response_data_model.amount,
- time=response_data_model.time,
- external_url=str(response_data_model.external_url),
- message=response_data_model.message,
- )
+ type=response_data_model.result,
+ amount=response_data_model.amount or request_event_amount,
+ time=response_data_model.time,
+ external_url=str(response_data_model.external_url),
+ message=response_data_model.message,
+ )
+ return (
+ TransactionRequestResponse(
+ psp_reference=response_data_model.psp_reference,
+ available_actions=response_data_model.actions,
+ event=event if response_data_model.result else None,
),
- ),
- None,
- )
+ None,
+ )
+ except ValidationError as error:
+ error_msg_response = str(error)
+ logger.warning(error_msg_response)
+ error_msg_response = truncate_transaction_event_message(error_msg_response)
+ return None, error_msg_response
def parse_available_actions(available_actions):
@@ -1121,6 +1071,7 @@ def _create_event_from_response(
def _get_parsed_transaction_action_data(
transaction_webhook_response: dict[str, Any] | None,
event_type: str,
+ request_event_amount: Decimal,
event_is_optional: bool = True,
) -> tuple[Optional["TransactionRequestResponse"], error_msg | None]:
if transaction_webhook_response is None:
@@ -1129,6 +1080,7 @@ def _get_parsed_transaction_action_data(
transaction_request_response, error_msg = parse_transaction_action_data(
transaction_webhook_response,
event_type,
+ request_event_amount=request_event_amount,
event_is_optional=event_is_optional,
)
if not transaction_request_response:
@@ -1162,6 +1114,7 @@ def create_transaction_event_for_transaction_session(
transaction_request_response, error_msg = _get_parsed_transaction_action_data(
transaction_webhook_response=transaction_webhook_response,
event_type=SESSION_REQUEST_EVENT_TYPE,
+ request_event_amount=request_event.amount_value,
event_is_optional=False,
)
if not transaction_request_response or not transaction_request_response.event:
@@ -1290,6 +1243,7 @@ def create_transaction_event_from_request_and_webhook_response(
transaction_request_response, error_msg = _get_parsed_transaction_action_data(
transaction_webhook_response=transaction_webhook_response,
event_type=request_event.type,
+ request_event_amount=request_event.amount_value,
)
transaction_item = request_event.transaction
if not transaction_request_response:
diff --git a/saleor/webhook/response_schemas/transaction.py b/saleor/webhook/response_schemas/transaction.py
index dc56664e07..6cea02a9b9 100644
--- a/saleor/webhook/response_schemas/transaction.py
+++ b/saleor/webhook/response_schemas/transaction.py
@@ -11,6 +11,7 @@ from pydantic import (
Field,
HttpUrl,
JsonValue,
+ ValidationInfo,
field_validator,
model_validator,
)
@@ -45,7 +46,11 @@ class TransactionSchema(BaseModel):
),
]
amount: Annotated[
- Decimal, Field(description="Decimal amount of the processed action")
+ DefaultIfNone[Decimal],
+ Field(
+ description="Decimal amount of the processed action",
+ default=None,
+ ),
]
time: Annotated[
DefaultIfNone[DatetimeUTC],
@@ -85,20 +90,33 @@ class TransactionSchema(BaseModel):
| None
) = None
result: Annotated[
- str,
+ DefaultIfNone[str],
Field(description="Result of the action"),
]
@model_validator(mode="after")
- def clean_psp_reference(self):
- if not self.psp_reference and self.result not in OPTIONAL_PSP_REFERENCE_EVENTS:
+ def clean_event(self, info: ValidationInfo):
+ is_event_optional = (
+ info.context.get("is_event_optional", False) if info.context else False
+ )
+
+ if self.result is None:
+ if not is_event_optional:
+ raise ValueError("Providing `result` is required.")
+ if not self.psp_reference:
+ raise ValueError("Providing `pspReference` is required.")
+ elif (
+ not self.psp_reference and self.result not in OPTIONAL_PSP_REFERENCE_EVENTS
+ ):
error_msg = f"Providing `pspReference` is required for {self.result.upper()} action result."
raise ValueError(error_msg)
return self
@field_validator("amount", mode="after")
@classmethod
- def clean_amount(cls, amount: Decimal) -> Decimal:
+ def clean_amount(cls, amount: Decimal | None) -> Decimal | None:
+ if amount is None:
+ return None
amount = amount.quantize(Decimal(10) ** (-settings.DEFAULT_DECIMAL_PLACES))
return amount
@@ -150,7 +168,9 @@ class TransactionSchema(BaseModel):
@field_validator("result", mode="after")
@classmethod
- def clean_result(cls, result: str) -> str:
+ def clean_result(cls, result: str | None) -> str | None:
+ if result is None:
+ return None
return result.lower()
@@ -166,7 +186,7 @@ class TransactionChargeRequestedSchema(TransactionSchema):
TransactionEventTypeEnum.CHARGE_SUCCESS.name,
TransactionEventTypeEnum.CHARGE_FAILURE.name,
],
- Field(description="Result of the action"),
+ Field(description="Result of the action", default=None),
]
@@ -176,7 +196,7 @@ class TransactionCancelRequestedSchema(TransactionSchema):
TransactionEventTypeEnum.CANCEL_SUCCESS.name,
TransactionEventTypeEnum.CANCEL_FAILURE.name,
],
- Field(description="Result of the action"),
+ Field(description="Result of the action", default=None),
]
@@ -186,7 +206,7 @@ class TransactionRefundRequestedSchema(TransactionSchema):
TransactionEventTypeEnum.REFUND_SUCCESS.name,
TransactionEventTypeEnum.REFUND_FAILURE.name,
],
- Field(description="Result of the action"),
+ Field(description="Result of the action", default=None),
]
diff --git a/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_cancelation_requested.py b/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_cancelation_requested.py
index 3d165ad209..2a5e04d16e 100644
--- a/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_cancelation_requested.py
+++ b/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_cancelation_requested.py
@@ -72,6 +72,7 @@ def test_order_transaction_cancel_request(
action_type=TransactionAction.CANCEL,
event=request_event,
transaction_app_owner=None,
+ action_value=authorized_value,
)
# when
deliveries = create_deliveries_for_subscriptions(
@@ -100,7 +101,11 @@ def test_order_transaction_cancel_request(
},
"checkout": None,
},
- "action": {"actionType": "CANCEL", "amount": None, "currency": order.currency},
+ "action": {
+ "actionType": "CANCEL",
+ "amount": quantize_price(authorized_value, "USD"),
+ "currency": order.currency,
+ },
}
@@ -143,6 +148,7 @@ def test_checkout_transaction_cancel_request(
action_type=TransactionAction.CANCEL,
event=request_event,
transaction_app_owner=None,
+ action_value=authorized_value,
)
# when
deliveries = create_deliveries_for_subscriptions(
@@ -182,5 +188,9 @@ def test_checkout_transaction_cancel_request(
},
},
},
- "action": {"actionType": "CANCEL", "amount": None, "currency": "USD"},
+ "action": {
+ "actionType": "CANCEL",
+ "amount": quantize_price(authorized_value, "USD"),
+ "currency": "USD",
+ },
}
diff --git a/saleor/webhook/tests/test_tasks.py b/saleor/webhook/tests/test_tasks.py
index 98357b7078..8e623f3bdb 100644
--- a/saleor/webhook/tests/test_tasks.py
+++ b/saleor/webhook/tests/test_tasks.py
@@ -642,12 +642,15 @@ def test_handle_transaction_request_task_with_missing_required_event_field(
app,
):
# given
- expected_psp_reference = "psp:123:111"
mocked_webhook_response.text = json.dumps(
- {"pspReference": expected_psp_reference, "amount": 12.00}
+ {
+ "result": TransactionEventType.REFUND_REQUEST.upper(),
+ }
)
mocked_webhook_response.content = json.dumps(
- {"pspReference": expected_psp_reference, "amount": 12.00}
+ {
+ "result": TransactionEventType.REFUND_REQUEST.upper(),
+ }
)
mocked_post_request.return_value = mocked_webhook_response