Skip to content

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

Adds support for storing payment method details in the Transaction API (#17845)

Maciej Korycinski12258b4dcfac
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fe4f3df7d4..36557999c1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -32,8 +32,10 @@ All notable, unreleased changes to this project will be documented in this file.
- The content of customer note
- The order external reference
- Extend sorting options. You can now sort orders by their status.
+- Add support for payment method details in the Transaction API. The payment method details associated with a transaction can now be persisted on the Saleor side. See [docs](https://docs.saleor.io/developer/payments/transactions#via-transaction-mutations) to learn more.
### Webhooks
+- Transaction webhooks responsible for processing payments can now return payment method details`, which will be associated with the corresponding transaction. See [docs](https://docs.saleor.io/developer/extending/webhooks/synchronous-events/transaction#response-4) to learn more.
### Other changes
- Add JSON schemas for synchronous webhooks, now available in `saleor/json_schemas.py`. These schemas define the expected structure of webhook responses sent back to Saleor, enabling improved validation and tooling support for integrations. This change helps ensure that responses from webhook consumers meet Saleor’s expectations and can be reliably processed.
diff --git a/saleor/core/management/commands/generate_json_schemas.py b/saleor/core/management/commands/generate_json_schemas.py
index 4709789c7c..eef76b5a93 100644
--- a/saleor/core/management/commands/generate_json_schemas.py
+++ b/saleor/core/management/commands/generate_json_schemas.py
@@ -69,6 +69,7 @@ class Command(BaseCommand):
path = os.path.join(SCHEMA_OUTPUT_DIR, file_name)
with open(path, "w") as f:
json.dump(schema, f, indent=2)
+ f.write("\n")
self.stdout.write(self.style.SUCCESS(f"Generated {path}"))
@staticmethod
diff --git a/saleor/graphql/payment/mutations/transaction/shared.py b/saleor/graphql/payment/mutations/transaction/shared.py
new file mode 100644
index 0000000000..3d1ba44d09
--- /dev/null
+++ b/saleor/graphql/payment/mutations/transaction/shared.py
@@ -0,0 +1,228 @@
+import graphene
+from django.core.exceptions import ValidationError
+
+from .....payment import PaymentMethodType
+from .....payment.error_codes import (
+ TransactionCreateErrorCode,
+ TransactionEventReportErrorCode,
+ TransactionUpdateErrorCode,
+)
+from .....payment.interface import PaymentMethodDetails
+from ....core.descriptions import ADDED_IN_322
+from ....core.types.base import BaseInputObjectType
+from ....core.validators import validate_one_of_args_is_in_mutation
+
+
+class CardPaymentMethodDetailsInput(BaseInputObjectType):
+ name = graphene.String(
+ description="Name of the payment method used for the transaction. Max length is 256 characters.",
+ required=True,
+ )
+ brand = graphene.String(
+ description="Brand of the payment method used for the transaction. Max length is 40 characters.",
+ required=False,
+ )
+ first_digits = graphene.String(
+ description="First digits of the card used for the transaction. Max length is 4 characters.",
+ required=False,
+ )
+ last_digits = graphene.String(
+ description="Last digits of the card used for the transaction. Max length is 4 characters.",
+ required=False,
+ )
+ exp_month = graphene.Int(
+ description="Expiration month of the card used for the transaction. Value must be between 1 and 12.",
+ required=False,
+ )
+ exp_year = graphene.Int(
+ description="Expiration year of the card used for the transaction. Value must be between 2000 and 9999.",
+ required=False,
+ )
+
+
+class OtherPaymentMethodDetailsInput(BaseInputObjectType):
+ name = graphene.String(
+ description="Name of the payment method used for the transaction.",
+ required=True,
+ )
+
+
+class PaymentMethodDetailsInput(BaseInputObjectType):
+ card = graphene.Field(
+ CardPaymentMethodDetailsInput,
+ required=False,
+ description="Details of the card payment method used for the transaction.",
+ )
+ other = graphene.Field(
+ OtherPaymentMethodDetailsInput,
+ required=False,
+ description="Details of the non-card payment method used for this transaction.",
+ )
+
+ class Meta:
+ description = (
+ "Details of the payment method used for the transaction. "
+ "One of `card` or `other` is required." + ADDED_IN_322
+ )
+
+
+def validate_card_payment_method_details_input(
+ card_method_details_input: CardPaymentMethodDetailsInput,
+ error_code_class: type[TransactionEventReportErrorCode]
+ | type[TransactionCreateErrorCode]
+ | type[TransactionUpdateErrorCode],
+):
+ errors = []
+ if len(card_method_details_input.name) > 256:
+ errors.append(
+ {
+ "name": ValidationError(
+ "The `name` field must be less than 256 characters.",
+ code=error_code_class.INVALID.value,
+ )
+ }
+ )
+
+ if card_method_details_input.brand and len(card_method_details_input.brand) > 40:
+ errors.append(
+ {
+ "brand": ValidationError(
+ "The `brand` field must be less than 40 characters.",
+ code=error_code_class.INVALID.value,
+ )
+ }
+ )
+ if (
+ card_method_details_input.first_digits
+ and len(card_method_details_input.first_digits) > 4
+ ):
+ errors.append(
+ {
+ "first_digits": ValidationError(
+ "The `firstDigits` field must be less than 4 characters.",
+ code=error_code_class.INVALID.value,
+ )
+ }
+ )
+ if (
+ card_method_details_input.last_digits
+ and len(card_method_details_input.last_digits) > 4
+ ):
+ errors.append(
+ {
+ "last_digits": ValidationError(
+ "The `lastDigits` field must be less than 4 characters.",
+ code=error_code_class.INVALID.value,
+ )
+ }
+ )
+ if card_method_details_input.exp_month and (
+ card_method_details_input.exp_month < 1
+ or card_method_details_input.exp_month > 12
+ ):
+ errors.append(
+ {
+ "exp_month": ValidationError(
+ "The `expMonth` field must be between 1 and 12.",
+ code=error_code_class.INVALID.value,
+ )
+ }
+ )
+ if card_method_details_input.exp_year and (
+ card_method_details_input.exp_year < 2000
+ or card_method_details_input.exp_year > 9999
+ ):
+ errors.append(
+ {
+ "exp_year": ValidationError(
+ "The `expYear` field must be between 2000 and 9999.",
+ code=error_code_class.INVALID.value,
+ )
+ }
+ )
+ return errors
+
+
+def validate_payment_method_details_input(
+ payment_method_details_input: PaymentMethodDetailsInput,
+ error_code_class: type[TransactionEventReportErrorCode]
+ | type[TransactionCreateErrorCode]
+ | type[TransactionUpdateErrorCode],
+):
+ if (
+ payment_method_details_input.card is None
+ and payment_method_details_input.other is None
+ ):
+ raise ValidationError(
+ {
+ "payment_method_details": ValidationError(
+ "One of `card` or `other` is required.",
+ code=error_code_class.INVALID.value,
+ )
+ }
+ )
+ try:
+ validate_one_of_args_is_in_mutation(
+ "card",
+ payment_method_details_input.card,
+ "other",
+ payment_method_details_input.other,
+ )
+ except ValidationError as e:
+ e.code = error_code_class.INVALID.value
+ raise ValidationError({"payment_method_details": e}) from e
+
+ errors = []
+
+ if payment_method_details_input.card:
+ errors.extend(
+ validate_card_payment_method_details_input(
+ payment_method_details_input.card, error_code_class
+ )
+ )
+ elif payment_method_details_input.other:
+ if len(payment_method_details_input.other.name) > 256:
+ errors.append(
+ {
+ "name": ValidationError(
+ "The `name` field must be less than 256 characters.",
+ code=error_code_class.INVALID.value,
+ )
+ }
+ )
+
+ if errors:
+ raise ValidationError({"payment_method_details": errors})
+
+
+def get_payment_method_details(
+ payment_method_details_input: PaymentMethodDetailsInput | None,
+) -> PaymentMethodDetails | None:
+ """Get the payment method details dataclass from the input."""
+
+ if not payment_method_details_input:
+ return None
+
+ payment_details_data: PaymentMethodDetails | None = None
+ if payment_method_details_input.card:
+ card_details: CardPaymentMethodDetailsInput = payment_method_details_input.card
+
+ payment_details_data = PaymentMethodDetails(
+ type=PaymentMethodType.CARD,
+ name=card_details.name,
+ brand=card_details.brand,
+ first_digits=card_details.first_digits,
+ last_digits=card_details.last_digits,
+ exp_month=card_details.exp_month,
+ exp_year=card_details.exp_year,
+ )
+ elif payment_method_details_input.other:
+ other_details: OtherPaymentMethodDetailsInput = (
+ payment_method_details_input.other
+ )
+ payment_details_data = PaymentMethodDetails(
+ type=PaymentMethodType.OTHER,
+ name=other_details.name,
+ )
+
+ return payment_details_data
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_create.py b/saleor/graphql/payment/mutations/transaction/transaction_create.py
index afcd9b36cd..d5f8890ca6 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_create.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_create.py
@@ -20,14 +20,17 @@ from .....order.utils import update_order_status, updates_amounts_for_order
from .....payment import TransactionEventType
from .....payment import models as payment_models
from .....payment.error_codes import TransactionCreateErrorCode
+from .....payment.interface import PaymentMethodDetails
from .....payment.transaction_item_calculations import recalculate_transaction_amounts
from .....payment.utils import (
create_manual_adjustment_events,
truncate_transaction_event_message,
+ update_transaction_item_with_payment_method_details,
)
from .....permission.enums import PaymentPermissions
from ....app.dataloaders import get_app_promise
from ....core import ResolveInfo
+from ....core.descriptions import ADDED_IN_322
from ....core.doc_category import DOC_CATEGORY_PAYMENTS
from ....core.mutations import BaseMutation
from ....core.types import BaseInputObjectType
@@ -38,6 +41,11 @@ from ...enums import TransactionActionEnum
from ...types import TransactionItem
from ...utils import deprecated_metadata_contains_empty_key
from ..payment.payment_check_balance import MoneyInput
+from .shared import (
+ PaymentMethodDetailsInput,
+ get_payment_method_details,
+ validate_payment_method_details_input,
+)
class TransactionCreateInput(BaseInputObjectType):
@@ -73,6 +81,11 @@ class TransactionCreateInput(BaseInputObjectType):
"payment provider page with transaction event details."
)
)
+ payment_method_details = PaymentMethodDetailsInput(
+ description="Details of the payment method used for the transaction."
+ + ADDED_IN_322,
+ required=False,
+ )
class Meta:
doc_category = DOC_CATEGORY_PAYMENTS
@@ -251,13 +264,23 @@ class TransactionCreate(BaseMutation):
transaction.get("external_url"),
error_code=TransactionCreateErrorCode.INVALID.value,
)
+ if payment_method_details := transaction.get("payment_method_details"):
+ validate_payment_method_details_input(
+ payment_method_details, TransactionCreateErrorCode
+ )
+
if "available_actions" in transaction and not transaction["available_actions"]:
transaction.pop("available_actions")
return instance
@classmethod
def create_transaction(
- cls, transaction_input: dict, user, app, save: bool = True
+ cls,
+ transaction_input: dict,
+ user,
+ app,
+ save: bool = True,
+ payment_details_data: PaymentMethodDetails | None = None,
) -> payment_models.TransactionItem:
app_identifier = None
if app and app.identifier:
@@ -275,6 +298,10 @@ class TransactionCreate(BaseMutation):
app_identifier=app_identifier,
app=app,
)
+ if payment_details_data:
+ update_transaction_item_with_payment_method_details(
+ transaction, payment_details_data
+ )
cls.cleanup_and_update_metadata_data(transaction, metadata, private_metadata)
if save:
transaction.save()
@@ -355,6 +382,10 @@ class TransactionCreate(BaseMutation):
order_or_checkout_instance = cls.validate_input(
order_or_checkout_instance, transaction=transaction
)
+ payment_details_data: PaymentMethodDetails | None = None
+ if payment_method_details := transaction.pop("payment_method_details", None):
+ payment_details_data = get_payment_method_details(payment_method_details)
+
transaction_data = {**transaction}
currency = order_or_checkout_instance.currency
transaction_data["currency"] = currency
@@ -375,7 +406,12 @@ class TransactionCreate(BaseMutation):
message=transaction_event.get("message", ""),
)
money_data = cls.get_money_data_from_input(transaction_data, currency)
- new_transaction = cls.create_transaction(transaction_data, user=user, app=app)
+ new_transaction = cls.create_transaction(
+ transaction_data,
+ user=user,
+ app=app,
+ payment_details_data=payment_details_data,
+ )
if money_data:
create_manual_adjustment_events(
transaction=new_transaction, money_data=money_data, user=user, app=app
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py b/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
index 8c1b09fe50..cca890fc0f 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
@@ -24,6 +24,7 @@ from .....order.utils import (
)
from .....payment import OPTIONAL_AMOUNT_EVENTS, TransactionEventType
from .....payment import models as payment_models
+from .....payment.interface import PaymentMethodDetails
from .....payment.transaction_item_calculations import recalculate_transaction_amounts
from .....payment.utils import (
authorization_success_already_exists,
@@ -31,12 +32,14 @@ from .....payment.utils import (
get_already_existing_event,
get_transaction_event_amount,
truncate_transaction_event_message,
+ update_transaction_item_with_payment_method_details,
)
from .....permission.auth_filters import AuthorizationFilters
from .....permission.enums import PaymentPermissions
from .....webhook.event_types import WebhookEventAsyncType
from ....app.dataloaders import get_app_promise
from ....core import ResolveInfo
+from ....core.descriptions import ADDED_IN_322
from ....core.doc_category import DOC_CATEGORY_PAYMENTS
from ....core.enums import TransactionEventReportErrorCode
from ....core.mutations import DeprecatedModelMutation
@@ -50,6 +53,11 @@ from ....plugins.dataloaders import get_plugin_manager_promise
from ...enums import TransactionActionEnum, TransactionEventTypeEnum
from ...types import TransactionEvent, TransactionItem
from ...utils import check_if_requestor_has_access
+from .shared import (
+ PaymentMethodDetailsInput,
+ get_payment_method_details,
+ validate_payment_method_details_input,
+)
from .utils import get_transaction_item
if TYPE_CHECKING:
@@ -137,6 +145,11 @@ class TransactionEventReport(DeprecatedModelMutation):
f"\n\n{MetadataInputDescription.PRIVATE_METADATA_INPUT}",
required=False,
)
+ payment_method_details = PaymentMethodDetailsInput(
+ description="Details of the payment method used for the transaction."
+ + ADDED_IN_322,
+ required=False,
+ )
class Meta:
description = (
@@ -192,6 +205,7 @@ class TransactionEventReport(DeprecatedModelMutation):
app: Optional["App"] = None,
metadata: list[MetadataInput] | None = None,
private_metadata: list[MetadataInput] | None = None,
+ payment_details_data: PaymentMethodDetails | None = None,
):
fields_to_update = [
"authorized_value",
@@ -224,6 +238,13 @@ class TransactionEventReport(DeprecatedModelMutation):
transaction.available_actions = available_actions
fields_to_update.append("available_actions")
+ if payment_details_data:
+ fields_to_update.extend(
+ update_transaction_item_with_payment_method_details(
+ transaction, payment_details_data
+ )
+ )
+
recalculate_transaction_amounts(transaction, save=False)
transaction_has_assigned_app = transaction.app_id or transaction.app_identifier
if app and not transaction.user_id and not transaction_has_assigned_app:
@@ -377,6 +398,7 @@ class TransactionEventReport(DeprecatedModelMutation):
available_actions=None,
transaction_metadata: list[MetadataInput] | None = None,
transaction_private_metadata: list[MetadataInput] | None = None,
+ payment_method_details: PaymentMethodDetailsInput | None = None,
):
validate_one_of_args_is_in_mutation("id", id, "token", token)
transaction = get_transaction_item(id, token)
@@ -407,6 +429,13 @@ class TransactionEventReport(DeprecatedModelMutation):
psp_reference, transaction
)
+ payment_details_data: PaymentMethodDetails | None = None
+ if payment_method_details:
+ validate_payment_method_details_input(
+ payment_method_details, TransactionEventReportErrorCode
+ )
+ payment_details_data = get_payment_method_details(payment_method_details)
+
message = (
truncate_transaction_event_message(message) if message is not None else ""
)
@@ -504,6 +533,7 @@ class TransactionEventReport(DeprecatedModelMutation):
app=app,
metadata=transaction_metadata,
private_metadata=transaction_private_metadata,
+ payment_details_data=payment_details_data,
)
cls.process_order_or_checkout_with_transaction(
transaction,
@@ -515,11 +545,22 @@ class TransactionEventReport(DeprecatedModelMutation):
previous_refunded_value,
related_granted_refund,
)
- elif available_actions is not None and set(
- transaction.available_actions
- ) != set(available_actions):
- transaction.available_actions = available_actions
- transaction.save(update_fields=["available_actions"])
+ else:
+ updated_fields = []
+ if available_actions is not None and set(
+ transaction.available_actions
+ ) != set(available_actions):
+ transaction.available_actions = available_actions
+ updated_fields.append("available_actions")
+
+ if payment_details_data:
+ updated_fields.extend(
+ update_transaction_item_with_payment_method_details(
+ transaction, payment_details_data
+ )
+ )
+ if updated_fields:
+ transaction.save(update_fields=updated_fields)
return cls(
already_processed=already_processed,
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_update.py b/saleor/graphql/payment/mutations/transaction/transaction_update.py
index 67f104e025..c7205974b6 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_update.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_update.py
@@ -15,11 +15,15 @@ from .....payment.error_codes import (
TransactionCreateErrorCode,
TransactionUpdateErrorCode,
)
+from .....payment.interface import PaymentMethodDetails
from .....payment.transaction_item_calculations import (
calculate_transaction_amount_based_on_events,
recalculate_transaction_amounts,
)
-from .....payment.utils import create_manual_adjustment_events
+from .....payment.utils import (
+ create_manual_adjustment_events,
+ update_transaction_item_with_payment_method_details,
+)
from .....permission.auth_filters import AuthorizationFilters
from .....permission.enums import PaymentPermissions
from ....app.dataloaders import get_app_promise
@@ -31,6 +35,7 @@ from ....core.validators import validate_one_of_args_is_in_mutation
from ....plugins.dataloaders import get_plugin_manager_promise
from ...types import TransactionItem
from ...utils import check_if_requestor_has_access
+from .shared import get_payment_method_details, validate_payment_method_details_input
from .transaction_create import (
TransactionCreate,
TransactionCreateInput,
@@ -131,6 +136,10 @@ class TransactionUpdate(TransactionCreate):
transaction_data.get("external_url"),
error_code=TransactionCreateErrorCode.INVALID.value,
)
+ if payment_method_details := transaction_data.get("payment_method_details"):
+ validate_payment_method_details_input(
+ payment_method_details, TransactionUpdateErrorCode
+ )
@classmethod
def update_transaction(
@@ -140,6 +149,7 @@ class TransactionUpdate(TransactionCreate):
money_data: dict,
user: Optional["User"],
app: Optional["App"],
+ payment_details_data: PaymentMethodDetails | None = None,
):
psp_reference = transaction_data.get("psp_reference")
if psp_reference and instance.psp_reference != psp_reference:
@@ -155,6 +165,10 @@ class TransactionUpdate(TransactionCreate):
}
)
instance = cls.construct_instance(instance, transaction_data)
+ if payment_details_data:
+ update_transaction_item_with_payment_method_details(
+ instance, payment_details_data
+ )
instance.save()
if money_data:
calculate_transaction_amount_based_on_events(transaction=instance)
@@ -218,7 +232,21 @@ class TransactionUpdate(TransactionCreate):
transaction.pop("private_metadata", None),
)
money_data = cls.get_money_data_from_input(transaction, instance.currency)
- cls.update_transaction(instance, transaction, money_data, user, app)
+ payment_details_data: PaymentMethodDetails | None = None
+ if payment_method_details := transaction.pop(
+ "payment_method_details", None
+ ):
+ payment_details_data = get_payment_method_details(
+ payment_method_details
+ )
+ cls.update_transaction(
+ instance,
+ transaction,
+ money_data,
+ user,
+ app,
+ payment_details_data=payment_details_data,
+ )
event = None
if transaction_event:
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_create.py b/saleor/graphql/payment/tests/mutations/test_transaction_create.py
index 3af8c9139e..006135db18 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_create.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_create.py
@@ -12,7 +12,7 @@ from .....checkout.models import Checkout
from .....order import OrderAuthorizeStatus, OrderChargeStatus, OrderEvents, OrderStatus
from .....order.models import Order
from .....order.utils import update_order_authorize_data, update_order_charge_data
-from .....payment import TransactionEventType
+from .....payment import PaymentMethodType, TransactionEventType
from .....payment.error_codes import TransactionCreateErrorCode
from .....payment.models import TransactionItem
from ....core.utils import to_global_id_or_none
@@ -63,6 +63,21 @@ mutation TransactionCreate(
id
}
}
+ paymentMethodDetails{
+ ...on CardPaymentMethodDetails{
+ __typename
+ name
+ brand
+ firstDigits
+ lastDigits
+ expMonth
+ expYear
+ }
+ ...on OtherPaymentMethodDetails{
+ __typename
+ name
+ }
+ }
events{
pspReference
message
@@ -2466,3 +2481,307 @@ def test_transaction_create_create_event_message_is_empty(
event = transaction.events.last()
assert event.message == ""
assert event.psp_reference == transaction_reference
+
+
+ (
+ "card_brand",
+ "card_first_digits",
+ "card_last_digits",
+ "card_exp_month",
+ "card_exp_year",
+ ),
+ [
+ ("Brand", "1234", "5678", 12, 2025),
+ (None, "1111", "0000", 1, 2001),
+ (None, None, None, None, None),
+ ("", "", "", None, None),
+ (None, None, "1234", None, None),
+ ],
+)
+def test_transaction_create_with_card_payment_method_details(
+ card_brand,
+ card_first_digits,
+ card_last_digits,
+ card_exp_month,
+ card_exp_year,
+ order_with_lines,
+ permission_manage_payments,
+ app_api_client,
+):
+ # given
+ name = "Credit Card"
+ psp_reference = "PSP reference - 123"
+
+ authorized_value = Decimal("10")
+
+ card_name = "Payment Method Name"
+
+ variables = {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "transaction": {
+ "name": name,
+ "pspReference": psp_reference,
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ "paymentMethodDetails": {
+ "card": {
+ "name": card_name,
+ "brand": card_brand,
+ "firstDigits": card_first_digits,
+ "lastDigits": card_last_digits,
+ "expMonth": card_exp_month,
+ "expYear": card_exp_year,
+ }
+ },
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ transaction = order_with_lines.payment_transactions.first()
+ content = get_graphql_content(response)
+ transaction_data = content["data"]["transactionCreate"]["transaction"]
+ assert transaction_data
+ assert not content["data"]["transactionCreate"]["errors"]
+
+ payment_method_details_data = transaction_data["paymentMethodDetails"]
+ assert payment_method_details_data["__typename"] == "CardPaymentMethodDetails"
+ assert payment_method_details_data["name"] == card_name
+ assert payment_method_details_data["brand"] == card_brand
+ assert payment_method_details_data["firstDigits"] == card_first_digits
+ assert payment_method_details_data["lastDigits"] == card_last_digits
+ assert payment_method_details_data["expMonth"] == card_exp_month
+ assert payment_method_details_data["expYear"] == card_exp_year
+
+ assert transaction.payment_method_type == PaymentMethodType.CARD
+ assert transaction.payment_method_name == card_name
+ assert transaction.cc_brand == card_brand
+ assert transaction.cc_first_digits == card_first_digits
+ assert transaction.cc_last_digits == card_last_digits
+ assert transaction.cc_exp_month == card_exp_month
+ assert transaction.cc_exp_year == card_exp_year
+
+
+def test_transaction_create_with_other_payment_method_details(
+ order_with_lines,
+ permission_manage_payments,
+ app_api_client,
+):
+ # given
+ name = "Credit Card"
+ psp_reference = "PSP reference - 123"
+
+ authorized_value = Decimal("10")
+
+ other_name = "Payment Method Name"
+
+ variables = {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "transaction": {
+ "name": name,
+ "pspReference": psp_reference,
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ "paymentMethodDetails": {
+ "other": {
+ "name": other_name,
+ }
+ },
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ transaction = order_with_lines.payment_transactions.first()
+ content = get_graphql_content(response)
+ transaction_data = content["data"]["transactionCreate"]["transaction"]
+ assert transaction_data
+ assert not content["data"]["transactionCreate"]["errors"]
+
+ payment_method_details_data = transaction_data["paymentMethodDetails"]
+ assert payment_method_details_data["__typename"] == "OtherPaymentMethodDetails"
+ assert payment_method_details_data["name"] == other_name
+
+ transaction.refresh_from_db()
+ assert transaction.payment_method_type == PaymentMethodType.OTHER
+ assert transaction.payment_method_name == other_name
+ assert transaction.cc_brand is None
+ assert transaction.cc_first_digits is None
+ assert transaction.cc_last_digits is None
+ assert transaction.cc_exp_month is None
+ assert transaction.cc_exp_year is None
+
+
+def test_transaction_create_with_both_payment_method_details_inputs(
+ order_with_lines,
+ permission_manage_payments,
+ app_api_client,
+):
+ # given
+ name = "Credit Card"
+ psp_reference = "PSP reference - 123"
+
+ authorized_value = Decimal("10")
+
+ variables = {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "transaction": {
+ "name": name,
+ "pspReference": psp_reference,
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ "paymentMethodDetails": {
+ "other": {
+ "name": "Other",
+ },
+ "card": {
+ "name": "Name",
+ },
+ },
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ response = get_graphql_content(response)
+ transaction_data = response["data"]["transactionCreate"]
+ assert transaction_data["errors"]
+ assert len(transaction_data["errors"]) == 1
+ assert transaction_data["errors"][0]["code"] == "INVALID"
+
+
+ (
+ "card_brand_length",
+ "card_first_digits",
+ "card_last_digits",
+ "card_exp_month",
+ "card_exp_year",
+ "card_name_length",
+ ),
+ [
+ (41, "12345", "56780", 33, 12025, 257),
+ (41, None, None, None, None, None),
+ (None, "12345", None, None, None, None),
+ (None, None, "56780", None, None, None),
+ (None, None, None, 33, None, None),
+ (None, None, None, None, 12025, None),
+ (None, None, None, None, None, 257),
+ ],
+)
+def test_transaction_create_with_invalid_card_payment_method_details(
+ card_brand_length,
+ card_first_digits,
+ card_last_digits,
+ card_exp_month,
+ card_exp_year,
+ card_name_length,
+ order_with_lines,
+ permission_manage_payments,
+ app_api_client,
+):
+ # given
+ name = "Credit Card"
+ psp_reference = "PSP reference - 123"
+
+ authorized_value = Decimal("10")
+
+ variables = {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "transaction": {
+ "name": name,
+ "pspReference": psp_reference,
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ "paymentMethodDetails": {
+ "card": {
+ "name": "N" * (card_name_length or 0),
+ "brand": "B" * (card_brand_length or 0),
+ "firstDigits": card_first_digits,
+ "lastDigits": card_last_digits,
+ "expMonth": card_exp_month,
+ "expYear": card_exp_year,
+ }
+ },
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ response = get_graphql_content(response)
+ transaction_data = response["data"]["transactionCreate"]
+ assert transaction_data["errors"]
+
+ for error in transaction_data["errors"]:
+ assert error["code"] == "INVALID"
+ assert error["field"] == "paymentMethodDetails"
+
+
+def test_transaction_create_with_invalid_other_payment_method_details(
+ order_with_lines,
+ permission_manage_payments,
+ app_api_client,
+):
+ # given
+ name = "Credit Card"
+ psp_reference = "PSP reference - 123"
+
+ authorized_value = Decimal("10")
+
+ other_name = "Payment Method Name"
+
+ variables = {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "transaction": {
+ "name": name,
+ "pspReference": psp_reference,
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ "paymentMethodDetails": {
+ "other": {
+ "name": other_name * 256,
+ }
+ },
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ response = get_graphql_content(response)
+ transaction_data = response["data"]["transactionCreate"]
+ assert transaction_data["errors"]
+ assert len(transaction_data["errors"]) == 1
+ error = transaction_data["errors"][0]
+ assert error["code"] == "INVALID"
+ assert error["field"] == "paymentMethodDetails"
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
index b98babb654..34d131ede3 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
@@ -17,7 +17,7 @@ from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.models import Checkout
from .....order import OrderEvents, OrderGrantedRefundStatus, OrderStatus
from .....order.models import Order
-from .....payment import OPTIONAL_AMOUNT_EVENTS, TransactionEventType
+from .....payment import OPTIONAL_AMOUNT_EVENTS, PaymentMethodType, TransactionEventType
from .....payment.models import TransactionEvent
from .....payment.transaction_item_calculations import recalculate_transaction_amounts
from .....tests import race_condition
@@ -55,6 +55,21 @@ fragment TransactionEventData on TransactionEventReport {
key
value
}
+ paymentMethodDetails{
+ ...on CardPaymentMethodDetails{
+ __typename
+ name
+ brand
+ firstDigits
+ lastDigits
+ expMonth
+ expYear
+ }
+ ...on OtherPaymentMethodDetails{
+ __typename
+ name
+ }
+ }
}
transactionEvent {
id
@@ -68,16 +83,17 @@ fragment TransactionEventData on TransactionEventReport {
}
type
createdBy {
- ... on User {
- id
- }
- ... on App {
- id
- }
+ ... on User {
+ id
+ }
+ ... on App {
+ id
+ }
}
}
errors {
field
+ message
code
}
}
@@ -3538,3 +3554,464 @@ def test_transaction_event_report_checkout_completed_race_condition(
assert order.status == OrderStatus.UNFULFILLED
assert order.charge_status == OrderChargeStatusEnum.FULL.value
assert order.total_charged.amount == checkout.total.gross.amount
+
+
+TRANSACTION_EVENT_REPORT_WITH_CARD_PAYMENT_METHOD_DETAILS_QUERY = (
+ MUTATION_DATA_FRAGMENT
+ + """
+ mutation TransactionEventReport(
+ $id: ID
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ $paymentMethodDetails: PaymentMethodDetailsInput
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ paymentMethodDetails: $paymentMethodDetails
+ ) {
+ ...TransactionEventData
+ }
+ }
+ """
+)
+
+
+ (
+ "card_brand",
+ "card_first_digits",
+ "card_last_digits",
+ "card_exp_month",
+ "card_exp_year",
+ ),
+ [
+ ("Brand", "1234", "5678", 12, 2025),
+ (None, "1111", "0000", 1, 2001),
+ (None, None, None, None, None),
+ ("", "", "", None, None),
+ (None, None, "1234", None, None),
+ ],
+)
+def test_transaction_event_report_with_card_payment_method_details(
+ card_brand,
+ card_first_digits,
+ card_last_digits,
+ card_exp_month,
+ card_exp_year,
+ transaction_item_generator,
+ app_api_client,
+ permission_manage_payments,
+):
+ # given
+ transaction = transaction_item_generator(
+ app=app_api_client.app, authorized_value=Decimal("10")
+ )
+ transaction.payment_method_type = PaymentMethodType.CARD
+ transaction.payment_method_name = "Payment Method Name"
+ transaction.cc_brand = None
+ transaction.cc_first_digits = "1111"
+ transaction.cc_last_digits = "0000"
+ transaction.cc_exp_month = 6
+ transaction.cc_exp_year = 2010
+ transaction.save()
+
+ psp_reference = "111-abc"
+ amount = Decimal("11.00")
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
+
+ card_name = "Payment Method Name"
+
+ variables = {
+ "id": transaction_id,
+ "type": TransactionEventTypeEnum.CHARGE_SUCCESS.name,
+ "amount": amount,
+ "pspReference": psp_reference,
+ "paymentMethodDetails": {
+ "card": {
+ "name": card_name,
+ "brand": card_brand,
+ "firstDigits": card_first_digits,
+ "lastDigits": card_last_digits,
+ "expMonth": card_exp_month,
+ "expYear": card_exp_year,
+ }
+ },
+ }
+ # when
+ response = app_api_client.post_graphql(
+ TRANSACTION_EVENT_REPORT_WITH_CARD_PAYMENT_METHOD_DETAILS_QUERY,
+ variables,
+ permissions=[permission_manage_payments],
+ )
+
+ # then
+ response = get_graphql_content(response)
+ transaction_report_data = response["data"]["transactionEventReport"]
+ assert not transaction_report_data["errors"]
+
+ transaction_data = transaction_report_data["transaction"]
+ assert transaction_data
+ payment_method_details_data = transaction_data["paymentMethodDetails"]
+ assert payment_method_details_data["__typename"] == "CardPaymentMethodDetails"
+ assert payment_method_details_data["name"] == card_name
+ assert payment_method_details_data["brand"] == card_brand
+ assert payment_method_details_data["firstDigits"] == card_first_digits
+ assert payment_method_details_data["lastDigits"] == card_last_digits
+ assert payment_method_details_data["expMonth"] == card_exp_month
+ assert payment_method_details_data["expYear"] == card_exp_year
+
+ transaction.refresh_from_db()
+ assert transaction.payment_method_type == PaymentMethodType.CARD
+ assert transaction.payment_method_name == card_name
+ assert transaction.cc_brand == card_brand
+ assert transaction.cc_first_digits == card_first_digits
+ assert transaction.cc_last_digits == card_last_digits
+ assert transaction.cc_exp_month == card_exp_month
+ assert transaction.cc_exp_year == card_exp_year
+
+
+def test_transaction_event_report_with_other_payment_method_details(
+ transaction_item_generator,
+ app_api_client,
+ permission_manage_payments,
+):
+ # given
+ transaction = transaction_item_generator(
+ app=app_api_client.app, authorized_value=Decimal("10")
+ )
+ transaction.payment_method_type = PaymentMethodType.CARD
+ transaction.payment_method_name = "Payment Method Name"
+ transaction.cc_brand = None
+ transaction.cc_first_digits = "1111"
+ transaction.cc_last_digits = "0000"
+ transaction.cc_exp_month = 6
+ transaction.cc_exp_year = 2010
+ transaction.save()
+
+ psp_reference = "111-abc"
+ amount = Decimal("11.00")
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
+
+ other_name = "Payment Method Name"
+
+ variables = {
+ "id": transaction_id,
+ "type": TransactionEventTypeEnum.CHARGE_SUCCESS.name,
+ "amount": amount,
+ "pspReference": psp_reference,
+ "paymentMethodDetails": {
+ "other": {
+ "name": other_name,
+ }
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ TRANSACTION_EVENT_REPORT_WITH_CARD_PAYMENT_METHOD_DETAILS_QUERY,
+ variables,
+ permissions=[permission_manage_payments],
+ )
+
+ # then
+ response = get_graphql_content(response)
+ transaction_report_data = response["data"]["transactionEventReport"]
+ assert not transaction_report_data["errors"]
+
+ transaction_data = transaction_report_data["transaction"]
+ assert transaction_data
+
+ payment_method_details_data = transaction_data["paymentMethodDetails"]
+ assert payment_method_details_data["__typename"] == "OtherPaymentMethodDetails"
+ assert payment_method_details_data["name"] == other_name
+
+ transaction.refresh_from_db()
+ assert transaction.payment_method_type == PaymentMethodType.OTHER
+ assert transaction.payment_method_name == other_name
+ assert transaction.cc_brand is None
+ assert transaction.cc_first_digits is None
+ assert transaction.cc_last_digits is None
+ assert transaction.cc_exp_month is None
+ assert transaction.cc_exp_year is None
+
+
+def test_transaction_event_report_with_both_payment_method_details_inputs(
+ transaction_item_generator,
+ app_api_client,
+ permission_manage_payments,
+):
+ # given
+ transaction = transaction_item_generator(
+ app=app_api_client.app, authorized_value=Decimal("10")
+ )
+
+ psp_reference = "111-abc"
+ amount = Decimal("11.00")
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
+
+ variables = {
+ "id": transaction_id,
+ "type": TransactionEventTypeEnum.CHARGE_SUCCESS.name,
+ "amount": amount,
+ "pspReference": psp_reference,
+ "paymentMethodDetails": {
+ "other": {
+ "name": "Other",
+ },
+ "card": {
+ "name": "Name",
+ },
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ TRANSACTION_EVENT_REPORT_WITH_CARD_PAYMENT_METHOD_DETAILS_QUERY,
+ variables,
+ permissions=[permission_manage_payments],
+ )
+
+ # then
+ response = get_graphql_content(response)
+ transaction_report_data = response["data"]["transactionEventReport"]
+ assert transaction_report_data["errors"]
+ assert len(transaction_report_data["errors"]) == 1
+ assert transaction_report_data["errors"][0]["code"] == "INVALID"
+
+
+ (
+ "card_brand_length",
+ "card_first_digits",
+ "card_last_digits",
+ "card_exp_month",
+ "card_exp_year",
+ "card_name_length",
+ ),
+ [
+ (41, "12345", "56780", 33, 12025, 257),
+ (41, None, None, None, None, None),
+ (None, "12345", None, None, None, None),
+ (None, None, "56780", None, None, None),
+ (None, None, None, 33, None, None),
+ (None, None, None, None, 12025, None),
+ (None, None, None, None, None, 257),
+ ],
+)
+def test_transaction_event_report_with_invalid_card_payment_method_details(
+ card_brand_length,
+ card_first_digits,
+ card_last_digits,
+ card_exp_month,
+ card_exp_year,
+ card_name_length,
+ transaction_item_generator,
+ app_api_client,
+ permission_manage_payments,
+):
+ # given
+ transaction = transaction_item_generator(
+ app=app_api_client.app, authorized_value=Decimal("10")
+ )
+
+ psp_reference = "111-abc"
+ amount = Decimal("11.00")
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
+
+ variables = {
+ "id": transaction_id,
+ "type": TransactionEventTypeEnum.CHARGE_SUCCESS.name,
+ "amount": amount,
+ "pspReference": psp_reference,
+ "paymentMethodDetails": {
+ "card": {
+ "name": "N" * (card_name_length or 0),
+ "brand": "B" * (card_brand_length or 0),
+ "firstDigits": card_first_digits,
+ "lastDigits": card_last_digits,
+ "expMonth": card_exp_month,
+ "expYear": card_exp_year,
+ }
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ TRANSACTION_EVENT_REPORT_WITH_CARD_PAYMENT_METHOD_DETAILS_QUERY,
+ variables,
+ permissions=[permission_manage_payments],
+ )
+
+ # then
+ response = get_graphql_content(response)
+ transaction_report_data = response["data"]["transactionEventReport"]
+ assert transaction_report_data["errors"]
+
+ for error in transaction_report_data["errors"]:
+ assert error["code"] == "INVALID"
+ assert error["field"] == "paymentMethodDetails"
+
+
+def test_transaction_event_report_with_invalid_other_payment_method_details(
+ transaction_item_generator,
+ app_api_client,
+ permission_manage_payments,
+):
+ # given
+ transaction = transaction_item_generator(
+ app=app_api_client.app, authorized_value=Decimal("10")
+ )
+
+ psp_reference = "111-abc"
+ amount = Decimal("11.00")
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
+
+ variables = {
+ "id": transaction_id,
+ "type": TransactionEventTypeEnum.CHARGE_SUCCESS.name,
+ "amount": amount,
+ "pspReference": psp_reference,
+ "paymentMethodDetails": {
+ "other": {
+ "name": "N" * 257,
+ }
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ TRANSACTION_EVENT_REPORT_WITH_CARD_PAYMENT_METHOD_DETAILS_QUERY,
+ variables,
+ permissions=[permission_manage_payments],
+ )
+
+ # then
+ response = get_graphql_content(response)
+ transaction_report_data = response["data"]["transactionEventReport"]
+ assert transaction_report_data["errors"]
+ assert len(transaction_report_data["errors"]) == 1
+ error = transaction_report_data["errors"][0]
+ assert error["code"] == "INVALID"
+ assert error["field"] == "paymentMethodDetails"
+
+
+def test_transaction_event_report_event_already_exists_updates_card_payment_method_details(
+ transaction_item_generator, app_api_client, permission_manage_payments, app
+):
+ # given
+ card_name = "Name"
+ card_brand = "Brand"
+ card_first_digits = "1234"
+ card_last_digits = "5678"
+ card_exp_month = 12
+ card_exp_year = 2025
+
+ psp_reference = "111-abc"
+ amount = Decimal("11.00")
+ event_type = TransactionEventTypeEnum.CHARGE_SUCCESS
+ transaction = transaction_item_generator(app=app, charged_value=amount)
+ transaction.events.update(
+ psp_reference=psp_reference,
+ )
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
+ variables = {
+ "id": transaction_id,
+ "type": event_type.name,
+ "amount": amount,
+ "pspReference": psp_reference,
+ "paymentMethodDetails": {
+ "card": {
+ "name": card_name,
+ "brand": card_brand,
+ "firstDigits": card_first_digits,
+ "lastDigits": card_last_digits,
+ "expMonth": card_exp_month,
+ "expYear": card_exp_year,
+ },
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ TRANSACTION_EVENT_REPORT_WITH_CARD_PAYMENT_METHOD_DETAILS_QUERY,
+ variables,
+ permissions=[permission_manage_payments],
+ )
+
+ # then
+ transaction.refresh_from_db()
+ response = get_graphql_content(response)
+ assert not response["data"]["transactionEventReport"]["errors"]
+ transaction_report_data = response["data"]["transactionEventReport"]
+ transaction_data = transaction_report_data["transaction"]
+ assert transaction_data
+ payment_method_details_data = transaction_data["paymentMethodDetails"]
+ assert payment_method_details_data["__typename"] == "CardPaymentMethodDetails"
+ assert payment_method_details_data["name"] == card_name
+ assert payment_method_details_data["brand"] == card_brand
+ assert payment_method_details_data["firstDigits"] == card_first_digits
+ assert payment_method_details_data["lastDigits"] == card_last_digits
+ assert payment_method_details_data["expMonth"] == card_exp_month
+ assert payment_method_details_data["expYear"] == card_exp_year
+
+ transaction.refresh_from_db()
+ assert transaction.payment_method_type == PaymentMethodType.CARD
+ assert transaction.payment_method_name == card_name
+ assert transaction.cc_brand == card_brand
+ assert transaction.cc_first_digits == card_first_digits
+ assert transaction.cc_last_digits == card_last_digits
+ assert transaction.cc_exp_month == card_exp_month
+ assert transaction.cc_exp_year == card_exp_year
+
+
+def test_transaction_event_report_event_already_exists_updates_other_payment_method_details(
+ transaction_item_generator, app_api_client, permission_manage_payments, app
+):
+ # given
+ payment_method_name = "Payment Method Name"
+
+ psp_reference = "111-abc"
+ amount = Decimal("11.00")
+ event_type = TransactionEventTypeEnum.CHARGE_SUCCESS
+ transaction = transaction_item_generator(app=app, charged_value=amount)
+ transaction.events.update(
+ psp_reference=psp_reference,
+ )
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
+ variables = {
+ "id": transaction_id,
+ "type": event_type.name,
+ "amount": amount,
+ "pspReference": psp_reference,
+ "paymentMethodDetails": {
+ "other": {
+ "name": payment_method_name,
+ },
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ TRANSACTION_EVENT_REPORT_WITH_CARD_PAYMENT_METHOD_DETAILS_QUERY,
+ variables,
+ permissions=[permission_manage_payments],
+ )
+
+ # then
+ transaction.refresh_from_db()
+ response = get_graphql_content(response)
+ assert not response["data"]["transactionEventReport"]["errors"]
+ transaction_report_data = response["data"]["transactionEventReport"]
+ transaction_data = transaction_report_data["transaction"]
+ assert transaction_data
+ payment_method_details_data = transaction_data["paymentMethodDetails"]
+ assert payment_method_details_data["__typename"] == "OtherPaymentMethodDetails"
+ assert payment_method_details_data["name"] == payment_method_name
+
+ transaction.refresh_from_db()
+ assert transaction.payment_method_type == PaymentMethodType.OTHER
+ assert transaction.payment_method_name == payment_method_name
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_update.py b/saleor/graphql/payment/tests/mutations/test_transaction_update.py
index d37a8b5e33..2154629511 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_update.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_update.py
@@ -11,7 +11,7 @@ from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.models import Checkout
from .....order import OrderAuthorizeStatus, OrderChargeStatus, OrderEvents, OrderStatus
from .....order.models import Order
-from .....payment import TransactionEventType
+from .....payment import PaymentMethodType, TransactionEventType
from .....payment.error_codes import TransactionUpdateErrorCode
from .....payment.models import TransactionEvent, TransactionItem
from .....payment.transaction_item_calculations import recalculate_transaction_amounts
@@ -73,6 +73,21 @@ mutation TransactionUpdate(
id
}
}
+ paymentMethodDetails{
+ ...on CardPaymentMethodDetails{
+ __typename
+ name
+ brand
+ firstDigits
+ lastDigits
+ expMonth
+ expYear
+ }
+ ...on OtherPaymentMethodDetails{
+ __typename
+ name
+ }
+ }
events{
pspReference
message
@@ -3468,3 +3483,269 @@ def test_transaction_uodate_transaction_event_empty_message(
event = transaction.events.last()
assert event.message == ""
assert event.psp_reference == transaction_reference
+
+
+ (
+ "card_brand",
+ "card_first_digits",
+ "card_last_digits",
+ "card_exp_month",
+ "card_exp_year",
+ ),
+ [
+ ("Brand", "1234", "5678", 12, 2025),
+ (None, "1111", "0000", 1, 2001),
+ (None, None, None, None, None),
+ ("", "", "", None, None),
+ (None, None, "1234", None, None),
+ ],
+)
+def test_transaction_update_with_card_payment_method_details(
+ card_brand,
+ card_first_digits,
+ card_last_digits,
+ card_exp_month,
+ card_exp_year,
+ transaction_item_created_by_app,
+ permission_manage_payments,
+ app_api_client,
+):
+ # given
+ transaction = transaction_item_created_by_app
+ transaction.payment_method_type = PaymentMethodType.CARD
+ transaction.payment_method_name = "Payment Method Name"
+ transaction.cc_brand = None
+ transaction.cc_first_digits = "9999"
+ transaction.cc_last_digits = "8888"
+ transaction.cc_exp_month = 6
+ transaction.cc_exp_year = 2010
+ transaction.save()
+
+ card_name = "Payment Method Name"
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "transaction": {
+ "paymentMethodDetails": {
+ "card": {
+ "name": card_name,
+ "brand": card_brand,
+ "firstDigits": card_first_digits,
+ "lastDigits": card_last_digits,
+ "expMonth": card_exp_month,
+ "expYear": card_exp_year,
+ }
+ },
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ transaction.refresh_from_db()
+ content = get_graphql_content(response)
+ transaction_data = content["data"]["transactionUpdate"]["transaction"]
+
+ payment_method_details_data = transaction_data["paymentMethodDetails"]
+ assert payment_method_details_data["__typename"] == "CardPaymentMethodDetails"
+ assert payment_method_details_data["name"] == card_name
+ assert payment_method_details_data["brand"] == card_brand
+ assert payment_method_details_data["firstDigits"] == card_first_digits
+ assert payment_method_details_data["lastDigits"] == card_last_digits
+ assert payment_method_details_data["expMonth"] == card_exp_month
+ assert payment_method_details_data["expYear"] == card_exp_year
+
+ assert transaction.payment_method_type == PaymentMethodType.CARD
+ assert transaction.payment_method_name == card_name
+ assert transaction.cc_brand == card_brand
+ assert transaction.cc_first_digits == card_first_digits
+ assert transaction.cc_last_digits == card_last_digits
+ assert transaction.cc_exp_month == card_exp_month
+ assert transaction.cc_exp_year == card_exp_year
+
+
+def test_transaction_update_with_other_payment_method_details(
+ transaction_item_created_by_app, permission_manage_payments, app_api_client
+):
+ # given
+ transaction = transaction_item_created_by_app
+ transaction.payment_method_type = PaymentMethodType.CARD
+ transaction.payment_method_name = "Payment Method Name"
+ transaction.cc_brand = None
+ transaction.cc_first_digits = "9999"
+ transaction.cc_last_digits = "8888"
+ transaction.cc_exp_month = 6
+ transaction.cc_exp_year = 2010
+ transaction.save()
+
+ other_name = "Payment Method Name"
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "transaction": {
+ "paymentMethodDetails": {
+ "other": {
+ "name": other_name,
+ }
+ },
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ transaction.refresh_from_db()
+ content = get_graphql_content(response)
+ transaction_data = content["data"]["transactionUpdate"]["transaction"]
+ assert transaction_data
+ assert not content["data"]["transactionUpdate"]["errors"]
+
+ payment_method_details_data = transaction_data["paymentMethodDetails"]
+ assert payment_method_details_data["__typename"] == "OtherPaymentMethodDetails"
+ assert payment_method_details_data["name"] == other_name
+
+ transaction.refresh_from_db()
+ assert transaction.payment_method_type == PaymentMethodType.OTHER
+ assert transaction.payment_method_name == other_name
+ assert transaction.cc_brand is None
+ assert transaction.cc_first_digits is None
+ assert transaction.cc_last_digits is None
+ assert transaction.cc_exp_month is None
+ assert transaction.cc_exp_year is None
+
+
+def test_transaction_update_with_both_payment_method_details_inputs(
+ transaction_item_created_by_app, permission_manage_payments, app_api_client
+):
+ # given
+ transaction = transaction_item_created_by_app
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "transaction": {
+ "paymentMethodDetails": {
+ "other": {
+ "name": "Other",
+ },
+ "card": {
+ "name": "Name",
+ },
+ },
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ response = get_graphql_content(response)
+ transaction_data = response["data"]["transactionUpdate"]
+ assert transaction_data["errors"]
+ assert len(transaction_data["errors"]) == 1
+ assert transaction_data["errors"][0]["code"] == "INVALID"
+
+
+ (
+ "card_brand_length",
+ "card_first_digits",
+ "card_last_digits",
+ "card_exp_month",
+ "card_exp_year",
+ "card_name_length",
+ ),
+ [
+ (41, "12345", "56780", 33, 12025, 257),
+ (41, None, None, None, None, None),
+ (None, "12345", None, None, None, None),
+ (None, None, "56780", None, None, None),
+ (None, None, None, 33, None, None),
+ (None, None, None, None, 12025, None),
+ (None, None, None, None, None, 257),
+ ],
+)
+def test_transaction_update_with_invalid_card_payment_method_details(
+ card_brand_length,
+ card_first_digits,
+ card_last_digits,
+ card_exp_month,
+ card_exp_year,
+ card_name_length,
+ transaction_item_created_by_app,
+ permission_manage_payments,
+ app_api_client,
+):
+ # given
+ transaction = transaction_item_created_by_app
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "transaction": {
+ "paymentMethodDetails": {
+ "card": {
+ "name": "N" * (card_name_length or 0),
+ "brand": "B" * (card_brand_length or 0),
+ "firstDigits": card_first_digits,
+ "lastDigits": card_last_digits,
+ "expMonth": card_exp_month,
+ "expYear": card_exp_year,
+ }
+ },
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ response = get_graphql_content(response)
+ transaction_data = response["data"]["transactionUpdate"]
+ assert transaction_data["errors"]
+
+ for error in transaction_data["errors"]:
+ assert error["code"] == "INVALID"
+ assert error["field"] == "paymentMethodDetails"
+
+
+def test_transaction_update_with_invalid_other_payment_method_details(
+ transaction_item_created_by_app,
+ permission_manage_payments,
+ app_api_client,
+):
+ # given
+ transaction = transaction_item_created_by_app
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "transaction": {
+ "paymentMethodDetails": {
+ "other": {
+ "name": "N" * 257,
+ }
+ },
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ response = get_graphql_content(response)
+ transaction_data = response["data"]["transactionUpdate"]
+ assert transaction_data["errors"]
+ assert len(transaction_data["errors"]) == 1
+ error = transaction_data["errors"][0]
+ assert error["code"] == "INVALID"
+ assert error["field"] == "paymentMethodDetails"
diff --git a/saleor/graphql/payment/tests/queries/test_transaction.py b/saleor/graphql/payment/tests/queries/test_transaction.py
index a796b26916..b7f172b282 100644
--- a/saleor/graphql/payment/tests/queries/test_transaction.py
+++ b/saleor/graphql/payment/tests/queries/test_transaction.py
@@ -5,7 +5,7 @@ import pytest
from django.utils import timezone
from freezegun import freeze_time
-from .....payment import TransactionEventType
+from .....payment import PaymentMethodType, TransactionEventType
from .....payment.models import TransactionEvent
from ....core.utils import to_global_id_or_none
from ....tests.utils import (
@@ -92,6 +92,23 @@ TRANSACTION_QUERY = """
id
}
}
+ paymentMethodDetails{
+ __typename
+ ...on GenericPaymentMethodDetails{
+ name
+ }
+ ...on CardPaymentMethodDetails{
+ name
+ brand
+ firstDigits
+ lastDigits
+ expMonth
+ expYear
+ }
+ ...on OtherPaymentMethodDetails{
+ name
+ }
+ }
}
}
"""
@@ -794,3 +811,145 @@ def test_transaction_event_by_app_marked_to_remove(
]
assert event_data["amount"]["currency"] == event.currency
assert event_data["createdBy"]["id"] == to_global_id_or_none(webhook_app)
+
+
+def test_transaction_query_by_app_with_payment_method_card(
+ app_api_client, transaction_item_created_by_app, permission_manage_payments, app
+):
+ # given
+ expected_brand = "Visa"
+ expected_first_digits = "1234"
+ expected_last_digits = "5678"
+ expected_exp_month = 12
+ expected_exp_year = 2025
+
+ transaction_item_created_by_app.payment_method_type = PaymentMethodType.CARD
+ transaction_item_created_by_app.cc_brand = expected_brand
+ transaction_item_created_by_app.cc_first_digits = expected_first_digits
+ transaction_item_created_by_app.cc_last_digits = expected_last_digits
+ transaction_item_created_by_app.cc_exp_month = expected_exp_month
+ transaction_item_created_by_app.cc_exp_year = expected_exp_year
+ transaction_item_created_by_app.save()
+
+ variables = {
+ "id": graphene.Node.to_global_id(
+ "TransactionItem", transaction_item_created_by_app.token
+ )
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ TRANSACTION_QUERY, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["transaction"]
+ assert data["paymentMethodDetails"]["__typename"] == "CardPaymentMethodDetails"
+ assert data["paymentMethodDetails"]["brand"] == expected_brand
+ assert data["paymentMethodDetails"]["firstDigits"] == expected_first_digits
+ assert data["paymentMethodDetails"]["lastDigits"] == expected_last_digits
+ assert data["paymentMethodDetails"]["expMonth"] == expected_exp_month
+ assert data["paymentMethodDetails"]["expYear"] == expected_exp_year
+
+
+def test_transaction_query_by_staff_with_payment_method_card(
+ staff_api_client, transaction_item_created_by_app, permission_manage_payments
+):
+ # given
+ expected_brand = "Visa"
+ expected_first_digits = "1234"
+ expected_last_digits = "5678"
+ expected_exp_month = 12
+ expected_exp_year = 2025
+
+ transaction_item_created_by_app.payment_method_type = PaymentMethodType.CARD
+ transaction_item_created_by_app.cc_brand = expected_brand
+ transaction_item_created_by_app.cc_first_digits = expected_first_digits
+ transaction_item_created_by_app.cc_last_digits = expected_last_digits
+ transaction_item_created_by_app.cc_exp_month = expected_exp_month
+ transaction_item_created_by_app.cc_exp_year = expected_exp_year
+ transaction_item_created_by_app.save()
+
+ variables = {
+ "id": graphene.Node.to_global_id(
+ "TransactionItem", transaction_item_created_by_app.token
+ )
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ TRANSACTION_QUERY, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["transaction"]
+ assert data["paymentMethodDetails"]["__typename"] == "CardPaymentMethodDetails"
+ assert data["paymentMethodDetails"]["brand"] == expected_brand
+ assert data["paymentMethodDetails"]["firstDigits"] == expected_first_digits
+ assert data["paymentMethodDetails"]["lastDigits"] == expected_last_digits
+ assert data["paymentMethodDetails"]["expMonth"] == expected_exp_month
+ assert data["paymentMethodDetails"]["expYear"] == expected_exp_year
+
+
+def test_transaction_query_by_app_with_payment_method_other(
+ app_api_client, transaction_item_created_by_app, permission_manage_payments, app
+):
+ # given
+ expected_payment_method_name = "PayPal Express"
+
+ transaction_item_created_by_app.payment_method_type = PaymentMethodType.OTHER
+ transaction_item_created_by_app.payment_method_name = expected_payment_method_name
+ # Clear card-specific fields for OTHER payment method
+ transaction_item_created_by_app.cc_brand = None
+ transaction_item_created_by_app.cc_first_digits = None
+ transaction_item_created_by_app.cc_last_digits = None
+ transaction_item_created_by_app.cc_exp_month = None
+ transaction_item_created_by_app.cc_exp_year = None
+ transaction_item_created_by_app.save()
+
+ variables = {
+ "id": graphene.Node.to_global_id(
+ "TransactionItem", transaction_item_created_by_app.token
+ )
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ TRANSACTION_QUERY, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["transaction"]
+ assert data["paymentMethodDetails"]["__typename"] == "OtherPaymentMethodDetails"
+ assert data["paymentMethodDetails"]["name"] == expected_payment_method_name
+
+
+def test_transaction_query_by_staff_with_payment_method_other(
+ staff_api_client, transaction_item_created_by_app, permission_manage_payments
+):
+ # given
+ expected_payment_method_name = "Apple Pay"
+
+ transaction_item_created_by_app.payment_method_type = PaymentMethodType.OTHER
+ transaction_item_created_by_app.payment_method_name = expected_payment_method_name
+ transaction_item_created_by_app.save()
+
+ variables = {
+ "id": graphene.Node.to_global_id(
+ "TransactionItem", transaction_item_created_by_app.token
+ )
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ TRANSACTION_QUERY, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["transaction"]
+ assert data["paymentMethodDetails"]["__typename"] == "OtherPaymentMethodDetails"
+ assert data["paymentMethodDetails"]["name"] == expected_payment_method_name
diff --git a/saleor/graphql/payment/types.py b/saleor/graphql/payment/types.py
index 09819e2e86..7ad02cfc1c 100644
--- a/saleor/graphql/payment/types.py
+++ b/saleor/graphql/payment/types.py
@@ -6,7 +6,8 @@ from django.db.models import Q
from graphene import relay
from ...core.exceptions import PermissionDenied
-from ...payment import models
+from ...graphql.core.descriptions import ADDED_IN_322
+from ...payment import PaymentMethodType, models
from ...payment.interface import PaymentMethodData
from ...permission.enums import OrderPermissions
from ..account.dataloaders import UserByUserIdLoader
@@ -427,6 +428,84 @@ class TransactionEvent(ModelObjectType[models.TransactionEvent]):
return None
+class GenericPaymentMethodDetails(graphene.Interface):
+ name = graphene.String(required=True, description="Name of the payment method.")
+
+ class Meta:
+ description = (
+ "Represents a payment method used for a transaction." + ADDED_IN_322
+ )
+
+ def resolve_name(root: models.TransactionItem, _info):
+ return root.payment_method_name or ""
+
+
+class CardPaymentMethodDetails(BaseObjectType):
+ name = graphene.String(required=True, description="Name of the payment method.")
+ brand = graphene.String(description="Card brand.", required=False)
+ first_digits = graphene.String(
+ description="First 4 digits of the card number.", required=False
+ )
+ last_digits = graphene.String(
+ description="Last 4 digits of the card number.", required=False
+ )
+ exp_month = graphene.Int(
+ description="Two-digit number representing the card’s expiration month.",
+ required=False,
+ )
+ exp_year = graphene.Int(
+ description="Four-digit number representing the card’s expiration year.",
+ required=False,
+ )
+
+ class Meta:
+ description = (
+ "Represents a card payment method used for a transaction." + ADDED_IN_322
+ )
+ interfaces = [GenericPaymentMethodDetails]
+
+ @staticmethod
+ def resolve_brand(root: models.TransactionItem, _info):
+ return root.cc_brand
+
+ @staticmethod
+ def resolve_first_digits(root: models.TransactionItem, _info):
+ return root.cc_first_digits
+
+ @staticmethod
+ def resolve_last_digits(root: models.TransactionItem, _info):
+ return root.cc_last_digits
+
+ @staticmethod
+ def resolve_exp_month(root: models.TransactionItem, _info):
+ return root.cc_exp_month
+
+ @staticmethod
+ def resolve_exp_year(root: models.TransactionItem, _info):
+ return root.cc_exp_year
+
+
+class OtherPaymentMethodDetails(BaseObjectType):
+ name = graphene.String(required=True, description="Name of the payment method.")
+
+ class Meta:
+ description = (
+ "Represents a payment method used for a transaction." + ADDED_IN_322
+ )
+ interfaces = [GenericPaymentMethodDetails]
+
+
+class PaymentMethodDetails(graphene.Union):
+ class Meta:
+ types = (CardPaymentMethodDetails, OtherPaymentMethodDetails)
+
+ @classmethod
+ def resolve_type(cls, instance, info: graphene.ResolveInfo):
+ if instance.payment_method_type == PaymentMethodType.CARD:
+ return CardPaymentMethodDetails
+ return OtherPaymentMethodDetails
+
+
class TransactionItem(ModelObjectType[models.TransactionItem]):
token = graphene.Field(
UUIDScalar, description="The transaction token.", required=True
@@ -514,11 +593,22 @@ class TransactionItem(ModelObjectType[models.TransactionItem]):
required=True,
)
+ payment_method_details = graphene.Field(
+ PaymentMethodDetails,
+ description="The payment method used for this transaction." + ADDED_IN_322,
+ )
+
class Meta:
description = "Represents a payment transaction."
interfaces = [relay.Node, ObjectWithMetadata]
model = models.TransactionItem
+ @staticmethod
+ def resolve_payment_method_details(root: models.TransactionItem, info):
+ if not root.payment_method_type:
+ return None
+ return root
+
@staticmethod
def resolve_id(root: models.TransactionItem, _info: ResolveInfo):
return root.token
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 367b9fa52a..0ebcc1cee3 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -10710,6 +10710,13 @@ type TransactionItem implements Node & ObjectWithMetadata @doc(category: "Paymen
The url that will allow to redirect user to payment provider page with transaction details.
"""
externalUrl: String!
+
+ """
+ The payment method used for this transaction.
+
+ Added in Saleor 3.22.
+ """
+ paymentMethodDetails: PaymentMethodDetails
}
"""
@@ -12178,6 +12185,53 @@ enum TransactionEventTypeEnum @doc(category: "Payments") {
union UserOrApp = User | App
+union PaymentMethodDetails = CardPaymentMethodDetails | OtherPaymentMethodDetails
+
+"""
+Represents a card payment method used for a transaction.
+
+Added in Saleor 3.22.
+"""
+type CardPaymentMethodDetails implements GenericPaymentMethodDetails {
+ """Name of the payment method."""
+ name: String!
+
+ """Card brand."""
+ brand: String
+
+ """First 4 digits of the card number."""
+ firstDigits: String
+
+ """Last 4 digits of the card number."""
+ lastDigits: String
+
+ """Two-digit number representing the card’s expiration month."""
+ expMonth: Int
+
+ """Four-digit number representing the card’s expiration year."""
+ expYear: Int
+}
+
+"""
+Represents a payment method used for a transaction.
+
+Added in Saleor 3.22.
+"""
+interface GenericPaymentMethodDetails {
+ """Name of the payment method."""
+ name: String!
+}
+
+"""
+Represents a payment method used for a transaction.
+
+Added in Saleor 3.22.
+"""
+type OtherPaymentMethodDetails implements GenericPaymentMethodDetails {
+ """Name of the payment method."""
+ name: String!
+}
+
"""
Determine a current authorize status for checkout.
@@ -15798,6 +15852,13 @@ type Mutation {
"""
message: String
+ """
+ Details of the payment method used for the transaction.
+
+ Added in Saleor 3.22.
+ """
+ paymentMethodDetails: PaymentMethodDetailsInput
+
"""PSP Reference of the event to report."""
pspReference: String!
@@ -22778,6 +22839,63 @@ input TransactionCreateInput @doc(category: "Payments") {
The url that will allow to redirect user to payment provider page with transaction event details.
"""
externalUrl: String
+
+ """
+ Details of the payment method used for the transaction.
+
+ Added in Saleor 3.22.
+ """
+ paymentMethodDetails: PaymentMethodDetailsInput
+}
+
+"""
+Details of the payment method used for the transaction. One of `card` or `other` is required.
+
+Added in Saleor 3.22.
+"""
+input PaymentMethodDetailsInput {
+ """Details of the card payment method used for the transaction."""
+ card: CardPaymentMethodDetailsInput
+
+ """Details of the non-card payment method used for this transaction."""
+ other: OtherPaymentMethodDetailsInput
+}
+
+input CardPaymentMethodDetailsInput {
+ """
+ Name of the payment method used for the transaction. Max length is 256 characters.
+ """
+ name: String!
+
+ """
+ Brand of the payment method used for the transaction. Max length is 40 characters.
+ """
+ brand: String
+
+ """
+ First digits of the card used for the transaction. Max length is 4 characters.
+ """
+ firstDigits: String
+
+ """
+ Last digits of the card used for the transaction. Max length is 4 characters.
+ """
+ lastDigits: String
+
+ """
+ Expiration month of the card used for the transaction. Value must be between 1 and 12.
+ """
+ expMonth: Int
+
+ """
+ Expiration year of the card used for the transaction. Value must be between 2000 and 9999.
+ """
+ expYear: Int
+}
+
+input OtherPaymentMethodDetailsInput {
+ """Name of the payment method used for the transaction."""
+ name: String!
}
input TransactionEventInput @doc(category: "Payments") {
@@ -22863,6 +22981,13 @@ input TransactionUpdateInput @doc(category: "Payments") {
The url that will allow to redirect user to payment provider page with transaction event details.
"""
externalUrl: String
+
+ """
+ Details of the payment method used for the transaction.
+
+ Added in Saleor 3.22.
+ """
+ paymentMethodDetails: PaymentMethodDetailsInput
}
"""
diff --git a/saleor/json_schemas/TransactionInitializeSession.json b/saleor/json_schemas/TransactionInitializeSession.json
index e51abdaf9e..b928896978 100644
--- a/saleor/json_schemas/TransactionInitializeSession.json
+++ b/saleor/json_schemas/TransactionInitializeSession.json
@@ -78,6 +78,33 @@
"$ref": "#/$defs/JsonValue",
"default": null,
"description": "The JSON data that will be returned to storefront"
+ },
+ "paymentMethodDetails": {
+ "anyOf": [
+ {
+ "discriminator": {
+ "mapping": {
+ "CARD": "#/$defs/CardPaymentMethodDetails",
+ "OTHER": "#/$defs/OtherPaymentMethodDetails"
+ },
+ "propertyName": "type"
+ },
+ "oneOf": [
+ {
+ "$ref": "#/$defs/OtherPaymentMethodDetails"
+ },
+ {
+ "$ref": "#/$defs/CardPaymentMethodDetails"
+ }
+ ]
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "description": "Details of the payment method used for the transaction.",
+ "title": "Paymentmethoddetails"
}
},
"required": [
@@ -163,6 +190,33 @@
"$ref": "#/$defs/JsonValue",
"default": null,
"description": "The JSON data that will be returned to storefront"
+ },
+ "paymentMethodDetails": {
+ "anyOf": [
+ {
+ "discriminator": {
+ "mapping": {
+ "CARD": "#/$defs/CardPaymentMethodDetails",
+ "OTHER": "#/$defs/OtherPaymentMethodDetails"
+ },
+ "propertyName": "type"
+ },
+ "oneOf": [
+ {
+ "$ref": "#/$defs/OtherPaymentMethodDetails"
+ },
+ {
+ "$ref": "#/$defs/CardPaymentMethodDetails"
+ }
+ ]
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "description": "Details of the payment method used for the transaction.",
+ "title": "Paymentmethoddetails"
}
},
"required": [
@@ -247,6 +301,33 @@
"$ref": "#/$defs/JsonValue",
"default": null,
"description": "The JSON data that will be returned to storefront"
+ },
+ "paymentMethodDetails": {
+ "anyOf": [
+ {
+ "discriminator": {
+ "mapping": {
+ "CARD": "#/$defs/CardPaymentMethodDetails",
+ "OTHER": "#/$defs/OtherPaymentMethodDetails"
+ },
+ "propertyName": "type"
+ },
+ "oneOf": [
+ {
+ "$ref": "#/$defs/OtherPaymentMethodDetails"
+ },
+ {
+ "$ref": "#/$defs/CardPaymentMethodDetails"
+ }
+ ]
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "description": "Details of the payment method used for the transaction.",
+ "title": "Paymentmethoddetails"
}
},
"required": [
@@ -257,6 +338,100 @@
}
],
"$defs": {
+ "CardPaymentMethodDetails": {
+ "properties": {
+ "type": {
+ "const": "CARD",
+ "description": "Type of the payment method used for the transaction.",
+ "maxLength": 32,
+ "title": "Type",
+ "type": "string"
+ },
+ "name": {
+ "description": "Name of the payment method used for the transaction.",
+ "maxLength": 256,
+ "title": "Name",
+ "type": "string"
+ },
+ "brand": {
+ "anyOf": [
+ {
+ "maxLength": 40,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "description": "Brand of the card used for the transaction.",
+ "title": "Brand"
+ },
+ "firstDigits": {
+ "anyOf": [
+ {
+ "maxLength": 4,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "description": "First digits of the card used for the transaction.",
+ "title": "Firstdigits"
+ },
+ "lastDigits": {
+ "anyOf": [
+ {
+ "maxLength": 4,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "description": "Last digits of the card used for the transaction.",
+ "title": "Lastdigits"
+ },
+ "expMonth": {
+ "anyOf": [
+ {
+ "maximum": 12,
+ "minimum": 1,
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "description": "Expiration month of the card used for the transaction.",
+ "title": "Expmonth"
+ },
+ "expYear": {
+ "anyOf": [
+ {
+ "minimum": 2000,
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "description": "Expiration year of the card used for the transaction.",
+ "title": "Expyear"
+ }
+ },
+ "required": [
+ "type",
+ "name"
+ ],
+ "title": "CardPaymentMethodDetails",
+ "type": "object"
+ },
"JsonValue": {
"anyOf": [
{
@@ -284,6 +459,29 @@
}
],
"title": "JsonValue"
+ },
+ "OtherPaymentMethodDetails": {
+ "properties": {
+ "type": {
+ "const": "OTHER",
+ "description": "Type of the payment method used for the transaction.",
+ "maxLength": 32,
+ "title": "Type",
+ "type": "string"
+ },
+ "name": {
+ "description": "Name of the payment method used for the transaction.",
+ "maxLength": 256,
+ "title": "Name",
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "name"
+ ],
+ "title": "OtherPaymentMethodDetails",
+ "type": "object"
}
}
}
diff --git a/saleor/json_schemas/TransactionProcessSession.json b/saleor/json_schemas/TransactionProcessSession.json
index 2dda4f2b60..bedda5b6f7 100644
--- a/saleor/json_schemas/TransactionProcessSession.json
+++ b/saleor/json_schemas/TransactionProcessSession.json
@@ -78,6 +78,33 @@
"$ref": "#/$defs/JsonValue",
"default": null,
"description": "The JSON data that will be returned to storefront"
+ },
+ "paymentMethodDetails": {
+ "anyOf": [
+ {
+ "discriminator": {
+ "mapping": {
+ "CARD": "#/$defs/CardPaymentMethodDetails",
+ "OTHER": "#/$defs/OtherPaymentMethodDetails"
+ },
+ "propertyName": "type"
+ },
+ "oneOf": [
+ {
+ "$ref": "#/$defs/OtherPaymentMethodDetails"
+ },
+ {
+ "$ref": "#/$defs/CardPaymentMethodDetails"
+ }
+ ]
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "description": "Details of the payment method used for the transaction.",
+ "title": "Paymentmethoddetails"
}
},
"required": [
@@ -163,6 +190,33 @@
"$ref": "#/$defs/JsonValue",
"default": null,
"description": "The JSON data that will be returned to storefront"
+ },
+ "paymentMethodDetails": {
+ "anyOf": [
+ {
+ "discriminator": {
+ "mapping": {
+ "CARD": "#/$defs/CardPaymentMethodDetails",
+ "OTHER": "#/$defs/OtherPaymentMethodDetails"
+ },
+ "propertyName": "type"
+ },
+ "oneOf": [
+ {
+ "$ref": "#/$defs/OtherPaymentMethodDetails"
+ },
+ {
+ "$ref": "#/$defs/CardPaymentMethodDetails"
+ }
+ ]
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "description": "Details of the payment method used for the transaction.",
+ "title": "Paymentmethoddetails"
}
},
"required": [
@@ -247,6 +301,33 @@
"$ref": "#/$defs/JsonValue",
"default": null,
"description": "The JSON data that will be returned to storefront"
+ },
+ "paymentMethodDetails": {
+ "anyOf": [
+ {
+ "discriminator": {
+ "mapping": {
+ "CARD": "#/$defs/CardPaymentMethodDetails",
+ "OTHER": "#/$defs/OtherPaymentMethodDetails"
+ },
+ "propertyName": "type"
+ },
+ "oneOf": [
+ {
+ "$ref": "#/$defs/OtherPaymentMethodDetails"
+ },
+ {
+ "$ref": "#/$defs/CardPaymentMethodDetails"
+ }
+ ]
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "description": "Details of the payment method used for the transaction.",
+ "title": "Paymentmethoddetails"
}
},
"required": [
@@ -257,6 +338,100 @@
}
],
"$defs": {
+ "CardPaymentMethodDetails": {
+ "properties": {
+ "type": {
+ "const": "CARD",
+ "description": "Type of the payment method used for the transaction.",
+ "maxLength": 32,
+ "title": "Type",
+ "type": "string"
+ },
+ "name": {
+ "description": "Name of the payment method used for the transaction.",
+ "maxLength": 256,
+ "title": "Name",
+ "type": "string"
+ },
+ "brand": {
+ "anyOf": [
+ {
+ "maxLength": 40,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "description": "Brand of the card used for the transaction.",
+ "title": "Brand"
+ },
+ "firstDigits": {
+ "anyOf": [
+ {
+ "maxLength": 4,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "description": "First digits of the card used for the transaction.",
+ "title": "Firstdigits"
+ },
+ "lastDigits": {
+ "anyOf": [
+ {
+ "maxLength": 4,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "description": "Last digits of the card used for the transaction.",
+ "title": "Lastdigits"
+ },
+ "expMonth": {
+ "anyOf": [
+ {
+ "maximum": 12,
+ "minimum": 1,
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "description": "Expiration month of the card used for the transaction.",
+ "title": "Expmonth"
+ },
+ "expYear": {
+ "anyOf": [
+ {
+ "minimum": 2000,
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "description": "Expiration year of the card used for the transaction.",
+ "title": "Expyear"
+ }
+ },
+ "required": [
+ "type",
+ "name"
+ ],
+ "title": "CardPaymentMethodDetails",
+ "type": "object"
+ },
"JsonValue": {
"anyOf": [
{
@@ -284,6 +459,29 @@
}
],
"title": "JsonValue"
+ },
+ "OtherPaymentMethodDetails": {
+ "properties": {
+ "type": {
+ "const": "OTHER",
+ "description": "Type of the payment method used for the transaction.",
+ "maxLength": 32,
+ "title": "Type",
+ "type": "string"
+ },
+ "name": {
+ "description": "Name of the payment method used for the transaction.",
+ "maxLength": 256,
+ "title": "Name",
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "name"
+ ],
+ "title": "OtherPaymentMethodDetails",
+ "type": "object"
}
}
}
diff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.py
index 8ae2233a27..fbec69b69e 100644
--- a/saleor/payment/__init__.py
+++ b/saleor/payment/__init__.py
@@ -284,3 +284,21 @@ class TokenizedPaymentFlow:
CHOICES = [
(INTERACTIVE, "Interactive"),
]
+
+
+class PaymentMethodType:
+ """Represents possible payment method types.
+
+ The following types are possible:
+ CARD - represents a card payment method.
+ OTHER - represents any payment method that is not a card payment.
+
+ """
+
+ CARD = "card"
+ OTHER = "other"
+
+ CHOICES = [
+ (CARD, "Card"),
+ (OTHER, "Other"),
+ ]
diff --git a/saleor/payment/interface.py b/saleor/payment/interface.py
index 254bfd23f8..0d30b5afdf 100644
--- a/saleor/payment/interface.py
+++ b/saleor/payment/interface.py
@@ -128,6 +128,17 @@ class TransactionRequestEventResponse:
message: str | None = ""
+@dataclass
+class PaymentMethodDetails:
+ type: str
+ name: str
+ brand: str | None = None
+ first_digits: str | None = None
+ last_digits: str | None = None
+ exp_month: int | None = None
+ exp_year: int | None = None
+
+
@dataclass
class TransactionResponseBase:
psp_reference: str | None
@@ -137,6 +148,7 @@ class TransactionResponseBase:
@dataclass
class TransactionSessionResponse(TransactionResponseBase):
event: TransactionRequestEventResponse
+ payment_method_details: PaymentMethodDetails | None = None
@dataclass
diff --git a/saleor/payment/migrations/0062_transactionitem_cc_brand_and_more.py b/saleor/payment/migrations/0062_transactionitem_cc_brand_and_more.py
new file mode 100644
index 0000000000..c6546b3601
--- /dev/null
+++ b/saleor/payment/migrations/0062_transactionitem_cc_brand_and_more.py
@@ -0,0 +1,64 @@
+# Generated by Django 5.2.1 on 2025-06-11 07:40
+
+import django.core.validators
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("payment", "0061_merge_20250527_1210"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="transactionitem",
+ name="cc_brand",
+ field=models.CharField(blank=True, max_length=40, null=True),
+ ),
+ migrations.AddField(
+ model_name="transactionitem",
+ name="cc_exp_month",
+ field=models.PositiveIntegerField(
+ blank=True,
+ null=True,
+ validators=[
+ django.core.validators.MinValueValidator(1),
+ django.core.validators.MaxValueValidator(12),
+ ],
+ ),
+ ),
+ migrations.AddField(
+ model_name="transactionitem",
+ name="cc_exp_year",
+ field=models.PositiveIntegerField(
+ blank=True,
+ null=True,
+ validators=[django.core.validators.MinValueValidator(2000)],
+ ),
+ ),
+ migrations.AddField(
+ model_name="transactionitem",
+ name="cc_first_digits",
+ field=models.CharField(blank=True, max_length=4, null=True),
+ ),
+ migrations.AddField(
+ model_name="transactionitem",
+ name="cc_last_digits",
+ field=models.CharField(blank=True, max_length=4, null=True),
+ ),
+ migrations.AddField(
+ model_name="transactionitem",
+ name="payment_method_name",
+ field=models.CharField(blank=True, max_length=256, null=True),
+ ),
+ migrations.AddField(
+ model_name="transactionitem",
+ name="payment_method_type",
+ field=models.CharField(
+ blank=True,
+ choices=[("card", "Card"), ("other", "Other")],
+ max_length=32,
+ null=True,
+ ),
+ ),
+ ]
diff --git a/saleor/payment/models.py b/saleor/payment/models.py
index 9bf809f09e..3eb6c120d5 100644
--- a/saleor/payment/models.py
+++ b/saleor/payment/models.py
@@ -20,6 +20,7 @@ from ..permission.enums import PaymentPermissions
from . import (
ChargeStatus,
CustomPaymentChoices,
+ PaymentMethodType,
StorePaymentMethod,
TransactionAction,
TransactionEventType,
@@ -150,6 +151,31 @@ class TransactionItem(ModelWithMetadata):
# Set to False when automatic refund was triggered.
last_refund_success = models.BooleanField(default=True)
+ cc_first_digits = models.CharField(
+ max_length=4,
+ blank=True,
+ null=True,
+ )
+ cc_last_digits = models.CharField(
+ max_length=4,
+ blank=True,
+ null=True,
+ )
+ cc_brand = models.CharField(max_length=40, blank=True, null=True)
+ cc_exp_month = models.PositiveIntegerField(
+ validators=[MinValueValidator(1), MaxValueValidator(12)], null=True, blank=True
+ )
+ cc_exp_year = models.PositiveIntegerField(
+ validators=[MinValueValidator(2000)], null=True, blank=True
+ )
+ payment_method_type = models.CharField(
+ max_length=32,
+ blank=True,
+ null=True,
+ choices=PaymentMethodType.CHOICES,
+ )
+ payment_method_name = models.CharField(max_length=256, blank=True, null=True)
+
class Meta:
ordering = ("pk",)
indexes = [
diff --git a/saleor/payment/tests/test_utils/test_create_transaction_event_for_transaction_session.py b/saleor/payment/tests/test_utils/test_create_transaction_event_for_transaction_session.py
index d97494910b..f974e07fc6 100644
--- a/saleor/payment/tests/test_utils/test_create_transaction_event_for_transaction_session.py
+++ b/saleor/payment/tests/test_utils/test_create_transaction_event_for_transaction_session.py
@@ -1044,3 +1044,158 @@ def test_create_transaction_event_for_transaction_session_twice_auth(
assert failed_event
assert failed_event.psp_reference == request_event.psp_reference
assert failed_event.type == TransactionEventType.AUTHORIZATION_FAILURE
+
+
+ "response_result",
+ [
+ TransactionEventType.AUTHORIZATION_REQUEST,
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ TransactionEventType.CHARGE_REQUEST,
+ TransactionEventType.CHARGE_SUCCESS,
+ TransactionEventType.AUTHORIZATION_ACTION_REQUIRED,
+ TransactionEventType.CHARGE_ACTION_REQUIRED,
+ TransactionEventType.AUTHORIZATION_FAILURE,
+ TransactionEventType.CHARGE_FAILURE,
+ ],
+)
+ "payment_method_details",
+ [
+ {
+ "type": "CARD",
+ "name": "Test Card",
+ "brand": "Brand",
+ "firstDigits": "1234",
+ "lastDigits": "5678",
+ "expMonth": 12,
+ "expYear": 2025,
+ },
+ {
+ "type": "CARD",
+ "name": "Test Card",
+ },
+ {
+ "type": "CARD",
+ "name": "Test Card",
+ "brand": "Brand",
+ "lastDigits": "5678",
+ },
+ {
+ "type": "OTHER",
+ "name": "Test Other",
+ },
+ ],
+)
+def test_create_transaction_event_for_transaction_session_sets_payment_method_details(
+ payment_method_details,
+ 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"] = expected_amount
+ response["paymentMethodDetails"] = payment_method_details
+
+ transaction = transaction_item_generator()
+ request_event = TransactionEvent.objects.create(
+ transaction=transaction, include_in_calculations=False
+ )
+ # when
+ response_event = create_transaction_event_for_transaction_session(
+ request_event,
+ webhook_app,
+ manager=plugins_manager,
+ transaction_webhook_response=response,
+ )
+
+ # then
+ assert response_event
+ transaction.refresh_from_db()
+ assert transaction.payment_method_name == payment_method_details["name"]
+ assert transaction.payment_method_type == payment_method_details["type"].lower()
+ assert transaction.cc_brand == payment_method_details.get("brand")
+ assert transaction.cc_first_digits == payment_method_details.get("firstDigits")
+ assert transaction.cc_last_digits == payment_method_details.get("lastDigits")
+ assert transaction.cc_exp_month == payment_method_details.get("expMonth")
+ assert transaction.cc_exp_year == payment_method_details.get("expYear")
+
+
+ "response_result",
+ [
+ TransactionEventType.AUTHORIZATION_REQUEST,
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ TransactionEventType.CHARGE_REQUEST,
+ TransactionEventType.CHARGE_SUCCESS,
+ TransactionEventType.AUTHORIZATION_ACTION_REQUIRED,
+ TransactionEventType.CHARGE_ACTION_REQUIRED,
+ TransactionEventType.AUTHORIZATION_FAILURE,
+ TransactionEventType.CHARGE_FAILURE,
+ ],
+)
+ "payment_method_details",
+ [
+ # unknown type
+ {
+ "type": "WRONG-TYPE",
+ "name": "Test Card",
+ },
+ # Missing name
+ {
+ "type": "CARD",
+ },
+ # Missing type
+ {
+ "name": "Test Card",
+ },
+ ],
+)
+def test_create_transaction_event_for_transaction_session_invalid_payment_method_details(
+ payment_method_details,
+ 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"] = expected_amount
+ response["paymentMethodDetails"] = payment_method_details
+
+ transaction = transaction_item_generator()
+ request_event = TransactionEvent.objects.create(
+ transaction=transaction,
+ include_in_calculations=False,
+ type=TransactionEventType.AUTHORIZATION_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
+ assert response_event.type == TransactionEventType.AUTHORIZATION_FAILURE
+ assert "paymentMethodDetails" in response_event.message
+
+ transaction.refresh_from_db()
+ assert not transaction.payment_method_name
+ assert not transaction.payment_method_type
+ assert not transaction.cc_brand
+ assert not transaction.cc_first_digits
+ assert not transaction.cc_last_digits
+ assert not transaction.cc_exp_month
+ assert not transaction.cc_exp_year
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index adeb7a39c7..98fc03ad1f 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -57,6 +57,7 @@ from .interface import (
PaymentGatewayData,
PaymentLineData,
PaymentLinesData,
+ PaymentMethodDetails,
PaymentMethodInfo,
RefundData,
StorePaymentMethodEnum,
@@ -916,10 +917,32 @@ def parse_transaction_action_data_for_session_webhook(
external_url=str(response_data_model.external_url),
message=response_data_model.message,
)
+
+ payment_method_details = None
+ if parsed_payment_method_details := response_data_model.payment_method_details:
+ payment_method_details = PaymentMethodDetails(
+ type=parsed_payment_method_details.type,
+ name=parsed_payment_method_details.name,
+ )
+ if isinstance(
+ parsed_payment_method_details,
+ transaction_schemas.CardPaymentMethodDetails,
+ ):
+ payment_method_details.brand = parsed_payment_method_details.brand
+ payment_method_details.first_digits = (
+ parsed_payment_method_details.first_digits
+ )
+ payment_method_details.last_digits = (
+ parsed_payment_method_details.last_digits
+ )
+ payment_method_details.exp_month = parsed_payment_method_details.exp_month
+ payment_method_details.exp_year = parsed_payment_method_details.exp_year
+
return (
TransactionSessionResponse(
psp_reference=response_data_model.psp_reference,
available_actions=response_data_model.actions,
+ payment_method_details=payment_method_details,
event=event,
),
None,
@@ -1249,6 +1272,39 @@ def update_order_with_transaction_details(transaction: TransactionItem):
)
+def update_transaction_item_with_payment_method_details(
+ transaction_item: TransactionItem,
+ payment_method_details: PaymentMethodDetails,
+) -> list[str]:
+ """Assign the payment method details to the transaction item.
+
+ Returns the list of updated fields.
+ """
+ updated_fields = []
+ if payment_method_details.type != transaction_item.payment_method_type:
+ transaction_item.payment_method_type = payment_method_details.type
+ updated_fields.append("payment_method_type")
+ if payment_method_details.name != transaction_item.payment_method_name:
+ transaction_item.payment_method_name = payment_method_details.name
+ updated_fields.append("payment_method_name")
+ if payment_method_details.brand != transaction_item.cc_brand:
+ transaction_item.cc_brand = payment_method_details.brand
+ updated_fields.append("cc_brand")
+ if payment_method_details.first_digits != transaction_item.cc_first_digits:
+ transaction_item.cc_first_digits = payment_method_details.first_digits
+ updated_fields.append("cc_first_digits")
+ if payment_method_details.last_digits != transaction_item.cc_last_digits:
+ transaction_item.cc_last_digits = payment_method_details.last_digits
+ updated_fields.append("cc_last_digits")
+ if payment_method_details.exp_month != transaction_item.cc_exp_month:
+ transaction_item.cc_exp_month = payment_method_details.exp_month
+ updated_fields.append("cc_exp_month")
+ if payment_method_details.exp_year != transaction_item.cc_exp_year:
+ transaction_item.cc_exp_year = payment_method_details.exp_year
+ updated_fields.append("cc_exp_year")
+ return updated_fields
+
+
def create_transaction_event_for_transaction_session(
request_event: TransactionEvent,
app: App,
@@ -1311,6 +1367,14 @@ def create_transaction_event_for_transaction_session(
request_event.save(update_fields=request_event_update_fields)
transaction_item = event.transaction
+ transaction_item_updated_fields = []
+ if transaction_request_response.payment_method_details:
+ transaction_item_updated_fields.extend(
+ update_transaction_item_with_payment_method_details(
+ transaction_item, transaction_request_response.payment_method_details
+ )
+ )
+
if event.type in [
TransactionEventType.AUTHORIZATION_REQUEST,
TransactionEventType.AUTHORIZATION_SUCCESS,
@@ -1341,6 +1405,7 @@ def create_transaction_event_for_transaction_session(
"available_actions",
"modified_at",
]
+ + transaction_item_updated_fields
)
if transaction_item.order_id:
# circular import
@@ -1365,10 +1430,15 @@ def create_transaction_event_for_transaction_session(
)
elif event.psp_reference and transaction_item.psp_reference != event.psp_reference:
transaction_item.psp_reference = event.psp_reference
- transaction_item.save(update_fields=["psp_reference", "modified_at"])
+ transaction_item.save(
+ update_fields=["psp_reference", "modified_at"]
+ + transaction_item_updated_fields
+ )
if transaction_item.checkout_id:
checkout = cast(Checkout, transaction_item.checkout)
update_last_transaction_modified_at_for_checkout(checkout, transaction_item)
+ elif transaction_item_updated_fields:
+ transaction_item.save(update_fields=transaction_item_updated_fields)
return event
diff --git a/saleor/webhook/response_schemas/transaction.py b/saleor/webhook/response_schemas/transaction.py
index 7e1255c923..2edf6b079f 100644
--- a/saleor/webhook/response_schemas/transaction.py
+++ b/saleor/webhook/response_schemas/transaction.py
@@ -6,16 +6,12 @@ from typing import Annotated, Any, Literal
from django.conf import settings
from django.utils import timezone
-from pydantic import (
- BaseModel,
- Field,
- HttpUrl,
- field_validator,
-)
+from pydantic import BaseModel, Field, HttpUrl, field_validator
from ...graphql.core.utils import str_to_enum
from ...payment import (
OPTIONAL_PSP_REFERENCE_EVENTS,
+ PaymentMethodType,
TransactionAction,
TransactionEventType,
)
@@ -23,12 +19,98 @@ from .utils.annotations import DatetimeUTC, DefaultIfNone, JSONValue, OnErrorSki
logger = logging.getLogger(__name__)
-
TransactionActionEnum = Enum( # type: ignore[misc]
"TransactionActionEnum",
[(str_to_enum(value), value) for value, _ in TransactionAction.CHOICES],
)
+PaymentMethodTypeEnum = Enum( # type: ignore[misc]
+ "PaymentMethodTypeEnum",
+ [(str_to_enum(value), value) for value, _ in PaymentMethodType.CHOICES],
+)
+
+
+class PaymentMethodDetailsBase(BaseModel):
+ type: Annotated[
+ DefaultIfNone[str],
+ Field(
+ description="Type of the payment method used for the transaction.",
+ max_length=32,
+ ),
+ ]
+ name: Annotated[
+ str,
+ Field(
+ description=("Name of the payment method used for the transaction."),
+ max_length=256,
+ ),
+ ]
+
+ @field_validator("type", mode="after")
+ @classmethod
+ def clean_type(cls, type_value: str) -> str:
+ return type_value.lower()
+
+
+class OtherPaymentMethodDetails(PaymentMethodDetailsBase):
+ type: Annotated[ # type: ignore[name-defined]
+ Literal[PaymentMethodTypeEnum.OTHER.name],
+ Field(
+ description="Type of the payment method used for the transaction.",
+ max_length=32,
+ ),
+ ]
+
+
+class CardPaymentMethodDetails(PaymentMethodDetailsBase):
+ type: Annotated[ # type: ignore[name-defined]
+ Literal[PaymentMethodTypeEnum.CARD.name],
+ Field(
+ description="Type of the payment method used for the transaction.",
+ max_length=32,
+ ),
+ ]
+ brand: Annotated[
+ str | None,
+ Field(
+ description="Brand of the card used for the transaction.",
+ max_length=40,
+ ),
+ ] = None
+ first_digits: Annotated[
+ str | None,
+ Field(
+ description="First digits of the card used for the transaction.",
+ max_length=4,
+ validation_alias="firstDigits",
+ ),
+ ] = None
+ last_digits: Annotated[
+ str | None,
+ Field(
+ description="Last digits of the card used for the transaction.",
+ max_length=4,
+ validation_alias="lastDigits",
+ ),
+ ] = None
+ exp_month: Annotated[
+ int | None,
+ Field(
+ description="Expiration month of the card used for the transaction.",
+ ge=1,
+ le=12,
+ validation_alias="expMonth",
+ ),
+ ] = None
+ exp_year: Annotated[
+ int | None,
+ Field(
+ description="Expiration year of the card used for the transaction.",
+ ge=2000,
+ validation_alias="expYear",
+ ),
+ ] = None
+
class TransactionBaseSchema(BaseModel):
psp_reference: Annotated[
@@ -268,6 +350,16 @@ class TransactionSessionBaseSchema(TransactionBaseSchema):
),
]
+ payment_method_details: Annotated[
+ OtherPaymentMethodDetails | CardPaymentMethodDetails | None,
+ Field(
+ validation_alias="paymentMethodDetails",
+ default=None,
+ description="Details of the payment method used for the transaction.",
+ discriminator="type",
+ ),
+ ] = None
+
class TransactionSessionFailureSchema(TransactionSessionBaseSchema):
result: Annotated[ # type: ignore[name-defined]
diff --git a/saleor/webhook/tests/response_schemas/test_transaction.py b/saleor/webhook/tests/response_schemas/test_transaction.py
index 1a99a0729f..75004aa9ee 100644
--- a/saleor/webhook/tests/response_schemas/test_transaction.py
+++ b/saleor/webhook/tests/response_schemas/test_transaction.py
@@ -629,6 +629,131 @@ def test_transaction_session_action_required_schema_valid_result(result):
assert transaction.result == result
+ "result",
+ [
+ TransactionEventType.AUTHORIZATION_ACTION_REQUIRED,
+ TransactionEventType.CHARGE_ACTION_REQUIRED,
+ ],
+)
+ "payment_method_details",
+ [
+ {
+ "type": "CARD",
+ "name": "Test Card",
+ "brand": "Brand",
+ "firstDigits": "1234",
+ "lastDigits": "5678",
+ "expMonth": 12,
+ "expYear": 2025,
+ },
+ {
+ "type": "CARD",
+ "name": "Test Card",
+ },
+ {
+ "type": "CARD",
+ "name": "Test Card",
+ "brand": "Brand",
+ "lastDigits": "5678",
+ },
+ {
+ "type": "OTHER",
+ "name": "Test Other",
+ },
+ {
+ "type": "CARD",
+ "name": "Test Card",
+ "brand": None,
+ "firstDigits": None,
+ "lastDigits": None,
+ "expMonth": None,
+ "expYear": None,
+ },
+ ],
+)
+def test_transaction_session_action_required_schema_valid_payment_method_details(
+ payment_method_details, result
+):
+ # given
+ data = {
+ "pspReference": "psp-123",
+ "amount": Decimal("100.50"),
+ "result": result.upper(),
+ "data": "test-data",
+ "paymentMethodDetails": payment_method_details,
+ }
+
+ # when
+ parsed_transaction = TransactionSessionActionRequiredSchema.model_validate(data)
+
+ # then
+ assert parsed_transaction.result == result
+ assert parsed_transaction.payment_method_details
+ parsed_payment_method_details = parsed_transaction.payment_method_details
+
+ assert parsed_payment_method_details.type == payment_method_details["type"].lower()
+ assert parsed_payment_method_details.name == payment_method_details["name"]
+ assert getattr(
+ parsed_payment_method_details, "brand", None
+ ) == payment_method_details.get("brand")
+ assert getattr(
+ parsed_payment_method_details, "first_digits", None
+ ) == payment_method_details.get("firstDigits")
+ assert getattr(
+ parsed_payment_method_details, "last_digits", None
+ ) == payment_method_details.get("lastDigits")
+ assert getattr(
+ parsed_payment_method_details, "exp_month", None
+ ) == payment_method_details.get("expMonth")
+ assert getattr(
+ parsed_payment_method_details, "exp_year", None
+ ) == payment_method_details.get("expYear")
+
+
+ "result",
+ [
+ TransactionEventType.AUTHORIZATION_ACTION_REQUIRED,
+ TransactionEventType.CHARGE_ACTION_REQUIRED,
+ ],
+)
+ "payment_method_details",
+ [
+ # unknown type
+ {
+ "type": "WRONG-TYPE",
+ "name": "Test Card",
+ },
+ # Missing name
+ {
+ "type": "CARD",
+ },
+ # Missing type
+ {
+ "name": "Test Card",
+ },
+ ],
+)
+def test_transaction_session_action_required_schema_invalid_payment_method_details(
+ payment_method_details, result
+):
+ # given
+ data = {
+ "pspReference": "psp-123",
+ "amount": Decimal("100.50"),
+ "result": result.upper(),
+ "data": "test-data",
+ "paymentMethodDetails": payment_method_details,
+ }
+
+ # when & then
+ with pytest.raises(ValidationError):
+ TransactionSessionActionRequiredSchema.model_validate(data)
+
+
@pytest.mark.parametrize(
"result",
[
@@ -685,6 +810,133 @@ def test_transaction_session_success_schema_valid_result(result):
assert transaction.result == result
+ "result",
+ [
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ TransactionEventType.CHARGE_SUCCESS,
+ TransactionEventType.AUTHORIZATION_REQUEST,
+ TransactionEventType.CHARGE_REQUEST,
+ ],
+)
+ "payment_method_details",
+ [
+ {
+ "type": "CARD",
+ "name": "Test Card",
+ "brand": "Brand",
+ "firstDigits": "1234",
+ "lastDigits": "5678",
+ "expMonth": 12,
+ "expYear": 2025,
+ },
+ {
+ "type": "CARD",
+ "name": "Test Card",
+ },
+ {
+ "type": "CARD",
+ "name": "Test Card",
+ "brand": "Brand",
+ "lastDigits": "5678",
+ },
+ {
+ "type": "OTHER",
+ "name": "Test Other",
+ },
+ {
+ "type": "CARD",
+ "name": "Test Card",
+ "brand": None,
+ "firstDigits": None,
+ "lastDigits": None,
+ "expMonth": None,
+ "expYear": None,
+ },
+ ],
+)
+def test_transaction_session_success_schema_valid_payment_method_details(
+ payment_method_details, result
+):
+ # given
+ data = {
+ "pspReference": "psp-123",
+ "amount": Decimal("100.50"),
+ "result": result.upper(),
+ "data": "test-data",
+ "paymentMethodDetails": payment_method_details,
+ }
+
+ # when
+ parsed_transaction = TransactionSessionSuccessSchema.model_validate(data)
+
+ # then
+ assert parsed_transaction.result == result
+ assert parsed_transaction.payment_method_details
+ parsed_payment_method_details = parsed_transaction.payment_method_details
+
+ assert parsed_payment_method_details.type == payment_method_details["type"].lower()
+ assert parsed_payment_method_details.name == payment_method_details["name"]
+ assert getattr(
+ parsed_payment_method_details, "brand", None
+ ) == payment_method_details.get("brand")
+ assert getattr(
+ parsed_payment_method_details, "first_digits", None
+ ) == payment_method_details.get("firstDigits")
+ assert getattr(
+ parsed_payment_method_details, "last_digits", None
+ ) == payment_method_details.get("lastDigits")
+ assert getattr(
+ parsed_payment_method_details, "exp_month", None
+ ) == payment_method_details.get("expMonth")
+ assert getattr(
+ parsed_payment_method_details, "exp_year", None
+ ) == payment_method_details.get("expYear")
+
+
+ "result",
+ [
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ TransactionEventType.CHARGE_SUCCESS,
+ ],
+)
+ "payment_method_details",
+ [
+ # unknown type
+ {
+ "type": "WRONG-TYPE",
+ "name": "Test Card",
+ },
+ # Missing name
+ {
+ "type": "CARD",
+ },
+ # Missing type
+ {
+ "name": "Test Card",
+ },
+ ],
+)
+def test_transaction_session_success_schema_invalid_payment_method_details(
+ payment_method_details, result
+):
+ # given
+ data = {
+ "pspReference": "psp-123",
+ "amount": Decimal("100.50"),
+ "result": result.upper(),
+ "data": "test-data",
+ "paymentMethodDetails": payment_method_details,
+ }
+
+ # when & then
+ with pytest.raises(ValidationError):
+ TransactionSessionSuccessSchema.model_validate(data)
+
+
@pytest.mark.parametrize(
"result",
[
@@ -737,6 +989,132 @@ def test_transaction_session_failure_schema_valid_result(result):
assert transaction.result == result
+ "result",
+ [
+ TransactionEventType.AUTHORIZATION_FAILURE,
+ TransactionEventType.CHARGE_FAILURE,
+ ],
+)
+ "payment_method_details",
+ [
+ {
+ "type": "CARD",
+ "name": "Test Card",
+ "brand": "Brand",
+ "firstDigits": "1234",
+ "lastDigits": "5678",
+ "expMonth": 12,
+ "expYear": 2025,
+ },
+ {
+ "type": "CARD",
+ "name": "Test Card",
+ },
+ {
+ "type": "CARD",
+ "name": "Test Card",
+ "brand": "Brand",
+ "lastDigits": "5678",
+ },
+ {
+ "type": "OTHER",
+ "name": "Test Other",
+ },
+ {
+ "type": "CARD",
+ "name": "Test Card",
+ "brand": None,
+ "firstDigits": None,
+ "lastDigits": None,
+ "expMonth": None,
+ "expYear": None,
+ },
+ ],
+)
+def test_transaction_session_failure_schema_valid_payment_method_details(
+ payment_method_details, result
+):
+ # given
+ data = {
+ "pspReference": "psp-123",
+ "amount": Decimal("100.50"),
+ "result": result.upper(),
+ "data": "test-data",
+ "paymentMethodDetails": payment_method_details,
+ }
+
+ # when
+ parsed_transaction = TransactionSessionFailureSchema.model_validate(data)
+
+ # then
+
+ assert parsed_transaction.result == result
+ assert parsed_transaction.payment_method_details
+ parsed_payment_method_details = parsed_transaction.payment_method_details
+
+ assert parsed_payment_method_details.type == payment_method_details["type"].lower()
+ assert parsed_payment_method_details.name == payment_method_details["name"]
+ assert getattr(
+ parsed_payment_method_details, "brand", None
+ ) == payment_method_details.get("brand")
+ assert getattr(
+ parsed_payment_method_details, "first_digits", None
+ ) == payment_method_details.get("firstDigits")
+ assert getattr(
+ parsed_payment_method_details, "last_digits", None
+ ) == payment_method_details.get("lastDigits")
+ assert getattr(
+ parsed_payment_method_details, "exp_month", None
+ ) == payment_method_details.get("expMonth")
+ assert getattr(
+ parsed_payment_method_details, "exp_year", None
+ ) == payment_method_details.get("expYear")
+
+
+ "result",
+ [
+ TransactionEventType.AUTHORIZATION_ACTION_REQUIRED,
+ TransactionEventType.CHARGE_ACTION_REQUIRED,
+ ],
+)
+ "payment_method_details",
+ [
+ # unknown type
+ {
+ "type": "WRONG-TYPE",
+ "name": "Test Card",
+ },
+ # Missing name
+ {
+ "type": "CARD",
+ },
+ # Missing type
+ {
+ "name": "Test Card",
+ },
+ ],
+)
+def test_transaction_session_failure_schema_invalid_payment_method_details(
+ payment_method_details, result
+):
+ # given
+ data = {
+ "pspReference": "psp-123",
+ "amount": Decimal("100.50"),
+ "result": result.upper(),
+ "data": "test-data",
+ "paymentMethodDetails": payment_method_details,
+ }
+
+ # when & then
+ with pytest.raises(ValidationError):
+ TransactionSessionFailureSchema.model_validate(data)
+
+
@pytest.mark.parametrize(
"result",
[