Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add `customerIpAddress` to transactionAPI (#13718)
Maciej Korycinskic0d4785abd74
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7b2d96a2ba..205c988474 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,14 +13,16 @@ in 3.17. Use `PaymentSettings.defaultTransactionFlowStrategy` instead.- Change in the CSV export. It will now use empty string for empty attribute values instead of a single whitespace value.### GraphQL API+- Add `customerIpAddress` to `transactionInitialize` and `transactionProcess` mutations - #13718 by @korycins+- Add `PaymentSettings` to `Channel` - #13677 by @korycins- Adjust where filtering by empty values - explicit treat empty values - #13754 by @IKarbowiak- Add `storedPaymentMethodRequestDelete` mutation - #13660 by @korycins-- Add `PaymentSettings` to `Channel` - #13677 by @korycins- Add `externalReference` to `updateWarehouse`. It will allow update warehouse byexternal reference. - #13342 by @Smit-Parmar### Saleor Apps+- Add `customerIpAddress` to `TRANSACTION_INITIALIZE_SESSION` and `TRANSACTION_PROCESS_SESSION` webhooks #13718 by @korycins- Add `STORED_PAYMENT_METHOD_DELETE_REQUESTED` webhook event - #13660 by @korycins- Add `NOTIFY_CUSTOMER` flag to `FulfillmentCreated` type - #13620, by @Air-t- Inform apps if customer should be notified when fulfillment is created.diff --git a/saleor/graphql/payment/mutations/transaction/transaction_initialize.py b/saleor/graphql/payment/mutations/transaction/transaction_initialize.pyindex d0fcc5ac00..662320efed 100644--- a/saleor/graphql/payment/mutations/transaction/transaction_initialize.py+++ b/saleor/graphql/payment/mutations/transaction/transaction_initialize.py@@ -11,7 +11,7 @@ from .....payment.utils import handle_transaction_initialize_sessionfrom .....permission.enums import PaymentPermissionsfrom ....app.dataloaders import get_app_promisefrom ....channel.enums import TransactionFlowStrategyEnum-from ....core.descriptions import ADDED_IN_313, PREVIEW_FEATURE+from ....core.descriptions import ADDED_IN_313, ADDED_IN_316, PREVIEW_FEATUREfrom ....core.doc_category import DOC_CATEGORY_PAYMENTSfrom ....core.enums import TransactionInitializeErrorCodefrom ....core.scalars import JSON, PositiveDecimal@@ -20,6 +20,7 @@ from ....plugins.dataloaders import get_plugin_manager_promisefrom ...types import TransactionEvent, TransactionItemfrom ..base import TransactionSessionBasefrom .payment_gateway_initialize import PaymentGatewayToInitialize+from .utils import clean_customer_ip_addressclass TransactionInitialize(TransactionSessionBase):@@ -55,6 +56,16 @@ class TransactionInitialize(TransactionSessionBase):"can be used only by app that has `HANDLE_PAYMENTS` permission."),)+ customer_ip_address = graphene.String(+ description=(+ "The customer's IP address. If not provided Saleor will try to "+ "determine the customer's IP address on its own. "+ "The customer's IP address will be passed to the payment app. "+ "The IP should be in ipv4 or ipv6 format. "+ "The field can be used only by an app that has `HANDLE_PAYMENTS` "+ "permission." + ADDED_IN_316+ )+ )payment_gateway = graphene.Argument(PaymentGatewayToInitialize,description="Payment gateway used to initialize the transaction.",@@ -96,7 +107,15 @@ class TransactionInitialize(TransactionSessionBase):@classmethoddef perform_mutation(- cls, root, info, *, id, payment_gateway, amount=None, action=None+ cls,+ root,+ info,+ *,+ id,+ payment_gateway,+ amount=None,+ action=None,+ customer_ip_address=None):manager = get_plugin_manager_promise(info.context).get()payment_gateway_data = PaymentGatewayData(@@ -110,6 +129,11 @@ class TransactionInitialize(TransactionSessionBase):manager=manager,)action = cls.clean_action(info, action, source_object.channel)+ customer_ip_address = clean_customer_ip_address(+ info,+ customer_ip_address,+ error_code=TransactionInitializeErrorCode.INVALID.value,+ )amount = cls.get_amount(source_object,@@ -121,6 +145,7 @@ class TransactionInitialize(TransactionSessionBase):payment_gateway_data=payment_gateway_data,amount=amount,action=action,+ customer_ip_address=customer_ip_address,app=app,manager=manager,)diff --git a/saleor/graphql/payment/mutations/transaction/transaction_process.py b/saleor/graphql/payment/mutations/transaction/transaction_process.pyindex c26085c6c1..ea25a40515 100644--- a/saleor/graphql/payment/mutations/transaction/transaction_process.py+++ b/saleor/graphql/payment/mutations/transaction/transaction_process.py@@ -17,13 +17,14 @@ from .....payment.utils import (get_final_session_statuses,handle_transaction_process_session,)-from ....core.descriptions import ADDED_IN_313, PREVIEW_FEATURE+from ....core.descriptions import ADDED_IN_313, ADDED_IN_316, PREVIEW_FEATUREfrom ....core.doc_category import DOC_CATEGORY_PAYMENTSfrom ....core.mutations import BaseMutationfrom ....core.scalars import JSONfrom ....core.types import common as common_typesfrom ....plugins.dataloaders import get_plugin_manager_promisefrom ...types import TransactionEvent, TransactionItem+from .utils import clean_customer_ip_addressif TYPE_CHECKING:pass@@ -49,6 +50,16 @@ class TransactionProcess(BaseMutation):data = graphene.Argument(JSON, description="The data that will be passed to the payment gateway.")+ customer_ip_address = graphene.String(+ description=(+ "The customer's IP address. If not provided Saleor will try to "+ "determine the customer's IP address on its own. "+ "The customer's IP address will be passed to the payment app. "+ "The IP should be in ipv4 or ipv6 format. "+ "The field can be used only by an app that has `HANDLE_PAYMENTS` "+ "permission." + ADDED_IN_316+ )+ )class Meta:doc_category = DOC_CATEGORY_PAYMENTS@@ -150,7 +161,7 @@ class TransactionProcess(BaseMutation):return app@classmethod- def perform_mutation(cls, root, info, *, id, data=None):+ def perform_mutation(cls, root, info, *, id, data=None, customer_ip_address=None):transaction_item = cls.get_node_or_error(info, id, only_type="TransactionItem", field="token")@@ -168,6 +179,12 @@ class TransactionProcess(BaseMutation):app_identifier = app.identifierapp_identifier = cast(str, app_identifier)action = cls.get_action(request_event, source_object.channel)+ customer_ip_address = clean_customer_ip_address(+ info,+ customer_ip_address,+ error_code=TransactionProcessErrorCode.INVALID.value,+ )+manager = get_plugin_manager_promise(info.context).get()event, data = handle_transaction_process_session(transaction_item=transaction_item,@@ -177,6 +194,7 @@ class TransactionProcess(BaseMutation):),app=app,action=action,+ customer_ip_address=customer_ip_address,manager=manager,request_event=request_event,)diff --git a/saleor/graphql/payment/mutations/transaction/utils.py b/saleor/graphql/payment/mutations/transaction/utils.pyindex 87a1fa6501..adc5078e95 100644--- a/saleor/graphql/payment/mutations/transaction/utils.py+++ b/saleor/graphql/payment/mutations/transaction/utils.py@@ -1,9 +1,14 @@-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Optionalfrom django.core.exceptions import ValidationError+from django.core.validators import validate_ipv46_address+from .....core.exceptions import PermissionDenied+from .....core.utils import get_client_ipfrom .....payment import models as payment_modelsfrom .....payment.error_codes import TransactionUpdateErrorCode+from .....permission.enums import PaymentPermissions+from ....app.dataloaders import get_app_promisefrom ....core.utils import from_global_id_or_errorfrom ...types import TransactionItem@@ -36,3 +41,34 @@ def get_transaction_item(id: str) -> payment_models.TransactionItem:})return instance+++def clean_customer_ip_address(+ info, customer_ip_address: Optional[str], error_code: str+):+ """Get customer IP address.++ The customer IP address is required for some payment gateways. By default, the+ customer IP address is taken from the request.++ If customer IP address is provided, we require the app to have the+ `PaymentPermissions.HANDLE_PAYMENTS` permission.+ """++ if not customer_ip_address:+ return get_client_ip(info.context)+ app = get_app_promise(info.context).get()+ if not app or not app.has_perm(PaymentPermissions.HANDLE_PAYMENTS):+ raise PermissionDenied(permissions=[PaymentPermissions.HANDLE_PAYMENTS])+ try:+ validate_ipv46_address(customer_ip_address)+ except ValidationError as error:+ raise ValidationError(+ {+ "customer_ip_address": ValidationError(+ message=error.message,+ code=error_code,+ )+ }+ )+ return customer_ip_addressdiff --git a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.pyindex 2e4b90a7b5..4dd39e673e 100644--- a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py+++ b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py@@ -26,12 +26,14 @@ mutation TransactionInitialize($amount: PositiveDecimal,$id: ID!,$paymentGateway: PaymentGatewayToInitialize!+ $customerIpAddress: String) {transactionInitialize(action: $actionamount: $amountid: $idpaymentGateway: $paymentGateway+ customerIpAddress: $customerIpAddress) {datatransaction {@@ -167,6 +169,7 @@ def _assert_fields(amount=expected_amount,currency=source_object.currency,),+ customer_ip_address="127.0.0.1",payment_gateway_data=PaymentGatewayData(app_identifier=app_identifier, data=None, error=None),@@ -824,7 +827,6 @@ def test_app_with_action_field_and_handle_payments(checkout_with_prices,webhook_app,transaction_session_response,- transaction_item_generator,permission_manage_payments,plugins_manager,):@@ -1062,7 +1064,6 @@ def test_checkout_doesnt_exist(checkout_with_prices,webhook_app,transaction_session_response,- transaction_item_generator,permission_manage_payments,):# given@@ -1097,7 +1098,6 @@ def test_order_doesnt_exists(order_with_lines,webhook_app,transaction_session_response,- transaction_item_generator,permission_manage_payments,):# given@@ -1177,3 +1177,268 @@ def test_checkout_fully_paid(mocked_fully_paid.assert_called_once_with(checkout)assert checkout.charge_status == CheckoutChargeStatus.FULLassert checkout.authorize_status == CheckoutAuthorizeStatus.FULL+++def test_user_missing_permission_for_customer_ip_address(+ user_api_client,+ order_with_lines,+ webhook_app,+ transaction_session_response,+):+ # given+ order = order_with_lines++ expected_app_identifier = "webhook.app.identifier"+ webhook_app.identifier = expected_app_identifier+ webhook_app.save()++ variables = {+ "action": None,+ "amount": None,+ "id": to_global_id_or_none(order),+ "paymentGateway": {"id": expected_app_identifier, "data": None},+ "customerIpAddress": "127.0.0.1",+ }++ # when+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)++ # then+ assert_no_permission(response)+++def test_app_missing_permission_for_customer_ip_address(+ app_api_client,+ order_with_lines,+ webhook_app,+ transaction_session_response,+):+ # given+ order = order_with_lines++ expected_app_identifier = "webhook.app.identifier"+ webhook_app.identifier = expected_app_identifier+ webhook_app.save()++ variables = {+ "action": None,+ "amount": None,+ "id": to_global_id_or_none(order),+ "paymentGateway": {"id": expected_app_identifier, "data": None},+ "customerIpAddress": "127.0.0.1",+ }++ # when+ response = app_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)++ # then+ assert_no_permission(response)++[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")+def test_with_customer_ip_address(+ mocked_initialize,+ app_api_client,+ order_with_lines,+ webhook_app,+ transaction_session_response,+ permission_manage_payments,+):+ # given+ order = order_with_lines+ expected_app_identifier = "webhook.app.identifier"+ webhook_app.identifier = expected_app_identifier+ webhook_app.save()++ expected_amount = Decimal("10.00")+ expected_psp_reference = "ppp-123"+ expected_response = transaction_session_response.copy()+ expected_response["result"] = TransactionEventType.CHARGE_REQUEST.upper()+ expected_response["pspReference"] = expected_psp_reference+ mocked_initialize.return_value = TransactionSessionResult(+ app_identifier=expected_app_identifier, response=expected_response+ )+ app_api_client.app.permissions.set([permission_manage_payments])++ variables = {+ "action": None,+ "amount": expected_amount,+ "id": to_global_id_or_none(order),+ "paymentGateway": {"id": expected_app_identifier, "data": None},+ "customerIpAddress": "127.0.0.2",+ }++ # when+ response = app_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)++ # then+ get_graphql_content(response)++ transaction = order.payment_transactions.last()+ mocked_initialize.assert_called_with(+ TransactionSessionData(+ transaction=transaction,+ source_object=order,+ action=TransactionProcessActionData(+ action_type=TransactionFlowStrategy.CHARGE,+ amount=expected_amount,+ currency=order.currency,+ ),+ customer_ip_address="127.0.0.2",+ payment_gateway_data=PaymentGatewayData(+ app_identifier=webhook_app.identifier, data=None, error=None+ ),+ )+ )++[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")+def test_sets_customer_ip_address_when_not_provided(+ mocked_initialize,+ app_api_client,+ order_with_lines,+ webhook_app,+ transaction_session_response,+ permission_manage_payments,+):+ # given+ order = order_with_lines+ expected_app_identifier = "webhook.app.identifier"+ webhook_app.identifier = expected_app_identifier+ webhook_app.save()++ expected_amount = Decimal("10.00")+ expected_psp_reference = "ppp-123"+ expected_response = transaction_session_response.copy()+ expected_response["result"] = TransactionEventType.CHARGE_REQUEST.upper()+ expected_response["pspReference"] = expected_psp_reference+ mocked_initialize.return_value = TransactionSessionResult(+ app_identifier=expected_app_identifier, response=expected_response+ )+ app_api_client.app.permissions.set([permission_manage_payments])++ variables = {+ "action": None,+ "amount": expected_amount,+ "id": to_global_id_or_none(order),+ "paymentGateway": {"id": expected_app_identifier, "data": None},+ }++ # when+ response = app_api_client.post_graphql(+ TRANSACTION_INITIALIZE, variables, REMOTE_ADDR="127.0.0.2"+ )++ # then+ get_graphql_content(response)++ transaction = order.payment_transactions.last()+ mocked_initialize.assert_called_with(+ TransactionSessionData(+ transaction=transaction,+ source_object=order,+ action=TransactionProcessActionData(+ action_type=TransactionFlowStrategy.CHARGE,+ amount=expected_amount,+ currency=order.currency,+ ),+ customer_ip_address="127.0.0.2",+ payment_gateway_data=PaymentGatewayData(+ app_identifier=webhook_app.identifier, data=None, error=None+ ),+ )+ )+++def test_customer_ip_address_wrong_format(+ app_api_client,+ order_with_lines,+ webhook_app,+ transaction_session_response,+ permission_manage_payments,+):+ # given+ order = order_with_lines+ expected_app_identifier = "webhook.app.identifier"+ webhook_app.identifier = expected_app_identifier+ webhook_app.save()++ expected_amount = Decimal("10.00")++ app_api_client.app.permissions.set([permission_manage_payments])++ variables = {+ "action": None,+ "amount": expected_amount,+ "id": to_global_id_or_none(order),+ "paymentGateway": {"id": expected_app_identifier, "data": None},+ "customerIpAddress": "127.0.02",+ }++ # when+ response = app_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)++ # then+ content = get_graphql_content(response)++ errors = content["data"]["transactionInitialize"]["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "customerIpAddress"+ assert errors[0]["code"] == TransactionInitializeErrorCode.INVALID.name++[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")+def test_customer_ip_address_ipv6(+ mocked_initialize,+ app_api_client,+ order_with_lines,+ webhook_app,+ transaction_session_response,+ permission_manage_payments,+):+ # given+ order = order_with_lines+ expected_app_identifier = "webhook.app.identifier"+ webhook_app.identifier = expected_app_identifier+ webhook_app.save()++ expected_amount = Decimal("10.00")+ expected_psp_reference = "ppp-123"+ expected_response = transaction_session_response.copy()+ expected_response["result"] = TransactionEventType.CHARGE_REQUEST.upper()+ expected_response["pspReference"] = expected_psp_reference+ mocked_initialize.return_value = TransactionSessionResult(+ app_identifier=expected_app_identifier, response=expected_response+ )+ app_api_client.app.permissions.set([permission_manage_payments])++ variables = {+ "action": None,+ "amount": expected_amount,+ "id": to_global_id_or_none(order),+ "paymentGateway": {"id": expected_app_identifier, "data": None},+ "customerIpAddress": "::1",+ }++ # when+ response = app_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)++ # then+ get_graphql_content(response)++ transaction = order.payment_transactions.last()+ mocked_initialize.assert_called_with(+ TransactionSessionData(+ transaction=transaction,+ source_object=order,+ action=TransactionProcessActionData(+ action_type=TransactionFlowStrategy.CHARGE,+ amount=expected_amount,+ currency=order.currency,+ ),+ customer_ip_address="::1",+ payment_gateway_data=PaymentGatewayData(+ app_identifier=webhook_app.identifier, data=None, error=None+ ),+ )+ )diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_process.py b/saleor/graphql/payment/tests/mutations/test_transaction_process.pyindex c449e7b833..114a9d062b 100644--- a/saleor/graphql/payment/tests/mutations/test_transaction_process.py+++ b/saleor/graphql/payment/tests/mutations/test_transaction_process.py@@ -19,16 +19,19 @@ from .....payment.interface import (from .....payment.models import TransactionEventfrom ....core.enums import TransactionProcessErrorCodefrom ....core.utils import to_global_id_or_none-from ....tests.utils import get_graphql_content+from ....tests.utils import assert_no_permission, get_graphql_contentTRANSACTION_PROCESS = """mutation TransactionProcess($id: ID!,$data: JSON+ $customerIpAddress: String+) {transactionProcess(id: $iddata: $data+ customerIpAddress: $customerIpAddress) {datatransaction {@@ -166,6 +169,7 @@ def _assert_fields(amount=expected_amount,currency=source_object.currency,),+ customer_ip_address="127.0.0.1",payment_gateway_data=PaymentGatewayData(app_identifier=app_identifier, data=data, error=None),@@ -933,3 +937,315 @@ def test_transaction_process_doesnt_accept_old_id(assert (response_data["errors"][0]["code"] == TransactionProcessErrorCode.INVALID.name)+++def test_user_missing_permission_for_customer_ip_address(+ user_api_client,+ checkout_with_prices,+ webhook_app,+ transaction_session_response,+ transaction_item_generator,+):+ # given+ checkout = checkout_with_prices++ expected_app_identifier = "webhook.app.identifier"+ webhook_app.identifier = expected_app_identifier+ webhook_app.save()++ expected_amount = Decimal("10.00")++ transaction_item = transaction_item_generator(+ checkout_id=checkout.pk, app=webhook_app+ )+ TransactionEvent.objects.create(+ transaction=transaction_item,+ amount_value=expected_amount,+ currency=transaction_item.currency,+ type=TransactionEventType.CHARGE_REQUEST,+ )++ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token),+ "data": None,+ "customerIpAddress": "127.0.0.1",+ }++ # when+ response = user_api_client.post_graphql(TRANSACTION_PROCESS, variables)++ # then+ assert_no_permission(response)+++def test_app_missing_permission_for_customer_ip_address(+ app_api_client,+ checkout_with_prices,+ webhook_app,+ transaction_item_generator,+ transaction_session_response,+):+ # given+ checkout = checkout_with_prices++ expected_app_identifier = "webhook.app.identifier"+ webhook_app.identifier = expected_app_identifier+ webhook_app.save()++ expected_amount = Decimal("10.00")++ transaction_item = transaction_item_generator(+ checkout_id=checkout.pk, app=webhook_app+ )+ TransactionEvent.objects.create(+ transaction=transaction_item,+ amount_value=expected_amount,+ currency=transaction_item.currency,+ type=TransactionEventType.CHARGE_REQUEST,+ )++ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token),+ "data": None,+ "customerIpAddress": "127.0.0.1",+ }++ # when+ response = app_api_client.post_graphql(TRANSACTION_PROCESS, variables)++ # then+ assert_no_permission(response)++[email protected]("saleor.plugins.manager.PluginsManager.transaction_process_session")+def test_with_customer_ip_address(+ mocked_process,+ app_api_client,+ checkout_with_prices,+ transaction_item_generator,+ webhook_app,+ transaction_session_response,+ permission_manage_payments,+):+ # given+ expected_amount = Decimal("10.00")++ checkout = checkout_with_prices+ expected_app_identifier = "webhook.app.identifier"+ webhook_app.identifier = expected_app_identifier+ webhook_app.save()++ transaction_item = transaction_item_generator(+ checkout_id=checkout_with_prices.pk, app=webhook_app+ )+ TransactionEvent.objects.create(+ transaction=transaction_item,+ amount_value=expected_amount,+ currency=transaction_item.currency,+ type=TransactionEventType.CHARGE_REQUEST,+ )++ mocked_process.return_value = TransactionSessionResult(+ app_identifier=expected_app_identifier, response=transaction_session_response+ )++ app_api_client.app.permissions.set([permission_manage_payments])++ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token),+ "data": None,+ "customerIpAddress": "127.0.0.2",+ }++ # when+ response = app_api_client.post_graphql(TRANSACTION_PROCESS, variables)++ # then+ get_graphql_content(response)++ mocked_process.assert_called_with(+ TransactionSessionData(+ transaction=transaction_item,+ source_object=checkout,+ action=TransactionProcessActionData(+ action_type=TransactionFlowStrategy.CHARGE,+ amount=expected_amount,+ currency=checkout.currency,+ ),+ customer_ip_address="127.0.0.2",+ payment_gateway_data=PaymentGatewayData(+ app_identifier=webhook_app.identifier, data=None, error=None+ ),+ )+ )++[email protected]("saleor.plugins.manager.PluginsManager.transaction_process_session")+def test_sets_customer_ip_address_when_not_provided(+ mocked_process,+ app_api_client,+ checkout_with_prices,+ webhook_app,+ transaction_session_response,+ transaction_item_generator,+ permission_manage_payments,+):+ # given+ expected_amount = Decimal("10.00")++ checkout = checkout_with_prices+ expected_app_identifier = "webhook.app.identifier"+ webhook_app.identifier = expected_app_identifier+ webhook_app.save()++ transaction_item = transaction_item_generator(+ checkout_id=checkout_with_prices.pk, app=webhook_app+ )+ TransactionEvent.objects.create(+ transaction=transaction_item,+ amount_value=expected_amount,+ currency=transaction_item.currency,+ type=TransactionEventType.CHARGE_REQUEST,+ )++ mocked_process.return_value = TransactionSessionResult(+ app_identifier=expected_app_identifier, response=transaction_session_response+ )++ app_api_client.app.permissions.set([permission_manage_payments])++ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token),+ "data": None,+ }++ # when+ response = app_api_client.post_graphql(+ TRANSACTION_PROCESS, variables, REMOTE_ADDR="127.0.0.2"+ )++ # then+ get_graphql_content(response)++ mocked_process.assert_called_with(+ TransactionSessionData(+ transaction=transaction_item,+ source_object=checkout,+ action=TransactionProcessActionData(+ action_type=TransactionFlowStrategy.CHARGE,+ amount=expected_amount,+ currency=checkout.currency,+ ),+ customer_ip_address="127.0.0.2",+ payment_gateway_data=PaymentGatewayData(+ app_identifier=webhook_app.identifier, data=None, error=None+ ),+ )+ )+++def test_customer_ip_address_wrong_format(+ checkout_with_prices,+ webhook_app,+ transaction_session_response,+ permission_manage_payments,+ transaction_item_generator,+ app_api_client,+):+ # given+ expected_amount = Decimal("10.00")++ expected_app_identifier = "webhook.app.identifier"+ webhook_app.identifier = expected_app_identifier+ webhook_app.save()++ transaction_item = transaction_item_generator(+ checkout_id=checkout_with_prices.pk, app=webhook_app+ )+ TransactionEvent.objects.create(+ transaction=transaction_item,+ amount_value=expected_amount,+ currency=transaction_item.currency,+ type=TransactionEventType.CHARGE_REQUEST,+ )++ app_api_client.app.permissions.set([permission_manage_payments])++ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token),+ "data": None,+ "customerIpAddress": "127.0.02",+ }+ # when+ response = app_api_client.post_graphql(TRANSACTION_PROCESS, variables)++ # then+ content = get_graphql_content(response)++ errors = content["data"]["transactionProcess"]["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "customerIpAddress"+ assert errors[0]["code"] == TransactionProcessErrorCode.INVALID.name++[email protected]("saleor.plugins.manager.PluginsManager.transaction_process_session")+def test_customer_ip_address_ipv6(+ mocked_process,+ app_api_client,+ checkout_with_prices,+ webhook_app,+ transaction_session_response,+ permission_manage_payments,+ transaction_item_generator,+):+ # given+ expected_amount = Decimal("10.00")++ checkout = checkout_with_prices+ expected_app_identifier = "webhook.app.identifier"+ webhook_app.identifier = expected_app_identifier+ webhook_app.save()++ transaction_item = transaction_item_generator(+ checkout_id=checkout_with_prices.pk, app=webhook_app+ )+ TransactionEvent.objects.create(+ transaction=transaction_item,+ amount_value=expected_amount,+ currency=transaction_item.currency,+ type=TransactionEventType.CHARGE_REQUEST,+ )++ mocked_process.return_value = TransactionSessionResult(+ app_identifier=expected_app_identifier, response=transaction_session_response+ )++ app_api_client.app.permissions.set([permission_manage_payments])++ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token),+ "data": None,+ "customerIpAddress": "::1",+ }++ # when+ response = app_api_client.post_graphql(TRANSACTION_PROCESS, variables)++ # then+ get_graphql_content(response)++ mocked_process.assert_called_with(+ TransactionSessionData(+ transaction=transaction_item,+ source_object=checkout,+ action=TransactionProcessActionData(+ action_type=TransactionFlowStrategy.CHARGE,+ amount=expected_amount,+ currency=checkout.currency,+ ),+ customer_ip_address="::1",+ payment_gateway_data=PaymentGatewayData(+ app_identifier=webhook_app.identifier, data=None, error=None+ ),+ )+ )diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 2ad87e5eb8..19d6bd1a2f 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -15597,6 +15597,13 @@ type Mutation {"""amount: PositiveDecimal+ """+ The customer's IP address. If not provided Saleor will try to determine the customer's IP address on its own. The customer's IP address will be passed to the payment app. The IP should be in ipv4 or ipv6 format. The field can be used only by an app that has `HANDLE_PAYMENTS` permission.++ Added in Saleor 3.16.+ """+ customerIpAddress: String+"""The ID of the checkout or order."""id: ID!@@ -15612,6 +15619,13 @@ type Mutation {Note: this API is currently in Feature Preview and can be subject to changes at later point."""transactionProcess(+ """+ The customer's IP address. If not provided Saleor will try to determine the customer's IP address on its own. The customer's IP address will be passed to the payment app. The IP should be in ipv4 or ipv6 format. The field can be used only by an app that has `HANDLE_PAYMENTS` permission.++ Added in Saleor 3.16.+ """+ customerIpAddress: String+"""The data that will be passed to the payment gateway."""data: JSON@@ -33179,12 +33193,19 @@ type TransactionInitializeSession implements Event @doc(category: "Payments") {"""Checkout or order"""sourceObject: OrderOrCheckout!- """Payment gateway data in JSON format, recieved from storefront."""+ """Payment gateway data in JSON format, received from storefront."""data: JSON"""Merchant reference assigned to this payment."""merchantReference: String!+ """+ The customer's IP address. If not provided as a parameter in the mutation, Saleor will try to determine the customer's IP address on its own.++ Added in Saleor 3.16.+ """+ customerIpAddress: String+"""Action to proceed for the transaction"""action: TransactionProcessAction!}@@ -33224,12 +33245,19 @@ type TransactionProcessSession implements Event @doc(category: "Payments") {"""Checkout or order"""sourceObject: OrderOrCheckout!- """Payment gateway data in JSON format, recieved from storefront."""+ """Payment gateway data in JSON format, received from storefront."""data: JSON"""Merchant reference assigned to this payment."""merchantReference: String!+ """+ The customer's IP address. If not provided as a parameter in the mutation, Saleor will try to determine the customer's IP address on its own.++ Added in Saleor 3.16.+ """+ customerIpAddress: String+"""Action to proceed for the transaction"""action: TransactionProcessAction!}diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.pyindex 8fc7c14a4b..1f4b03bfdc 100644--- a/saleor/graphql/webhook/subscription_types.py+++ b/saleor/graphql/webhook/subscription_types.py@@ -1800,11 +1800,18 @@ class TransactionSessionBase(SubscriptionObjectType, AbstractType):)data = graphene.Field(JSON,- description="Payment gateway data in JSON format, recieved from storefront.",+ description="Payment gateway data in JSON format, received from storefront.",)merchant_reference = graphene.String(description="Merchant reference assigned to this payment.", required=True)+ customer_ip_address = graphene.String(+ description=(+ "The customer's IP address. If not provided as a parameter in the "+ "mutation, Saleor will try to determine the customer's IP address on its "+ "own." + ADDED_IN_316+ ),+ )action = graphene.Field(TransactionProcessAction,description="Action to proceed for the transaction",@@ -1847,6 +1854,13 @@ class TransactionSessionBase(SubscriptionObjectType, AbstractType):_, transaction_session_data = rootreturn transaction_session_data.action+ @classmethod+ def resolve_customer_ip_address(+ cls, root: tuple[str, TransactionSessionData], _info: ResolveInfo+ ):+ _, transaction_session_data = root+ return transaction_session_data.customer_ip_address+class TransactionInitializeSession(TransactionSessionBase):class Meta:diff --git a/saleor/payment/interface.py b/saleor/payment/interface.pyindex 630c2d0f9b..537ac59247 100644--- a/saleor/payment/interface.py+++ b/saleor/payment/interface.py@@ -147,6 +147,7 @@ class TransactionSessionData:source_object: Union["Checkout", "Order"]action: TransactionProcessActionDatapayment_gateway_data: PaymentGatewayData+ customer_ip_address: Optional[str]@dataclassdiff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex 3f1f6f5157..034f6833e0 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -1435,6 +1435,7 @@ def handle_transaction_initialize_session(payment_gateway_data: PaymentGatewayData,amount: Decimal,action: str,+ customer_ip_address: Optional[str],app: App,manager: PluginsManager,):@@ -1448,6 +1449,7 @@ def handle_transaction_initialize_session(action=TransactionProcessActionData(action_type=action, currency=source_object.currency, amount=amount),+ customer_ip_address=customer_ip_address,)request_event = transaction_item.events.create(@@ -1478,6 +1480,7 @@ def handle_transaction_process_session(payment_gateway_data: PaymentGatewayData,action: str,app: App,+ customer_ip_address: Optional[str],manager: PluginsManager,request_event: TransactionEvent,):@@ -1490,6 +1493,7 @@ def handle_transaction_process_session(currency=source_object.currency,amount=request_event.amount_value,),+ customer_ip_address=customer_ip_address,)result = manager.transaction_process_session(session_data)diff --git a/saleor/plugins/tests/test_manager.py b/saleor/plugins/tests/test_manager.pyindex e2e147aedd..f61829d109 100644--- a/saleor/plugins/tests/test_manager.py+++ b/saleor/plugins/tests/test_manager.py@@ -1215,6 +1215,7 @@ def test_manager_transaction_initialize_session(currency=transaction.currency,action_type=action_type,),+ customer_ip_address="127.0.0.1",payment_gateway_data=PaymentGatewayData(app_identifier=webhook_app.identifier, data=None, error=None),@@ -1256,6 +1257,7 @@ def test_manager_transaction_process_session(currency=transaction.currency,action_type=action_type,),+ customer_ip_address="127.0.0.1",payment_gateway_data=PaymentGatewayData(app_identifier=webhook_app.identifier, data=None, error=None),diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_initialize_session.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_initialize_session.pyindex bcb0f9aefc..89ff250b5e 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_initialize_session.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_initialize_session.py@@ -24,6 +24,7 @@ subscription {actionType}data+ customerIpAddresssourceObject{__typename... on Checkout{@@ -75,6 +76,7 @@ def test_transaction_initialize_session_checkout_with_data(currency=transaction.currency,action_type=action_type,),+ customer_ip_address="127.0.0.1",payment_gateway_data=PaymentGatewayData(app_identifier=webhook_app.identifier, data=payload_data, error=None),@@ -100,6 +102,7 @@ def test_transaction_initialize_session_checkout_with_data("actionType": action_type.upper(),},"data": payload_data,+ "customerIpAddress": "127.0.0.1","sourceObject": {"__typename": "Checkout","id": checkout_id,@@ -140,6 +143,7 @@ def test_transaction_initialize_session_checkout_without_data(currency=transaction.currency,action_type=action_type,),+ customer_ip_address="127.0.0.1",payment_gateway_data=PaymentGatewayData(app_identifier=webhook_app.identifier, data=payload_data, error=None),@@ -164,6 +168,7 @@ def test_transaction_initialize_session_checkout_without_data("actionType": action_type.upper(),},"data": payload_data,+ "customerIpAddress": "127.0.0.1","sourceObject": {"__typename": "Checkout","id": checkout_id,@@ -204,6 +209,7 @@ def test_transaction_initialize_session_order_with_data(currency=transaction.currency,action_type=action_type,),+ customer_ip_address="127.0.0.1",payment_gateway_data=PaymentGatewayData(app_identifier=webhook_app.identifier, data=payload_data, error=None),@@ -229,6 +235,7 @@ def test_transaction_initialize_session_order_with_data("actionType": action_type.upper(),},"data": payload_data,+ "customerIpAddress": "127.0.0.1","sourceObject": {"__typename": "Order","id": order_id,@@ -268,6 +275,7 @@ def test_transaction_initialize_session_order_without_data(currency=transaction.currency,action_type=action_type,),+ customer_ip_address="127.0.0.1",payment_gateway_data=PaymentGatewayData(app_identifier=webhook_app.identifier, data=payload_data, error=None),@@ -292,6 +300,72 @@ def test_transaction_initialize_session_order_without_data("actionType": action_type.upper(),},"data": payload_data,+ "customerIpAddress": "127.0.0.1",+ "sourceObject": {+ "__typename": "Order",+ "id": order_id,+ },+ }+++def test_transaction_initialize_session_empty_customer_ip_addess(+ order, webhook_app, permission_manage_payments, transaction_item_generator+):+ # given+ webhook_app.permissions.add(permission_manage_payments)+ webhook = Webhook.objects.create(+ name="Webhook",+ app=webhook_app,+ subscription_query=TRANSACTION_INITIALIZE_SESSION,+ )+ event_type = WebhookEventSyncType.TRANSACTION_INITIALIZE_SESSION+ webhook.events.create(event_type=event_type)+ payload_data = None+ amount = Decimal("10")++ transaction = transaction_item_generator(+ order_id=order.pk,+ app=webhook_app,+ psp_reference=None,+ name=None,+ message=None,+ )+ action_type = TransactionFlowStrategy.CHARGE++ subscribable_object = TransactionSessionData(+ transaction=transaction,+ source_object=order,+ action=TransactionProcessActionData(+ amount=amount,+ currency=transaction.currency,+ action_type=action_type,+ ),+ customer_ip_address=None,+ payment_gateway_data=PaymentGatewayData(+ app_identifier=webhook_app.identifier, data=payload_data, error=None+ ),+ )++ # when+ delivery = create_deliveries_for_subscriptions(+ event_type, subscribable_object, [webhook]+ )[0]++ # then+ order_id = graphene.Node.to_global_id("Order", order.pk)+ assert delivery.payload+ assert delivery.payload.payload+ assert json.loads(delivery.payload.payload) == {+ "merchantReference": graphene.Node.to_global_id(+ "TransactionItem", transaction.token+ ),+ "action": {+ "amount": amount,+ "currency": "USD",+ "actionType": action_type.upper(),+ },+ "data": payload_data,+ "customerIpAddress": None,"sourceObject": {"__typename": "Order","id": order_id,diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_process_session.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_process_session.pyindex b379a81a1d..1c405ca9a5 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_process_session.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_process_session.py@@ -24,6 +24,7 @@ subscription {actionType}data+ customerIpAddresssourceObject{__typename... on Checkout{@@ -75,6 +76,7 @@ def test_transaction_process_session_checkout_with_data(currency=transaction.currency,action_type=action_type,),+ customer_ip_address="127.0.0.1",payment_gateway_data=PaymentGatewayData(app_identifier=webhook_app.identifier, data=payload_data, error=None),@@ -100,6 +102,7 @@ def test_transaction_process_session_checkout_with_data("actionType": action_type.upper(),},"data": payload_data,+ "customerIpAddress": "127.0.0.1","sourceObject": {"__typename": "Checkout","id": checkout_id,@@ -140,6 +143,7 @@ def test_transaction_process_session_checkout_without_data(currency=transaction.currency,action_type=action_type,),+ customer_ip_address="127.0.0.1",payment_gateway_data=PaymentGatewayData(app_identifier=webhook_app.identifier, data=payload_data, error=None),@@ -164,6 +168,7 @@ def test_transaction_process_session_checkout_without_data("actionType": action_type.upper(),},"data": payload_data,+ "customerIpAddress": "127.0.0.1","sourceObject": {"__typename": "Checkout","id": checkout_id,@@ -204,6 +209,7 @@ def test_transaction_process_session_order_with_data(currency=transaction.currency,action_type=action_type,),+ customer_ip_address="127.0.0.1",payment_gateway_data=PaymentGatewayData(app_identifier=webhook_app.identifier, data=payload_data, error=None),@@ -229,6 +235,7 @@ def test_transaction_process_session_order_with_data("actionType": action_type.upper(),},"data": payload_data,+ "customerIpAddress": "127.0.0.1","sourceObject": {"__typename": "Order","id": order_id,@@ -268,6 +275,7 @@ def test_transaction_process_session_order_without_data(currency=transaction.currency,action_type=action_type,),+ customer_ip_address="127.0.0.1",payment_gateway_data=PaymentGatewayData(app_identifier=webhook_app.identifier, data=payload_data, error=None),@@ -292,6 +300,72 @@ def test_transaction_process_session_order_without_data("actionType": action_type.upper(),},"data": payload_data,+ "customerIpAddress": "127.0.0.1",+ "sourceObject": {+ "__typename": "Order",+ "id": order_id,+ },+ }+++def test_transaction_process_session_empty_customer_ip_address(+ order, webhook_app, permission_manage_payments, transaction_item_generator+):+ # given+ webhook_app.permissions.add(permission_manage_payments)+ webhook = Webhook.objects.create(+ name="Webhook",+ app=webhook_app,+ subscription_query=TRANSACTION_PROCESS_SESSION,+ )+ event_type = WebhookEventSyncType.TRANSACTION_PROCESS_SESSION+ webhook.events.create(event_type=event_type)+ payload_data = None+ amount = Decimal("10")++ transaction = transaction_item_generator(+ order_id=order.pk,+ app=webhook_app,+ psp_reference=None,+ name=None,+ message=None,+ )+ action_type = TransactionFlowStrategy.CHARGE++ subscribable_object = TransactionSessionData(+ transaction=transaction,+ source_object=order,+ action=TransactionProcessActionData(+ amount=amount,+ currency=transaction.currency,+ action_type=action_type,+ ),+ customer_ip_address=None,+ payment_gateway_data=PaymentGatewayData(+ app_identifier=webhook_app.identifier, data=payload_data, error=None+ ),+ )++ # when+ delivery = create_deliveries_for_subscriptions(+ event_type, subscribable_object, [webhook]+ )[0]++ # then+ order_id = graphene.Node.to_global_id("Order", order.pk)+ assert delivery.payload+ assert delivery.payload.payload+ assert json.loads(delivery.payload.payload) == {+ "merchantReference": graphene.Node.to_global_id(+ "TransactionItem", transaction.token+ ),+ "action": {+ "amount": amount,+ "currency": "USD",+ "actionType": action_type.upper(),+ },+ "data": payload_data,+ "customerIpAddress": None,"sourceObject": {"__typename": "Order","id": order_id,diff --git a/saleor/plugins/webhook/tests/test_transaction_initialize_session_webhook.py b/saleor/plugins/webhook/tests/test_transaction_initialize_session_webhook.pyindex 2c0e81bdcd..99cbcc5210 100644--- a/saleor/plugins/webhook/tests/test_transaction_initialize_session_webhook.py+++ b/saleor/plugins/webhook/tests/test_transaction_initialize_session_webhook.py@@ -163,6 +163,7 @@ def test_transaction_initialize_checkout_without_request_data_and_static_payloadcurrency=transaction.currency,action_type=action_type,),+ customer_ip_address="127.0.0.1",payment_gateway_data=PaymentGatewayData(app_identifier=webhook_app.identifier, data=None, error=None),@@ -231,6 +232,7 @@ def test_transaction_initialize_checkout_with_request_data_and_static_payload(currency=transaction.currency,action_type=action_type,),+ customer_ip_address="127.0.0.1",payment_gateway_data=PaymentGatewayData(app_identifier=webhook_app.identifier, data=data, error=None),@@ -299,6 +301,7 @@ def test_transaction_initialize_checkout_without_request_data(currency=transaction.currency,action_type=action_type,),+ customer_ip_address="127.0.0.1",payment_gateway_data=PaymentGatewayData(app_identifier=webhook_app.identifier, data=None, error=None),@@ -368,6 +371,7 @@ def test_transaction_initialize_checkout_with_request_data(currency=transaction.currency,action_type=action_type,),+ customer_ip_address="127.0.0.1",payment_gateway_data=PaymentGatewayData(app_identifier=webhook_app.identifier, data=data, error=None),@@ -437,6 +441,7 @@ def test_transaction_initialize_session_skips_app_without_identifier(currency=transaction.currency,action_type=action_type,),+ customer_ip_address="127.0.0.1",payment_gateway_data=PaymentGatewayData(app_identifier=webhook_app.identifier, data=data, error=None),@@ -499,6 +504,7 @@ def test_transaction_initialize_order_without_request_data_and_static_payload(currency=transaction.currency,action_type=action_type,),+ customer_ip_address="127.0.0.1",payment_gateway_data=PaymentGatewayData(app_identifier=webhook_app.identifier, data=None, error=None),@@ -567,6 +573,7 @@ def test_transaction_initialize_order_with_request_data_and_static_payload(currency=transaction.currency,action_type=action_type,),+ customer_ip_address="127.0.0.1",payment_gateway_data=PaymentGatewayData(app_identifier=webhook_app.identifier, data=data, error=None),@@ -635,6 +642,7 @@ def test_transaction_initialize_order_without_request_data(currency=transaction.currency,action_type=action_type,),+ customer_ip_address="127.0.0.1",payment_gateway_data=PaymentGatewayData(app_identifier=webhook_app.identifier, data=None, error=None),@@ -704,6 +712,7 @@ def test_transaction_initialize_order_with_request_data(currency=transaction.currency,action_type=action_type,),+ customer_ip_address="127.0.0.1",payment_gateway_data=PaymentGatewayData(app_identifier=webhook_app.identifier, data=data, error=None),diff --git a/saleor/plugins/webhook/tests/test_transaction_process_session_webhook.py b/saleor/plugins/webhook/tests/test_transaction_process_session_webhook.pyindex b4f8062ae2..a84a38aa42 100644--- a/saleor/plugins/webhook/tests/test_transaction_process_session_webhook.py+++ b/saleor/plugins/webhook/tests/test_transaction_process_session_webhook.py@@ -163,6 +163,7 @@ def test_transaction_process_checkout_without_request_data_and_static_payload(currency=transaction.currency,action_type=action_type,),+ customer_ip_address=None,payment_gateway_data=PaymentGatewayData(app_identifier=webhook_app.identifier, data=None, error=None),@@ -231,6 +232,7 @@ def test_transaction_process_checkout_with_request_data_and_static_payload(currency=transaction.currency,action_type=action_type,),+ customer_ip_address=None,payment_gateway_data=PaymentGatewayData(app_identifier=webhook_app.identifier, data=data, error=None),@@ -299,6 +301,7 @@ def test_transaction_process_checkout_without_request_data(currency=transaction.currency,action_type=action_type,),+ customer_ip_address=None,payment_gateway_data=PaymentGatewayData(app_identifier=webhook_app.identifier, data=None, error=None),@@ -368,6 +371,7 @@ def test_transaction_process_checkout_with_request_data(currency=transaction.currency,action_type=action_type,),+ customer_ip_address=None,payment_gateway_data=PaymentGatewayData(app_identifier=webhook_app.identifier, data=data, error=None),@@ -437,6 +441,7 @@ def test_transaction_process_session_skips_app_without_identifier(currency=transaction.currency,action_type=action_type,),+ customer_ip_address=None,payment_gateway_data=PaymentGatewayData(app_identifier=webhook_app.identifier, data=data, error=None),@@ -499,6 +504,7 @@ def test_transaction_process_order_without_request_data_and_static_payload(currency=transaction.currency,action_type=action_type,),+ customer_ip_address=None,payment_gateway_data=PaymentGatewayData(app_identifier=webhook_app.identifier, data=None, error=None),@@ -567,6 +573,7 @@ def test_transaction_process_order_with_request_data_and_static_payload(currency=transaction.currency,action_type=action_type,),+ customer_ip_address=None,payment_gateway_data=PaymentGatewayData(app_identifier=webhook_app.identifier, data=data, error=None),@@ -635,6 +642,7 @@ def test_transaction_process_order_without_request_data(currency=transaction.currency,action_type=action_type,),+ customer_ip_address=None,payment_gateway_data=PaymentGatewayData(app_identifier=webhook_app.identifier, data=None, error=None),@@ -704,6 +712,7 @@ def test_transaction_process_order_with_request_data(currency=transaction.currency,action_type=action_type,),+ customer_ip_address=None,payment_gateway_data=PaymentGatewayData(app_identifier=webhook_app.identifier, data=data, error=None),