Skip to content

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

Remove Adyen plugin (#18735)

Lukasz Ostrowskiafe12a46dca0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 92d40fe31c..9a66aad361 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,6 +21,8 @@ All notable, unreleased changes to this project will be documented in this file.
Make sure to adapt your GraphQL queries if you use the `_entities` query.
- Mutations `channelCreate` and `channelUpdate` now raise GraphQL errors instead `INVALID` when negative `MINUTE`/`HOUR`/`DAY` values are passed.
- `AppInstallInput` for `appInstall` mutation now requires `appName` and `manifestUrl` fields in the schema, matching the validation that was always enforced by the mutation logic.
+- Removed Adyen plugin (payment gateway). [Switch to the app](https://docs.saleor.io/developer/app-store/apps/adyen/overview).
+- Removed `partial` field from the `Payment` GraphQL type. This field was an Adyen-specific workaround and always returned `false` after the Adyen plugin removal. Ensure you are not relying on this field (on Adyen gateway in general) before upgrading.
### GraphQL API
@@ -28,6 +30,7 @@ All notable, unreleased changes to this project will be documented in this file.
- `Attribute` fields `name`, `slug` and `type` are now non-nullable in schema.
- Added new scalar `NonNegativeInt` which allows integer values greater than or equal to zero.
- Scalars `Minute`, `Hour` and `Day` now inherit from `NonNegativeInt`, which mean GraphQL disallows negative values for time units.
+- Removed `partial` field from the `Payment` GraphQL type.
### Webhooks
- For order webhook events, sync webhooks (such as `ORDER_CALCULATE_TAXES` and `ORDER_FILTER_SHIPPING_METHODS`) are no longer pre-fired before sending async webhook events. Sync webhooks are now only triggered when their data is actually requested, improving performance and decoupling async event delivery from sync webhook execution.
diff --git a/pyproject.toml b/pyproject.toml
index 55576c5a03..533792e443 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -11,7 +11,6 @@ requires-python = ">=3.12,<3.13"
readme = "README.md"
license = "BSD-3-Clause"
dependencies = [
- "Adyen>=4.0.0,<5",
"asgiref>=3.7.2,<4",
"authlib>=1.6.9,<2",
"authorizenet>=1.1.5,<2",
diff --git a/saleor/graphql/payment/types.py b/saleor/graphql/payment/types.py
index aa3f8e1809..e3de78680e 100644
--- a/saleor/graphql/payment/types.py
+++ b/saleor/graphql/payment/types.py
@@ -200,10 +200,6 @@ class Payment(ModelObjectType[models.Payment]):
credit_card = graphene.Field(
CreditCard, description="The details of the card used for this payment."
)
- partial = graphene.Boolean(
- required=True,
- description="Informs whether this is a partial payment.",
- )
psp_reference = graphene.String(
required=False, description="PSP reference of the payment."
)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 7677fdb1e9..90aeb33901 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -12749,9 +12749,6 @@ type Payment implements Node & ObjectWithMetadata @doc(category: "Payments") {
"""The details of the card used for this payment."""
creditCard: CreditCard
- """Informs whether this is a partial payment."""
- partial: Boolean!
-
"""PSP reference of the payment."""
pspReference: String
}
diff --git a/saleor/order/models.py b/saleor/order/models.py
index 8869b126a6..ed64052861 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -433,12 +433,7 @@ class Order(ModelWithMetadata, ModelWithExternalReference):
return f"#{self.id}"
def get_last_payment(self) -> Payment | None:
- # Skipping a partial payment is a temporary workaround for storing a basic data
- # about partial payment from Adyen plugin. This is something that will removed
- # in 3.1 by introducing a partial payments feature.
- payments: list[Payment] = [
- payment for payment in self.payments.all() if not payment.partial
- ]
+ payments: list[Payment] = list(self.payments.all())
return max(payments, default=None, key=attrgetter("pk"))
def is_pre_authorized(self):
diff --git a/saleor/payment/gateways/adyen/__init__.py b/saleor/payment/gateways/adyen/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/saleor/payment/gateways/adyen/plugin.py b/saleor/payment/gateways/adyen/plugin.py
deleted file mode 100644
index 7fdef558f2..0000000000
--- a/saleor/payment/gateways/adyen/plugin.py
+++ /dev/null
@@ -1,855 +0,0 @@
-import json
-import logging
-from typing import Optional
-from urllib.parse import urlencode, urljoin
-
-from django.contrib.auth.hashers import make_password
-from django.core.exceptions import ObjectDoesNotExist, ValidationError
-from django.http import HttpResponse, HttpResponseNotFound
-from django.urls import reverse
-from requests.exceptions import SSLError
-
-from ....checkout.fetch import CheckoutInfo, CheckoutLineInfo
-from ....core.telemetry import saleor_attributes, tracer
-from ....core.utils import build_absolute_uri
-from ....core.utils.url import prepare_url
-from ....graphql.core import SaleorContext
-from ....order.events import external_notification_event
-from ....plugins.base_plugin import BasePlugin, ConfigurationTypeField
-from ....plugins.error_codes import PluginErrorCode
-from ....plugins.models import PluginConfiguration
-from ... import PaymentError, TransactionKind
-from ...interface import (
- GatewayConfig,
- GatewayResponse,
- InitializedPaymentResponse,
- PaymentData,
- PaymentGateway,
-)
-from ...models import Payment, Transaction
-from ..utils import get_supported_currencies
-from .utils.apple_pay import initialize_apple_pay, make_request_to_initialize_apple_pay
-from .utils.common import (
- AUTH_STATUS,
- FAILED_STATUSES,
- PENDING_STATUSES,
- api_call,
- call_capture,
- call_refund,
- get_payment_method_info,
- get_request_data_for_check_payment,
- initialize_adyen_client,
- request_data_for_gateway_config,
- request_data_for_payment,
- request_for_payment_cancel,
- update_payment_with_action_required_data,
-)
-from .webhooks import handle_additional_actions, handle_webhook
-
-GATEWAY_NAME = "Adyen"
-WEBHOOK_PATH = "/webhooks"
-ADDITIONAL_ACTION_PATH = "/additional-actions"
-
-logger = logging.getLogger(__name__)
-
-
-class AdyenGatewayPlugin(BasePlugin):
- PLUGIN_ID = "mirumee.payments.adyen"
- PLUGIN_NAME = GATEWAY_NAME
- CONFIGURATION_PER_CHANNEL = True
- DEFAULT_CONFIGURATION = [
- {"name": "merchant-account", "value": None},
- {"name": "api-key", "value": None},
- {"name": "supported-currencies", "value": ""},
- {"name": "client-key", "value": ""},
- {"name": "live", "value": ""},
- {"name": "adyen-auto-capture", "value": True},
- {"name": "auto-capture", "value": False},
- {"name": "hmac-secret-key", "value": ""},
- {"name": "notification-user", "value": ""},
- {"name": "notification-password", "value": ""},
- {"name": "enable-native-3d-secure", "value": False},
- {"name": "apple-pay-cert", "value": None},
- ]
-
- CONFIG_STRUCTURE = {
- "api-key": {
- "type": ConfigurationTypeField.SECRET,
- "help_text": (
- "To submit payments to Adyen, you'll be making API requests that are "
- "authenticated with an API key. You can generate API keys on your "
- "Customer Area."
- ),
- "label": "API key",
- },
- "merchant-account": {
- "type": ConfigurationTypeField.STRING,
- "help_text": "Your merchant account name.",
- "label": "Merchant Account",
- },
- "supported-currencies": {
- "type": ConfigurationTypeField.STRING,
- "help_text": "Determines currencies supported by gateway."
- " Please enter currency codes separated by a comma.",
- "label": "Supported currencies",
- },
- "client-key": {
- "type": ConfigurationTypeField.STRING,
- "help_text": (
- "The client key is a public key that uniquely identifies a web service "
- "user. Each web service user has a list of allowed origins, or domains "
- "from which we expect to get your requests. We make sure data cannot "
- "be accessed by unknown parties by using Cross-Origin Resource Sharing."
- "Not required for Android or iOS app."
- ),
- "label": "Client Key",
- },
- "live": {
- "type": ConfigurationTypeField.STRING,
- "help_text": (
- "Leave it blank when you want to use test env. To communicate with the"
- " Adyen API you should submit HTTP POST requests to corresponding "
- "endpoints. These endpoints differ for test and live accounts, and also"
- " depend on the data format (SOAP, JSON, or FORM) you use to submit "
- "data to the Adyen payments platform. "
- "https://docs.adyen.com/development-resources/live-endpoints"
- ),
- "label": "Live",
- },
- "adyen-auto-capture": {
- "type": ConfigurationTypeField.BOOLEAN,
- "help_text": (
- "All authorized payments will be marked as captured. This should only"
- " be enabled if Adyen is configured to auto-capture payments."
- " Saleor doesn't support the delayed capture Adyen feature."
- ),
- "label": "Assume all authorizations are automatically captured by Adyen",
- },
- "auto-capture": {
- "type": ConfigurationTypeField.BOOLEAN,
- "help_text": (
- "If enabled, Saleor will automatically capture funds. If, disabled, the"
- " funds are blocked but need to be captured manually."
- ),
- "label": "Automatically capture funds when a payment is made",
- },
- "hmac-secret-key": {
- "type": ConfigurationTypeField.SECRET,
- "help_text": (
- "Provide secret key generated on Adyen side."
- "https://docs.adyen.com/development-resources/webhooks#set-up-notificat"
- "ions-in-your-customer-area."
- ),
- "label": "HMAC secret key",
- },
- "notification-user": {
- "type": ConfigurationTypeField.STRING,
- "help_text": (
- "Base User provided on the Adyen side to authenticate incoming "
- "notifications. https://docs.adyen.com/development-resources/webhooks#"
- "set-up-notifications-in-your-customer-area "
- ),
- "label": "Notification user",
- },
- "notification-password": {
- "type": ConfigurationTypeField.SECRET,
- "help_text": (
- "User password provided on the Adyen side for authenticate incoming "
- "notifications. https://docs.adyen.com/development-resources/webhooks#"
- "set-up-notifications-in-your-customer-area "
- ),
- "label": "Notification password",
- },
- "enable-native-3d-secure": {
- "type": ConfigurationTypeField.BOOLEAN,
- "help_text": (
- "Saleor uses 3D Secure redirect authentication by default. If you want"
- " to use native 3D Secure authentication, enable this option. For more"
- " details see Adyen documentation: native - "
- "https://docs.adyen.com/checkout/3d-secure/native-3ds2, redirect"
- " - https://docs.adyen.com/checkout/3d-secure/redirect-3ds2-3ds1"
- ),
- "label": "Enable native 3D Secure",
- },
- "apple-pay-cert": {
- "type": ConfigurationTypeField.SECRET_MULTILINE,
- "help_text": (
- "Follow the Adyen docs related to activating the Apple Pay for the "
- "web - https://docs.adyen.com/payment-methods/apple-pay/"
- "enable-apple-pay. This certificate is only required when you offer "
- "the Apple Pay as a web payment method. Leave it blank if you don't "
- "offer Apple Pay or offer it only as a payment method in your iOS app."
- ),
- "label": "Apple Pay certificate",
- },
- "webhook-endpoint": {
- "type": ConfigurationTypeField.OUTPUT,
- "help_text": (
- "Endpoint which should be used to activate Adyen's webhooks. "
- "More details can be find here: "
- "https://docs.adyen.com/development-resources/webhooks"
- ),
- "label": "Webhook endpoint",
- },
- }
-
- def __init__(self, *args, **kwargs):
- channel = kwargs["channel"]
- raw_configuration = kwargs["configuration"].copy()
- self._insert_webhook_endpoint_to_configuration(raw_configuration, channel)
- kwargs["configuration"] = raw_configuration
-
- super().__init__(*args, **kwargs)
- configuration = {item["name"]: item["value"] for item in self.configuration}
- self.config = GatewayConfig(
- gateway_name=GATEWAY_NAME,
- auto_capture=configuration["auto-capture"],
- supported_currencies=configuration["supported-currencies"],
- connection_params={
- "api_key": configuration["api-key"],
- "merchant_account": configuration["merchant-account"],
- "client_key": configuration["client-key"],
- "live": configuration["live"],
- "webhook_hmac": configuration["hmac-secret-key"],
- "webhook_user": configuration["notification-user"],
- "webhook_user_password": configuration["notification-password"],
- "adyen_auto_capture": configuration["adyen-auto-capture"],
- "enable_native_3d_secure": configuration["enable-native-3d-secure"],
- "apple_pay_cert": configuration["apple-pay-cert"],
- },
- )
- self.adyen = initialize_adyen_client(self.config)
-
- def _insert_webhook_endpoint_to_configuration(self, raw_configuration, channel):
- updated = False
- for config in raw_configuration:
- if config["name"] == "webhook-endpoint":
- updated = True
- config["value"] = self._generate_webhook_url(channel)
- if not updated:
- raw_configuration.append(
- {
- "name": "webhook-endpoint",
- "value": self._generate_webhook_url(channel),
- }
- )
-
- def _generate_webhook_url(self, channel) -> str:
- api_path = reverse(
- "plugins-per-channel",
- kwargs={"plugin_id": self.PLUGIN_ID, "channel_slug": channel.slug},
- )
- base_url = build_absolute_uri(api_path)
- return urljoin(base_url, "webhooks")
-
- def webhook(
- self, request: SaleorContext, path: str, previous_value
- ) -> HttpResponse:
- """Handle a request received from Adyen.
-
- The method handles two types of requests:
- - webhook notification received from Adyen. It is required to properly
- update the current status of payment and order based on the type of
- received notification.
- - additional actions, called when a user is redirected to an external page
- and after processing a payment is redirecting back to the storefront page.
- The redirect request comes through the Saleor which calls Adyen API to
- validate the current status of payment.
- """
- if not self.channel:
- return HttpResponseNotFound()
- config = self._get_gateway_config()
- if path.startswith(WEBHOOK_PATH):
- return handle_webhook(request, config)
- if path.startswith(ADDITIONAL_ACTION_PATH):
- with tracer.start_as_current_span("adyen.checkout.payment_details") as span:
- span.set_attribute(saleor_attributes.COMPONENT, "payment")
- return handle_additional_actions(
- request, self.adyen.checkout.payments_details, self.channel.slug
- )
- return HttpResponseNotFound()
-
- def _get_gateway_config(self) -> GatewayConfig:
- return self.config
-
- def token_is_required_as_payment_input(self, previous_value):
- if not self.active:
- return previous_value
- return False
-
- def initialize_payment(
- self, payment_data, previous_value
- ) -> "InitializedPaymentResponse":
- """Initialize a payment for ApplePay.
-
- ApplePay requires an additional action that initializes a payment action. It is
- done by a separate mutation which calls this method.
- """
- if not self.active:
- return previous_value
- payment_method = payment_data.get("paymentMethod")
- if payment_method == "applepay":
- # The apple pay on the web requires additional step
- session_obj = initialize_apple_pay(
- payment_data, self.config.connection_params["apple_pay_cert"]
- )
- return InitializedPaymentResponse(
- gateway=self.PLUGIN_ID, name=self.PLUGIN_NAME, data=session_obj
- )
- return previous_value
-
- def get_payment_gateways(
- self,
- currency: str | None,
- checkout_info: Optional["CheckoutInfo"],
- checkout_lines: list["CheckoutLineInfo"] | None,
- previous_value,
- ) -> list["PaymentGateway"]:
- """Fetch current configuration for given checkout.
-
- It calls an Adyen API to fetch all available payment methods for given checkout.
- Adyen defines available payment methods based on the data that we send like
- amount, currency, and country. Some payment methods are only available if the
- given data matches their conditions. Like to display payment method X, which is
- available in UK, we need to set GBP as currency, and country-code needs to
- point to UK. We don't fetch anything if checkout is none, as we don't have
- enough info to provide the required data in the request.
- """
- if not self.active:
- return previous_value
- local_config = self._get_gateway_config()
- config = [
- {
- "field": "client_key",
- "value": local_config.connection_params["client_key"],
- }
- ]
-
- if checkout_info:
- # If checkout is available, fetch available payment methods from Adyen API
- # and append them to the config object returned for the gateway.
- request = request_data_for_gateway_config(
- checkout_info,
- checkout_lines,
- local_config.connection_params["merchant_account"],
- )
- with tracer.start_as_current_span("adyen.checkout.payment_methods") as span:
- span.set_attribute(saleor_attributes.COMPONENT, "payment")
- response = api_call(request, self.adyen.checkout.payment_methods)
- adyen_payment_methods = json.dumps(response.message)
- config.append({"field": "config", "value": adyen_payment_methods})
-
- gateway = PaymentGateway(
- id=self.PLUGIN_ID,
- name=self.PLUGIN_NAME,
- config=config,
- currencies=self.get_supported_currencies([]),
- )
- return [gateway]
-
- def check_payment_balance(self, data: dict, previous_value) -> dict:
- """Check current payment balance.
-
- For Adyen, we use it only for checking the balance of the gift cards. It builds
- a request based on the input and send a request to Adyen's API.
- """
- if not self.active:
- return previous_value
- request_data = get_request_data_for_check_payment(
- data, self.config.connection_params["merchant_account"]
- )
-
- with tracer.start_as_current_span(
- "adyen.checkout.payment_methods_balance"
- ) as span:
- span.set_attribute(saleor_attributes.COMPONENT, "payment")
- try:
- result = api_call(
- request_data,
- self.adyen.checkout.client.call_checkout_api,
- action="paymentMethods/balance",
- )
- return result.message
- except PaymentError as e:
- return e.message
-
- @property
- def order_auto_confirmation(self):
- if self.channel is None:
- return False
- return self.channel.automatically_confirm_all_new_orders
-
- def _normalize_response_field(self, field: str) -> str:
- """Normalize response field to lowercase and remove spaces."""
- return field.strip().lower()
-
- def process_payment(
- self, payment_information: "PaymentData", previous_value
- ) -> "GatewayResponse":
- """Process a payment on Adyen's side.
-
- This method is called when payment.to_confirm is set to False.
- It builds a request data required for a given payment method and sends the data
- to Adyen's side.
- If Adyen doesn't return any additional action required and the result code is
- a success, the payment is finalized with success. If auto_capture is set to
- True, and the payment status is AUTH, it will immediately call capture.
- If Adyen returns an additional action to process by customer, the payment is
- not finished yet. In that case, in the response from the method, we set
- action_required and add to action_required_data all Adyen's data required to
- finalize payment by the customer.
- """
- if not self.active:
- return previous_value
- try:
- payment = Payment.objects.get(pk=payment_information.payment_id)
- except ObjectDoesNotExist as e:
- raise PaymentError(
- "Payment cannot be performed. Payment does not exists."
- ) from e
-
- checkout = payment.checkout
- if checkout is None:
- raise PaymentError(
- "Payment cannot be performed. Checkout for this payment does not exist."
- )
-
- params = urlencode(
- {"payment": payment_information.graphql_payment_id, "checkout": checkout.pk}
- )
- return_url = prepare_url(
- params,
- build_absolute_uri(
- f"/plugins/channel/{self.channel.slug}/" # type: ignore[union-attr]
- f"{self.PLUGIN_ID}/additional-actions"
- ),
- )
- request_data = request_data_for_payment(
- payment_information,
- return_url=return_url,
- merchant_account=self.config.connection_params["merchant_account"],
- native_3d_secure=self.config.connection_params["enable_native_3d_secure"],
- )
- with tracer.start_as_current_span("adyen.checkout.payments") as span:
- span.set_attribute(saleor_attributes.COMPONENT, "payment")
- result = api_call(request_data, self.adyen.checkout.payments)
- result_code = self._normalize_response_field(result.message["resultCode"])
- is_success = result_code not in FAILED_STATUSES
- adyen_auto_capture = self.config.connection_params["adyen_auto_capture"]
- kind = TransactionKind.AUTH
- if result_code in PENDING_STATUSES:
- kind = TransactionKind.PENDING
- elif adyen_auto_capture:
- kind = TransactionKind.CAPTURE
- psp_reference = result.message.get("pspReference", "")
- action = result.message.get("action")
- error_message = result.message.get("refusalReason")
- if action:
- update_payment_with_action_required_data(
- payment,
- action,
- result.message.get("details", []),
- )
- # If auto capture is enabled, let's make a capture the auth payment
- elif (
- self.config.auto_capture
- and result_code == AUTH_STATUS
- and self.order_auto_confirmation
- ):
- kind = TransactionKind.CAPTURE
- result = call_capture(
- payment_information=payment_information,
- merchant_account=self.config.connection_params["merchant_account"],
- token=result.message.get("pspReference"),
- adyen_client=self.adyen,
- )
- payment_method_info = get_payment_method_info(payment_information, result)
- return GatewayResponse(
- is_success=is_success,
- action_required="action" in result.message,
- kind=kind,
- amount=payment_information.amount,
- currency=payment_information.currency,
- transaction_id=result.message.get("pspReference", ""),
- error=error_message,
- action_required_data=action,
- payment_method_info=payment_method_info,
- psp_reference=psp_reference,
- legacy_adyen_plugin_payment_method=self._normalize_response_field(
- result.message.get("paymentMethod", "")
- ),
- legacy_adyen_plugin_result_code=self._normalize_response_field(
- result.message.get("resultCode", "")
- ),
- )
-
- @classmethod
- def _update_config_items(
- cls, configuration_to_update: list[dict], current_config: list[dict]
- ):
- for item in configuration_to_update:
- if item.get("name") == "notification-password" and item["value"]:
- item["value"] = make_password(item["value"])
- super()._update_config_items(configuration_to_update, current_config)
-
- def get_payment_config(self, previous_value):
- if not self.active:
- return previous_value
- return []
-
- def get_supported_currencies(self, previous_value):
- if not self.active:
- return previous_value
- config = self._get_gateway_config()
- return get_supported_currencies(config, GATEWAY_NAME)
-
- def _process_additional_action(self, payment_information: "PaymentData", kind: str):
- config = self._get_gateway_config()
- additional_data = payment_information.data
- if not additional_data:
- return GatewayResponse(
- is_success=False,
- action_required=False,
- kind=kind,
- amount=payment_information.amount,
- currency=payment_information.currency,
- transaction_id="",
- error=f"Unable to finish the payment. "
- f"Payment ({payment_information.graphql_payment_id}) "
- f"does not have the additional data.",
- )
-
- with tracer.start_as_current_span("adyen.checkout.payment_details") as span:
- span.set_attribute(saleor_attributes.COMPONENT, "payment")
- result = api_call(additional_data, self.adyen.checkout.payments_details)
- result_code = self._normalize_response_field(result.message["resultCode"])
- is_success = result_code not in FAILED_STATUSES
- action_required = "action" in result.message
- if result_code in PENDING_STATUSES:
- kind = TransactionKind.PENDING
- elif (
- is_success
- and config.auto_capture
- and self.order_auto_confirmation
- and not action_required
- ):
- # For enabled auto_capture on Saleor side we need to proceed an additional
- # action
- kind = TransactionKind.CAPTURE
- result = call_capture(
- payment_information=payment_information,
- merchant_account=self.config.connection_params["merchant_account"],
- token=result.message.get("pspReference"),
- adyen_client=self.adyen,
- )
-
- payment_method_info = get_payment_method_info(payment_information, result)
- action = result.message.get("action")
- return GatewayResponse(
- is_success=is_success,
- action_required=action_required,
- action_required_data=action,
- kind=kind,
- amount=payment_information.amount,
- currency=payment_information.currency,
- transaction_id=result.message.get("pspReference", ""),
- error=result.message.get("refusalReason"),
- psp_reference=result.message.get("pspReference", ""),
- payment_method_info=payment_method_info,
- legacy_adyen_plugin_payment_method=self._normalize_response_field(
- result.message.get("paymentMethod", "")
- ),
- legacy_adyen_plugin_result_code=self._normalize_response_field(
- result.message.get("resultCode", "")
- ),
- )
-
- def confirm_payment(
- self, payment_information: "PaymentData", previous_value
- ) -> "GatewayResponse":
- """Confirm a payment on Adyen side.
-
- In case when we have a transaction with `ACTION_TO_CONFIRM`, we just need to
- finalize the payment process on our side. Transaction ACTION_TO_CONFIRM is
- created only when we receive a webhook with a notification that the payment
- process has been finished with success.
- In case when we can't find an ACTION_TO_CONFIRM transaction, we call logic
- responsible for confirming additional data received as an input. The data
- comes from the storefront when the customer finishes an additional action,
- which was requested in process_payment call. We still check the value of the
- action field in the Adyen's response, as there is a possibility that the given
- payment method will require more additional actions. In that case, we will
- return action_required set to True and action_required_data fulfilled with
- action data received from Adyen and required for the next additional action on
- the customer side.
- """
- if not self.active:
- return previous_value
- config = self._get_gateway_config()
- # The additional checks are proceed asynchronously so we try to confirm that
- # the payment is already processed
- payment = Payment.objects.filter(id=payment_information.payment_id).first()
- if not payment:
- raise PaymentError("Unable to find the payment.")
-
- transaction = (
- payment.transactions.filter(
- kind=TransactionKind.ACTION_TO_CONFIRM,
- is_success=True,
- action_required=False,
- )
- .exclude(token__isnull=False, token__exact="")
- .last()
- )
-
- adyen_auto_capture = self.config.connection_params["adyen_auto_capture"]
- kind = TransactionKind.AUTH
- if adyen_auto_capture or config.auto_capture:
- kind = TransactionKind.CAPTURE
-
- if not transaction:
- # We don't have async notification for this payment so we try to proceed
- # standard flow for confirming an additional action
- return self._process_additional_action(payment_information, kind)
-
- result_code_temporary_field = transaction.legacy_adyen_plugin_result_code
- payment_method_temporary_field = transaction.legacy_adyen_plugin_payment_method
-
- if result_code_temporary_field:
- result_code = result_code_temporary_field
- else:
- result_code = self._normalize_response_field(
- transaction.gateway_response.get("resultCode", "")
- )
-
- if payment_method_temporary_field:
- payment_method = payment_method_temporary_field
- else:
- payment_method = self._normalize_response_field(
- transaction.gateway_response.get("paymentMethod", "")
- )
-
- if result_code and result_code in PENDING_STATUSES:
- kind = TransactionKind.PENDING
- elif result_code == AUTH_STATUS and payment_method == "ideal":
- kind = TransactionKind.CAPTURE
-
- # We already have the ACTION_TO_CONFIRM transaction, it means that
- # payment was processed asynchronous and no additional action is required
-
- # Check if we didn't process this transaction asynchronously
- transaction_already_processed = payment.transactions.filter(
- kind=kind,
- is_success=True,
- action_required=False,
- amount=payment_information.amount,
- currency=payment_information.currency,
- ).first()
- is_success = True
-
- # confirm that we should proceed the capture action
- if (
- not transaction_already_processed
- and config.auto_capture
- and kind == TransactionKind.CAPTURE
- ):
- response = self.capture_payment(payment_information, None)
- is_success = response.is_success
-
- token = transaction.token
- if transaction_already_processed:
- token = transaction_already_processed.token
-
- return GatewayResponse(
- is_success=is_success,
- action_required=False,
- kind=kind,
- amount=payment_information.amount,
- currency=payment_information.currency,
- transaction_id=token,
- error=None,
- transaction_already_processed=bool(transaction_already_processed),
- psp_reference=token,
- )
-
- def refund_payment(
- self, payment_information: "PaymentData", previous_value
- ) -> "GatewayResponse":
- if not self.active:
- return previous_value
- # we take Auth kind because it contains the transaction id that we need
- transaction = (
- Transaction.objects.filter(
- payment__id=payment_information.payment_id,
- kind=TransactionKind.AUTH,
- is_success=True,
- )
- .exclude(token__isnull=False, token__exact="")
- .last()
- )
-
- if not transaction:
- # If we don't find the Auth kind we will try to get Capture kind
- transaction = (
- Transaction.objects.filter(
- payment__id=payment_information.payment_id,
- kind=TransactionKind.CAPTURE,
- is_success=True,
- )
- .exclude(token__isnull=False, token__exact="")
- .last()
- )
-
- if not transaction:
- raise PaymentError("Cannot find a payment reference to refund.")
-
- amount = payment_information.amount
- currency = payment_information.currency
-
- result = call_refund(
- amount=amount,
- currency=currency,
- graphql_payment_id=payment_information.graphql_payment_id,
- merchant_account=self.config.connection_params["merchant_account"],
- token=transaction.token,
- adyen_client=self.adyen,
- )
-
- if transaction.payment.order:
- msg = f"Adyen: Refund for amount {amount}{currency} has been requested."
- external_notification_event(
- order=transaction.payment.order,
- user=None,
- app=None,
- message=msg,
- parameters={
- "service": transaction.payment.gateway,
- "id": transaction.payment.token,
- },
- )
- return GatewayResponse(
- is_success=True,
- action_required=False,
- kind=TransactionKind.REFUND_ONGOING,
- amount=amount,
- currency=currency,
- transaction_id=result.message.get("pspReference", ""),
- error="",
- psp_reference=result.message.get("pspReference", ""),
- legacy_adyen_plugin_payment_method=self._normalize_response_field(
- result.message.get("paymentMethod", "")
- ),
- legacy_adyen_plugin_result_code=self._normalize_response_field(
- result.message.get("resultCode", "")
- ),
- )
-
- def capture_payment(
- self, payment_information: "PaymentData", previous_value
- ) -> "GatewayResponse":
- if not self.active:
- return previous_value
-
- if not payment_information.token:
- raise PaymentError("Cannot find a payment reference to capture.")
-
- result = call_capture(
- payment_information=payment_information,
- merchant_account=self.config.connection_params["merchant_account"],
- token=payment_information.token,
- adyen_client=self.adyen,
- )
-
- payment_method_info = get_payment_method_info(payment_information, result)
-
- return GatewayResponse(
- is_success=True,
- action_required=False,
- kind=TransactionKind.CAPTURE,
- amount=payment_information.amount,
- currency=payment_information.currency,
- transaction_id=result.message.get("pspReference", ""),
- error="",
- payment_method_info=payment_method_info,
- psp_reference=result.message.get("pspReference", ""),
- legacy_adyen_plugin_payment_method=self._normalize_response_field(
- result.message.get("paymentMethod", "")
- ),
- legacy_adyen_plugin_result_code=self._normalize_response_field(
- result.message.get("resultCode", "")
- ),
- )
-
- def void_payment(
- self, payment_information: "PaymentData", previous_value
- ) -> "GatewayResponse":
- if not self.active:
- return previous_value
-
- if not payment_information.token:
- raise PaymentError("Cannot find a payment reference to void.")
-
- request = request_for_payment_cancel(
- payment_information=payment_information,
- merchant_account=self.config.connection_params["merchant_account"],
- token=payment_information.token,
- )
- with tracer.start_as_current_span("adyen.payment.cancel") as span:
- span.set_attribute(saleor_attributes.COMPONENT, "payment")
- result = api_call(request, self.adyen.payment.cancel)
-
- return GatewayResponse(
- is_success=True,
- action_required=False,
- kind=TransactionKind.VOID,
- amount=payment_information.amount,
- currency=payment_information.currency,
- transaction_id=result.message.get("pspReference", ""),
- error="",
- psp_reference=result.message.get("pspReference", ""),
- legacy_adyen_plugin_payment_method=self._normalize_response_field(
- result.message.get("paymentMethod", "")
- ),
- legacy_adyen_plugin_result_code=self._normalize_response_field(
- result.message.get("resultCode", "")
- ),
- )
-
- @classmethod
- def validate_plugin_configuration(
- cls, plugin_configuration: "PluginConfiguration", **kwargs
- ):
- """Validate if provided configuration is correct."""
- configuration = plugin_configuration.configuration
- configuration = {item["name"]: item["value"] for item in configuration}
- apple_certificate = configuration.get("apple-pay-cert")
- if plugin_configuration.active and apple_certificate:
- global_apple_url = (
- "https://apple-pay-gateway.apple.com/paymentservices/paymentSession"
- )
- request_data = {
- "merchantIdentifier": "",
- "displayName": "",
- "initiative": "web",
- "initiativeContext": "",
- }
- # Try to exectue the session request without all required data. If the
- # apple certificate is correct we will get the error related to the missing
- # parameters. If certificate is incorrect, the SSL error will be raised.
- try:
- make_request_to_initialize_apple_pay(
- validation_url=global_apple_url,
- request_data=request_data,
- certificate=apple_certificate,
- )
- except SSLError as e:
- raise ValidationError(
- {
- "apple-pay-cert": ValidationError(
- "The provided apple certificate is invalid.",
- code=PluginErrorCode.INVALID.value,
- )
- }
- ) from e
- except Exception:
- pass
diff --git a/saleor/payment/gateways/adyen/tests/__init__.py b/saleor/payment/gateways/adyen/tests/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/saleor/payment/gateways/adyen/tests/cassettes/test_plugin/test_capture_payment.yaml b/saleor/payment/gateways/adyen/tests/cassettes/test_plugin/test_capture_payment.yaml
deleted file mode 100644
index eb382ecabb..0000000000
--- a/saleor/payment/gateways/adyen/tests/cassettes/test_plugin/test_capture_payment.yaml
+++ /dev/null
@@ -1,49 +0,0 @@
-interactions:
-- request:
- body: '{"merchantAccount": "SaleorECOM", "modificationAmount": {"value": "8000",
- "currency": "USD"}, "originalReference": "882595494831959A", "reference": "UGF5bWVudDoxMTQ0",
- "applicationInfo": {"adyenLibrary": {"name": "adyen-python-api-library", "version":
- "4.0.0"}}}'
- headers:
- Accept:
- - '*/*'
- Accept-Encoding:
- - gzip, deflate
- Connection:
- - keep-alive
- Content-Length:
- - '262'
- Content-Type:
- - application/json
- User-Agent:
- - adyen-python-api-library/4.0.0
- x-api-key:
- - test_key
- method: POST
- uri: https://pal-test.adyen.com/pal/servlet/Payment/v64/capture
- response:
- body:
- string: '{"pspReference":"852610007697063J","response":"[capture-received]"}'
- headers:
- Adyen-ServerState:
- - MEDIUM
- Connection:
- - Keep-Alive
- Content-Type:
- - application/json;charset=utf-8
- Date:
- - Thu, 07 Jan 2021 08:21:37 GMT
- Keep-Alive:
- - timeout=15, max=100
- Server:
- - Apache
- Set-Cookie:
- - JSESSIONID=014140433CC0DF32218EF2A20C65AF6D.test3e; Path=/pal; Secure; HttpOnly
- Transfer-Encoding:
- - chunked
- pspReference:
- - 852610007697063J
- status:
- code: 200
- message: OK
-version: 1
diff --git a/saleor/payment/gateways/adyen/tests/cassettes/test_plugin/test_get_payment_gateway_for_checkout.yaml b/saleor/payment/gateways/adyen/tests/cassettes/test_plugin/test_get_payment_gateway_for_checkout.yaml
deleted file mode 100644
index 44b0c981cf..0000000000
--- a/saleor/payment/gateways/adyen/tests/cassettes/test_plugin/test_get_payment_gateway_for_checkout.yaml
+++ /dev/null
@@ -1,49 +0,0 @@
-interactions:
-- request:
- body: '{"merchantAccount": "SaleorECOM", "countryCode": "PL", "channel": "web",
- "amount": {"value": "1000", "currency": "USD"}}'
- headers:
- Accept:
- - '*/*'
- Accept-Encoding:
- - gzip, deflate
- Connection:
- - keep-alive
- Content-Length:
- - '120'
- Content-Type:
- - application/json
- User-Agent:
- - adyen-python-api-library/4.0.0
- x-api-key:
- - test_key
- method: POST
- uri: https://checkout-test.adyen.com/v64/paymentMethods
- response:
- body:
- string: '{"groups":[{"name":"Credit Card","types":["visa","mc","amex","diners","discover"]}],"paymentMethods":[{"brands":["visa","mc","amex","diners","discover"],"details":[{"key":"encryptedCardNumber","type":"cardToken"},{"key":"encryptedSecurityCode","type":"cardToken"},{"key":"encryptedExpiryMonth","type":"cardToken"},{"key":"encryptedExpiryYear","type":"cardToken"},{"key":"holderName","optional":true,"type":"text"}],"name":"Credit
- Card","type":"scheme"},{"configuration":{"intent":"capture"},"name":"PayPal","supportsRecurring":true,"type":"paypal"},{"name":"Paysafecard","supportsRecurring":true,"type":"paysafecard"},{"configuration":{"merchantDisplayName":"SaleorECOM","merchantIdentifier":"1000"},"details":[{"key":"applepay.token","type":"applePayToken"}],"name":"Apple
- Pay","supportsRecurring":true,"type":"applepay"},{"configuration":{"merchantId":"1000","gatewayMerchantId":"SaleorECOM"},"details":[{"key":"paywithgoogle.token","type":"payWithGoogleToken"}],"name":"Google
- Pay","supportsRecurring":true,"type":"paywithgoogle"}]}'
- headers:
- Connection:
- - Keep-Alive
- Content-Type:
- - application/json;charset=UTF-8
- Date:
- - Thu, 07 Jan 2021 08:30:32 GMT
- Keep-Alive:
- - timeout=15, max=100
- Server:
- - Apache
- Set-Cookie:
- - JSESSIONID=BF32081F757B98CBB0DD5177B5497D87.test3e; Path=/checkout; Secure;
- HttpOnly
- Transfer-Encoding:
- - chunked
- pspReference:
- - 851610008232020A
- status:
- code: 200
- message: OK
-version: 1
diff --git a/saleor/payment/gateways/adyen/tests/cassettes/test_plugin/test_process_payment.yaml b/saleor/payment/gateways/adyen/tests/cassettes/test_plugin/test_process_payment.yaml
deleted file mode 100644
index f0dd22f95f..0000000000
--- a/saleor/payment/gateways/adyen/tests/cassettes/test_plugin/test_process_payment.yaml
+++ /dev/null
@@ -1,50 +0,0 @@
-interactions:
-- request:
- body: '{"amount": {"value": "8000", "currency": "USD"}, "reference": "UGF5bWVudDoxMTM3",
- "paymentMethod": {"type": "scheme", "encryptedCardNumber": "test_4646464646464644",
- "encryptedExpiryMonth": "test_03", "encryptedExpiryYear": "test_2030", "encryptedSecurityCode":
- "test_737"}, "returnUrl": "https://example.com/plugins/mirumee.payments.adyen/additional-actions?payment=UGF5bWVudDoxMTM3&checkout=dd45b15c-e50f-4734-9166-cb19b7da75d3",
- "merchantAccount": "SaleorECOM", "channel": "web", "shopperEmail": "", "applicationInfo":
- {"adyenLibrary": {"name": "adyen-python-api-library", "version": "4.0.0"}}}'
- headers:
- Accept:
- - '*/*'
- Accept-Encoding:
- - gzip, deflate
- Connection:
- - keep-alive
- Content-Length:
- - '596'
- Content-Type:
- - application/json
- User-Agent:
- - adyen-python-api-library/4.0.0
- x-api-key:
- - test_key
- method: POST
- uri: https://checkout-test.adyen.com/v64/payments
- response:
- body:
- string: '{"additionalData":{"paymentMethod":"visa"},"pspReference":"882609854544793A","resultCode":"Authorised","amount":{"currency":"USD","value":8000},"merchantReference":"UGF5bWVudDoxMTM3"}'
- headers:
- Connection:
- - Keep-Alive
- Content-Type:
- - application/json;charset=UTF-8
- Date:
- - Tue, 05 Jan 2021 13:49:04 GMT
- Keep-Alive:
- - timeout=15, max=100
- Server:
- - Apache
- Set-Cookie:
- - JSESSIONID=61CCDC10C5283298648628594A8C50EE.test3e; Path=/checkout; Secure;
- HttpOnly
- Transfer-Encoding:
- - chunked
- pspReference:
- - 851609854544380B
- status:
- code: 200
- message: OK
-version: 1
diff --git a/saleor/payment/gateways/adyen/tests/cassettes/test_plugin/test_process_payment_with_3ds_redirect.yaml b/saleor/payment/gateways/adyen/tests/cassettes/test_plugin/test_process_payment_with_3ds_redirect.yaml
deleted file mode 100644
index 823efa3222..0000000000
--- a/saleor/payment/gateways/adyen/tests/cassettes/test_plugin/test_process_payment_with_3ds_redirect.yaml
+++ /dev/null
@@ -1,54 +0,0 @@
-interactions:
-- request:
- body: '{"amount": {"value": "8000", "currency": "USD"}, "reference": "UGF5bWVudDoxMDM=",
- "paymentMethod": {"type": "scheme", "encryptedCardNumber": "test_4917610000000000",
- "encryptedExpiryMonth": "test_03", "encryptedExpiryYear": "test_2030", "encryptedSecurityCode":
- "test_737", "brand": "visa"}, "returnUrl": "https://example.com/plugins/mirumee.payments.adyen/additional-actions?payment=UGF5bWVudDoxMDM%3D&checkout=08546530-4718-422c-a912-9a1642a9031c",
- "merchantAccount": "SaleorECOM", "browserInfo": {"acceptHeader": "*/*", "colorDepth":
- 24, "language": "en-US", "javaEnabled": false, "screenHeight": 1080, "screenWidth":
- 1920, "userAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML,
- like Gecko) Chrome/89.0.4389.90 Safari/537.36", "timeZoneOffset": -120}, "channel":
- "web", "shopperEmail": "", "applicationInfo": {"adyenLibrary": {"name": "adyen-python-api-library",
- "version": "4.0.0"}}}'
- headers:
- Accept:
- - '*/*'
- Accept-Encoding:
- - gzip, deflate
- Connection:
- - keep-alive
- Content-Length:
- - '904'
- Content-Type:
- - application/json
- User-Agent:
- - adyen-python-api-library/4.0.0
- x-api-key:
- - test_key
- method: POST
- uri: https://checkout-test.adyen.com/v64/payments
- response:
- body:
- string: '{"resultCode":"RedirectShopper","action":{"paymentData":"Ab02b4c0!BQABAgA1Xk1nQmoiOJCEtVVdsDKBm0L9nW8T6NbdlRla9BsZHojoiRTZFldU5FqmUGzPBTOjJzl6nSpVvpModrodHiIRJPN9w\/AciIHNBDXb\/Ws7gdsJjSAZHgCXZq2AUx1wGpXUg47BhDus2MHITLLNEnli63Z7Ec5dpG28JCJISwi1prh8bev+riPQrdzShFvke78wPQDvm2v6PnS0bNE71b826I4audbxweA\/yC02nSsKR3qGKGbjigbl3Z6xLdaphuYrqhYvXCNd3bzypQ8E40vq7uJN7cV9G8mzsERen1B4rlLBxoft5P4fYMpDcd6CJueKn1IHpPW7wOITsStNnhKM7WAa+uM9gAtPbUoTE1TQEV7oGi0o3ARjZv2E2Sdy3TIfqFTr39HPyoUSRmo+Ge6nX0wp4PIg19+KnmsCBdvYYB0mzzjSAwiWpcxGO0fJ9nH2zpS4mA2vsXbsA9z7vto0bcpuDC8eCMUSC\/TdDPzA2+u7JAZgqZp6eTVzX6eh6pC1MW5+nVTLCKdU97xX6xwaxbzVGOeXQpUbPpaztDzVUJFxxxuI15vhPskmiuXzaXD3DQNNjRUpwAbX58TfeeZd9gRWJ\/IhMZWNXAswpIIqXO2HS+PIKFGpznQDJbFcifQA6m9auwGqnbBrvC+QWcIDaSbG+JQ16KQNeZnF5qp0FxCs8hOM5c7NXU3D9TMLM5WdAEp7ImtleSI6IkFGMEFBQTEwM0NBNTM3RUFFRDg3QzI0REQ1MzkwOUI4MEE3OEE5MjNFMzgyM0Q2OERBQ0M5NEI5RkY4MzA1REMifZBA6Vt\/IW\/eRndJuQrwM7CD54KrDi8ssSCeoec3F97rp++BzLX9QEHI4SLetMHYN9b2SDM5qdOjeIG1XldAfCgl2Swkh9U2VoXZCLfU6it5a9xoA8rrnJJhpj58\/khW+RMYOqVSsSbjnlnzctlUXi1Epmb8OxDS8XUCnZmqv57I3MXPVRUWM68ZKClAE0D5npPhc0H\/QJHeXj+l+o5v5quCCW09zu2V1EAQNsgoQ4217NJbeM98EcOuN8vphM50RyGSbBqtfIrSGJ1+tr2VIIsM9QTOC4KtraFKq34wXL1KoU+\/C3Z03jPbYA9BxVotI7pbra4UnpJ6XU3U7Ezj0XaLXVrwP4OdjzV2ISSLUdDoo\/NtChHIO0J3aQuhEtQvOs3a+GPgbzIAYxunjejsZeNZGkaZSaHIY2CxlK3vOYR4R7vAXqV+Y6qAOOSBPvxmspn5XabK7gpTzSStO6SBDX1+IeMKZGXp+vexP0+5R4sHOb5djDMmAdszc9Koh4\/BzgEBvbRCBobn7UjBhZsiYaqB\/Q7ZBDHvH2Dn7Nig4JPHprqpdc5oH4IfoJ2GXTe8NtQKeMQH37MxnN+FBzGqM4ixc8Tkra3QJ9jP9gXAqZXUhUWhoTN7DBAm\/+MEyCnHGCYorIAVv0ns9o9WZGoDuNzAbJc8jpwurktsRy8sUL+vig\/h5\/TcLNjtRcruSH8+wSNM3Z2YztAuEaBbS7JonasJRMMucYkgNiD51mBdR0aoWMXfvRZUdQmKqCMHRQSNDSbvWG+rjHWAgcTzAjT19oMWZemiqjqJ00mHbpRwr\/0zeHSpdBUQ\/hLYTr9+fdVgmxwA7Iee\/FVgRt\/c0lSsXDKTwo2N\/5P0ZqSWvtNvjVC+M836FN5yAngjM4pdeeNZCAlAW\/O5gtk5cTt+9+hQ5YxPhKtwFJkzeed7Ep6iKv2uQNfbUSutXOJInaF8XlsGjXJGY+GSLrChlaEuVduA9pXBADoV\/QDn8URYaky6Ujm5KLPp0ejBN0Rnb1b8hwf9cdF+vlfZOVii8aSBLcW18Ev4LAqkFD2PczpyEELTV9htqGEBINH71mkDDkaKE2i9C+UZaNVjGlQFQD4\/rTGRK11tiBzpIPxpS9q02TNSg9QrnVNe7+4y2xNoGU7CUM6tR9qn6uAaeMwz31VbZrl4NEEvVRSmRHECSW55yztE9dsASuw0sC4R19XyLhJO7czPT0HpZstrag6wd2gp8UhhcTpNbckPoYaKfU+WCEKhUBufiYq7DJk6mvfTQwJgo37nUG61eYdv5y4sx\/JrXa3nw\/B6glhBl0USTCpjqQiEwhAc23NNcj5P9TUAhQ4AeSm6oNLmb9ightcL6AuBW3vxMpvAO7I\/8zxrT9oq0cJ0+ggqSDDBHEUO3D0uqAqzRw+tc77GbpUalOdPL60FfpL0cecz3kJzwyF6tZox5bvP\/4\/NSR2n2FgVlBMa3wxAbwfOraon2uMrrjjFPIcV\/cOKMpzoz0S34n8OzNsVJGN3XHg7kMg=","paymentMethodType":"scheme","url":"https:\/\/checkoutshopper-test.adyen.com\/checkoutshopper\/threeDS2.shtml","data":{"MD":"M2RzMi5hYjZmZDU3Mzk3OTNlZGYxMDNhZmI5NWQ1YTAxNTM1MWExMjkzYjY4ZDIzMGMxNDFmNDEzMDJkOTFiNmQxMDRi","PaReq":"BQABAgANTFI__FtWpBHN57UmF6kH67p-WnDKFxMo3Ugz6r6OBZ-LlpisOSXTpyemBOTHod5Sl5gwFCwJHQq28D_edcTuE8IQupLBPqmpyC4lcy_jygbVYy4PyA3JVhJDaS9mKE7YD-O4wfgJBJs5VRnn8LWPd62L7fscAgvEl8FkeGs7zv85PPFJNCuzzHoWj8rLr75hmCzJpDNK6b9iqvsHixnl-PkzOHiDz5g_fwgVKa2-d14qsVkWG9DsZ7-JGn1JFH1xKrn6CZpiIQk-GqABMQ9yhGFfY2txyu6-QExhv8ko4-QtOwBiVOsFJm8rerMwWGx6knCt56ibKATm1Qe-zeuLnlnAaNV0v-GjhmfE6dGkL44YzqmExsrLQGmEQLTXxlwQBcJSYoOwz-bhlFR4dRZrXeSfziSzUEJR76cBrVAXOEYNCdQhIhsQ4eNucOwiI-WExWSdU5wvecXYIw5d97eN0OZvTBEHC7Fm0Kq9eYAh9ndyIbD4gNiTOBQb5Ggj4czegJ3bb0OxdhhhiKG1Urrl7471A9l8nCcqcEjp-tOMddPT0-TT7vroJSjY0tfK5YeiBYXNPNgDx1G0QtzcB9gyyMZGXFLthG6w3S0_g_6nKSfxnhjNX2BlTnH01DDP382F90rlUDlIKywAT6al8wCLM5PwRSneSsdmUSeT8_lCtBCDHoRswpR_JbG8HP_aB-huAEp7ImtleSI6IkFGMEFBQTEwM0NBNTM3RUFFRDg3QzI0REQ1MzkwOUI4MEE3OEE5MjNFMzgyM0Q2OERBQ0M5NEI5RkY4MzA1REMifUU65Q3hGwTuJiFPYk55rmAVAiDtPuowlNrJSSp39N7cRy8SsgJS32IQy1c35uSH8f79ybjQjkVDFaqk1CtrlJmW6HgjRouPfhwUljAUp9NXlwAVu33FicxxOJQQa08pO9Oorh_R4tenyA5W1-juZp84_SpvtVuvgGasABnqcNa6d1CDPTGbg64vrBc6WKTVMYlj_XowsjAPWJ6wl8OCzOaRe8Bu2aH246Dtx_lrkRLD9vFuF1ppS2340J4RNqDohFwCvzbVlxjMiznEHxVKlm9j6zMxJtO5EgBouBqInMCK5sjM1zNAA_WW3tHpXLjQ_o-HbdFuP5FLJJ9GiyT2ycTy1vOpPM7UKDKS4CLk42XqY-1luMBUX1ftKfIK9LcVR7hkdiulqS1BXDJ6Qmn9efvS0dU-p_tUNHNEULncn-lOg0ouMi4FAAEBAG4LVvu3IrIvZ48mUuT_lJCxiPk6aEtUQz_bIeVpSCW4AhKSVGIRZ5X6ImRSsSo8UskwNbTXegC3VW8vR4NAgsn8cjaflP3pOTVjwc83T7Vv5lXTmqz7_gbHeyf6Z5THf4KPIzB1_jUje4PkT8-Kr4Rl2O-GlaAg1wB5KX9VEqdjR6PZvYoBwNCd4tFwiVXQqTE3odjW3CfOiMG5yAzEpbXIxibu4sd5VizQ0Xn44Bk5J9s75Zy54ZIZ5lg2GM6ay9WOlPucQ4aVdRcBKboSnlIyi3U-oluZUSS-Vg8jdQBxdGC3IZiIVPOujgoJG86wbQ_zCaiHT2Tw9LCIc9w94TAQCDAFi0ktiyeu9bi-qxHW8AAA6mtmiVKGELn5pufZy1R7vIMtrACJ5bKkmT971ilKK4xTnzG3AMIuqzupsQwm0cMRcRjfPJdN3gvjgVXiz9DIJutqDYiDcOFqt7XBq_NY558aZbKTO7Gi2ejt4vBMrAY7krDLM-4dYucx0cIui__zmO037HCCjw49skYsZhuS6R7ZSRSuMibCbvaU7Tn6I9PtKXxM4Bxsib01mUxR7D4_nb41Yu4rCX6WXg_HlLfcMGPR36OdtQJjUcr8nX2w70OzibRsJucIj8a3VZZ2ljjYzcXNkIIqO6pkUkXX2inIYYyGrtDZEmYDRHHfsU_enIwttyZ7548pL5Hdvjio2y-pTszMYMjW1e5_yhrqfpr6Lj5vN3QfQi9JfBrYhbXt5ZFbB2HagRycGZIrW9eZUskeufum4APaP4GjCfHsHTb9PUhBuSEgfmawzXJH_GIAWvQmTwJurGzLTOwHT3URZVI9cBGuw_9GIYJE41T0GUnGwZhuwJcqzTjPx5xR3R8IQyQ1A8yd3TEoADB39N1ueXnpfmMd2-3S68_LBVYf51zOWYuu8Yo56YHC3ZZnsHjJEtrhtJznXJ2DGQ283Y6mK-cYWNrFWwUWEXSihDn49xAVeGUGTerySbCKZYtYYUWKzEOtbifRB15VcUHKb-2-daR6872v-ayf3dskZaKKFHSWfsv1rrzCMGaJU3gA2oW_jOtKkYaQHWw0sS98lfDUIn_RAd51GSlGXTkirH-LWD6fkBFQFh5v4dBoL1bxjBHaFMrW6NejxblsTvfP1goPubieSZ_woUiXwdaRAulKbZR1b2Zql-xhn_l7luIO2rU2nMKemLdBXP7l0EUemkr6ICYOzwHj8KKAfwvckB7LHGvN8HjG743lFoL5SkiBdKxH8k2rwowYfQ4PeG_f2XFsYu7maNHAYV30BLOrFaH49znPiJed1ZP9v6eU1it7R8DN9pJdybVRgjUzqEXUUh_diLcH5yK2691KJ6HC0TLwKpAEapptO49CiA6NQixIFIVG2n3PVsUu33n5lBiPPxX7ne7Qeep3u3LfGmA9hcjXsnycugr2mgHfx_FD-XQvvaON9Lq2HTTd9KGSVmPR4HTyhvRDpRzfemZrlGpdiJeJyKLLUP5UAjeuo6GSUS0fP49O8GbuHjrGBXSdcteBCSwJH7hX5Vxe1gJIHF7BtCm_tdUck_P0OvAN2Y-NyYO-GUp4M0zaE10tOG58fGZnEur2-ebdC3IUmPrjsj7Epr2-eDCTXiiW3k8j8r0y13HCo-NAcSApqv-IBveB7tnlY7isPa7BJip32NT9hoDl_M3BwnYQHs6NlJgR0sN8mBzHnA1wVRay52K1QJTAyS6SxW43lKJ-ltzcXzRs6fu6KRHflcPR_I33Td7O_8mHTvNFvlSRl2JUsugDDzS-9MTLPbKAgx07jR_Nw1gIwcEu1B6xvUWAK1pIrwwdZniMp3S1kwdt6H7ygEswBqUlGdqAadWgPsoCPXUEWJ7LpQJxY8oF2WJkh5QfOiOnrpPzIX5H2xaJdoYjSORUUWziHF8pv0inq2Xp0VOKVRaC7JXaOqzwlQ6D66fotAbOrw8J0UbtGsbpl3pq7OuFIFtvApJKbfWKn07ikpOoB_iqZwUDKk1-vJJZJ3Nb6LaC1egkXuXrfMGND6QllwCl46emPCzm9SuLSZ7P3oaOP077DHhtIfs4u0vjpuelYJMS2t1sIUfRFdL88GnDTRz3hacE","TermUrl":"http:\/\/mirumee.com\/plugins\/mirumee.payments.adyen\/additional-actions?payment=UGF5bWVudDoxMDM%3D&checkout=08546530-4718-422c-a912-9a1642a9031c"},"method":"POST","type":"redirect"},"details":[{"key":"MD","type":"text"},{"key":"PaRes","type":"text"}],"paymentData":"Ab02b4c0!BQABAgA1Xk1nQmoiOJCEtVVdsDKBm0L9nW8T6NbdlRla9BsZHojoiRTZFldU5FqmUGzPBTOjJzl6nSpVvpModrodHiIRJPN9w\/AciIHNBDXb\/Ws7gdsJjSAZHgCXZq2AUx1wGpXUg47BhDus2MHITLLNEnli63Z7Ec5dpG28JCJISwi1prh8bev+riPQrdzShFvke78wPQDvm2v6PnS0bNE71b826I4audbxweA\/yC02nSsKR3qGKGbjigbl3Z6xLdaphuYrqhYvXCNd3bzypQ8E40vq7uJN7cV9G8mzsERen1B4rlLBxoft5P4fYMpDcd6CJueKn1IHpPW7wOITsStNnhKM7WAa+uM9gAtPbUoTE1TQEV7oGi0o3ARjZv2E2Sdy3TIfqFTr39HPyoUSRmo+Ge6nX0wp4PIg19+KnmsCBdvYYB0mzzjSAwiWpcxGO0fJ9nH2zpS4mA2vsXbsA9z7vto0bcpuDC8eCMUSC\/TdDPzA2+u7JAZgqZp6eTVzX6eh6pC1MW5+nVTLCKdU97xX6xwaxbzVGOeXQpUbPpaztDzVUJFxxxuI15vhPskmiuXzaXD3DQNNjRUpwAbX58TfeeZd9gRWJ\/IhMZWNXAswpIIqXO2HS+PIKFGpznQDJbFcifQA6m9auwGqnbBrvC+QWcIDaSbG+JQ16KQNeZnF5qp0FxCs8hOM5c7NXU3D9TMLM5WdAEp7ImtleSI6IkFGMEFBQTEwM0NBNTM3RUFFRDg3QzI0REQ1MzkwOUI4MEE3OEE5MjNFMzgyM0Q2OERBQ0M5NEI5RkY4MzA1REMifZBA6Vt\/IW\/eRndJuQrwM7CD54KrDi8ssSCeoec3F97rp++BzLX9QEHI4SLetMHYN9b2SDM5qdOjeIG1XldAfCgl2Swkh9U2VoXZCLfU6it5a9xoA8rrnJJhpj58\/khW+RMYOqVSsSbjnlnzctlUXi1Epmb8OxDS8XUCnZmqv57I3MXPVRUWM68ZKClAE0D5npPhc0H\/QJHeXj+l+o5v5quCCW09zu2V1EAQNsgoQ4217NJbeM98EcOuN8vphM50RyGSbBqtfIrSGJ1+tr2VIIsM9QTOC4KtraFKq34wXL1KoU+\/C3Z03jPbYA9BxVotI7pbra4UnpJ6XU3U7Ezj0XaLXVrwP4OdjzV2ISSLUdDoo\/NtChHIO0J3aQuhEtQvOs3a+GPgbzIAYxunjejsZeNZGkaZSaHIY2CxlK3vOYR4R7vAXqV+Y6qAOOSBPvxmspn5XabK7gpTzSStO6SBDX1+IeMKZGXp+vexP0+5R4sHOb5djDMmAdszc9Koh4\/BzgEBvbRCBobn7UjBhZsiYaqB\/Q7ZBDHvH2Dn7Nig4JPHprqpdc5oH4IfoJ2GXTe8NtQKeMQH37MxnN+FBzGqM4ixc8Tkra3QJ9jP9gXAqZXUhUWhoTN7DBAm\/+MEyCnHGCYorIAVv0ns9o9WZGoDuNzAbJc8jpwurktsRy8sUL+vig\/h5\/TcLNjtRcruSH8+wSNM3Z2YztAuEaBbS7JonasJRMMucYkgNiD51mBdR0aoWMXfvRZUdQmKqCMHRQSNDSbvWG+rjHWAgcTzAjT19oMWZemiqjqJ00mHbpRwr\/0zeHSpdBUQ\/hLYTr9+fdVgmxwA7Iee\/FVgRt\/c0lSsXDKTwo2N\/5P0ZqSWvtNvjVC+M836FN5yAngjM4pdeeNZCAlAW\/O5gtk5cTt+9+hQ5YxPhKtwFJkzeed7Ep6iKv2uQNfbUSutXOJInaF8XlsGjXJGY+GSLrChlaEuVduA9pXBADoV\/QDn8URYaky6Ujm5KLPp0ejBN0Rnb1b8hwf9cdF+vlfZOVii8aSBLcW18Ev4LAqkFD2PczpyEELTV9htqGEBINH71mkDDkaKE2i9C+UZaNVjGlQFQD4\/rTGRK11tiBzpIPxpS9q02TNSg9QrnVNe7+4y2xNoGU7CUM6tR9qn6uAaeMwz31VbZrl4NEEvVRSmRHECSW55yztE9dsASuw0sC4R19XyLhJO7czPT0HpZstrag6wd2gp8UhhcTpNbckPoYaKfU+WCEKhUBufiYq7DJk6mvfTQwJgo37nUG61eYdv5y4sx\/JrXa3nw\/B6glhBl0USTCpjqQiEwhAc23NNcj5P9TUAhQ4AeSm6oNLmb9ightcL6AuBW3vxMpvAO7I\/8zxrT9oq0cJ0+ggqSDDBHEUO3D0uqAqzRw+tc77GbpUalOdPL60FfpL0cecz3kJzwyF6tZox5bvP\/4\/NSR2n2FgVlBMa3wxAbwfOraon2uMrrjjFPIcV\/cOKMpzoz0S34n8OzNsVJGN3XHg7kMg=","redirect":{"data":{"PaReq":"BQABAgANTFI__FtWpBHN57UmF6kH67p-WnDKFxMo3Ugz6r6OBZ-LlpisOSXTpyemBOTHod5Sl5gwFCwJHQq28D_edcTuE8IQupLBPqmpyC4lcy_jygbVYy4PyA3JVhJDaS9mKE7YD-O4wfgJBJs5VRnn8LWPd62L7fscAgvEl8FkeGs7zv85PPFJNCuzzHoWj8rLr75hmCzJpDNK6b9iqvsHixnl-PkzOHiDz5g_fwgVKa2-d14qsVkWG9DsZ7-JGn1JFH1xKrn6CZpiIQk-GqABMQ9yhGFfY2txyu6-QExhv8ko4-QtOwBiVOsFJm8rerMwWGx6knCt56ibKATm1Qe-zeuLnlnAaNV0v-GjhmfE6dGkL44YzqmExsrLQGmEQLTXxlwQBcJSYoOwz-bhlFR4dRZrXeSfziSzUEJR76cBrVAXOEYNCdQhIhsQ4eNucOwiI-WExWSdU5wvecXYIw5d97eN0OZvTBEHC7Fm0Kq9eYAh9ndyIbD4gNiTOBQb5Ggj4czegJ3bb0OxdhhhiKG1Urrl7471A9l8nCcqcEjp-tOMddPT0-TT7vroJSjY0tfK5YeiBYXNPNgDx1G0QtzcB9gyyMZGXFLthG6w3S0_g_6nKSfxnhjNX2BlTnH01DDP382F90rlUDlIKywAT6al8wCLM5PwRSneSsdmUSeT8_lCtBCDHoRswpR_JbG8HP_aB-huAEp7ImtleSI6IkFGMEFBQTEwM0NBNTM3RUFFRDg3QzI0REQ1MzkwOUI4MEE3OEE5MjNFMzgyM0Q2OERBQ0M5NEI5RkY4MzA1REMifUU65Q3hGwTuJiFPYk55rmAVAiDtPuowlNrJSSp39N7cRy8SsgJS32IQy1c35uSH8f79ybjQjkVDFaqk1CtrlJmW6HgjRouPfhwUljAUp9NXlwAVu33FicxxOJQQa08pO9Oorh_R4tenyA5W1-juZp84_SpvtVuvgGasABnqcNa6d1CDPTGbg64vrBc6WKTVMYlj_XowsjAPWJ6wl8OCzOaRe8Bu2aH246Dtx_lrkRLD9vFuF1ppS2340J4RNqDohFwCvzbVlxjMiznEHxVKlm9j6zMxJtO5EgBouBqInMCK5sjM1zNAA_WW3tHpXLjQ_o-HbdFuP5FLJJ9GiyT2ycTy1vOpPM7UKDKS4CLk42XqY-1luMBUX1ftKfIK9LcVR7hkdiulqS1BXDJ6Qmn9efvS0dU-p_tUNHNEULncn-lOg0ouMi4FAAEBAG4LVvu3IrIvZ48mUuT_lJCxiPk6aEtUQz_bIeVpSCW4AhKSVGIRZ5X6ImRSsSo8UskwNbTXegC3VW8vR4NAgsn8cjaflP3pOTVjwc83T7Vv5lXTmqz7_gbHeyf6Z5THf4KPIzB1_jUje4PkT8-Kr4Rl2O-GlaAg1wB5KX9VEqdjR6PZvYoBwNCd4tFwiVXQqTE3odjW3CfOiMG5yAzEpbXIxibu4sd5VizQ0Xn44Bk5J9s75Zy54ZIZ5lg2GM6ay9WOlPucQ4aVdRcBKboSnlIyi3U-oluZUSS-Vg8jdQBxdGC3IZiIVPOujgoJG86wbQ_zCaiHT2Tw9LCIc9w94TAQCDAFi0ktiyeu9bi-qxHW8AAA6mtmiVKGELn5pufZy1R7vIMtrACJ5bKkmT971ilKK4xTnzG3AMIuqzupsQwm0cMRcRjfPJdN3gvjgVXiz9DIJutqDYiDcOFqt7XBq_NY558aZbKTO7Gi2ejt4vBMrAY7krDLM-4dYucx0cIui__zmO037HCCjw49skYsZhuS6R7ZSRSuMibCbvaU7Tn6I9PtKXxM4Bxsib01mUxR7D4_nb41Yu4rCX6WXg_HlLfcMGPR36OdtQJjUcr8nX2w70OzibRsJucIj8a3VZZ2ljjYzcXNkIIqO6pkUkXX2inIYYyGrtDZEmYDRHHfsU_enIwttyZ7548pL5Hdvjio2y-pTszMYMjW1e5_yhrqfpr6Lj5vN3QfQi9JfBrYhbXt5ZFbB2HagRycGZIrW9eZUskeufum4APaP4GjCfHsHTb9PUhBuSEgfmawzXJH_GIAWvQmTwJurGzLTOwHT3URZVI9cBGuw_9GIYJE41T0GUnGwZhuwJcqzTjPx5xR3R8IQyQ1A8yd3TEoADB39N1ueXnpfmMd2-3S68_LBVYf51zOWYuu8Yo56YHC3ZZnsHjJEtrhtJznXJ2DGQ283Y6mK-cYWNrFWwUWEXSihDn49xAVeGUGTerySbCKZYtYYUWKzEOtbifRB15VcUHKb-2-daR6872v-ayf3dskZaKKFHSWfsv1rrzCMGaJU3gA2oW_jOtKkYaQHWw0sS98lfDUIn_RAd51GSlGXTkirH-LWD6fkBFQFh5v4dBoL1bxjBHaFMrW6NejxblsTvfP1goPubieSZ_woUiXwdaRAulKbZR1b2Zql-xhn_l7luIO2rU2nMKemLdBXP7l0EUemkr6ICYOzwHj8KKAfwvckB7LHGvN8HjG743lFoL5SkiBdKxH8k2rwowYfQ4PeG_f2XFsYu7maNHAYV30BLOrFaH49znPiJed1ZP9v6eU1it7R8DN9pJdybVRgjUzqEXUUh_diLcH5yK2691KJ6HC0TLwKpAEapptO49CiA6NQixIFIVG2n3PVsUu33n5lBiPPxX7ne7Qeep3u3LfGmA9hcjXsnycugr2mgHfx_FD-XQvvaON9Lq2HTTd9KGSVmPR4HTyhvRDpRzfemZrlGpdiJeJyKLLUP5UAjeuo6GSUS0fP49O8GbuHjrGBXSdcteBCSwJH7hX5Vxe1gJIHF7BtCm_tdUck_P0OvAN2Y-NyYO-GUp4M0zaE10tOG58fGZnEur2-ebdC3IUmPrjsj7Epr2-eDCTXiiW3k8j8r0y13HCo-NAcSApqv-IBveB7tnlY7isPa7BJip32NT9hoDl_M3BwnYQHs6NlJgR0sN8mBzHnA1wVRay52K1QJTAyS6SxW43lKJ-ltzcXzRs6fu6KRHflcPR_I33Td7O_8mHTvNFvlSRl2JUsugDDzS-9MTLPbKAgx07jR_Nw1gIwcEu1B6xvUWAK1pIrwwdZniMp3S1kwdt6H7ygEswBqUlGdqAadWgPsoCPXUEWJ7LpQJxY8oF2WJkh5QfOiOnrpPzIX5H2xaJdoYjSORUUWziHF8pv0inq2Xp0VOKVRaC7JXaOqzwlQ6D66fotAbOrw8J0UbtGsbpl3pq7OuFIFtvApJKbfWKn07ikpOoB_iqZwUDKk1-vJJZJ3Nb6LaC1egkXuXrfMGND6QllwCl46emPCzm9SuLSZ7P3oaOP077DHhtIfs4u0vjpuelYJMS2t1sIUfRFdL88GnDTRz3hacE","TermUrl":"http:\/\/mirumee.com\/plugins\/mirumee.payments.adyen\/additional-actions?payment=UGF5bWVudDoxMDM%3D&checkout=08546530-4718-422c-a912-9a1642a9031c","MD":"M2RzMi5hYjZmZDU3Mzk3OTNlZGYxMDNhZmI5NWQ1YTAxNTM1MWExMjkzYjY4ZDIzMGMxNDFmNDEzMDJkOTFiNmQxMDRi"},"method":"POST","url":"https:\/\/checkoutshopper-test.adyen.com\/checkoutshopper\/threeDS2.shtml"}}'
- headers:
- Connection:
- - Keep-Alive
- Content-Type:
- - application/json;charset=UTF-8
- Date:
- - Fri, 02 Apr 2021 11:07:28 GMT
- Keep-Alive:
- - timeout=15, max=100
- Server:
- - Apache
- Set-Cookie:
- - JSESSIONID=B651B944557BEBC4BDCE3440479CA286.test103e; Path=/checkout; Secure;
- HttpOnly
- Transfer-Encoding:
- - chunked
- pspReference:
- - 881617361648457F
- status:
- code: 200
- message: '200'
-version: 1
diff --git a/saleor/payment/gateways/adyen/tests/cassettes/test_plugin/test_process_payment_with_adyen_auto_capture.yaml b/saleor/payment/gateways/adyen/tests/cassettes/test_plugin/test_process_payment_with_adyen_auto_capture.yaml
deleted file mode 100644
index 00c1b0b5b0..0000000000
--- a/saleor/payment/gateways/adyen/tests/cassettes/test_plugin/test_process_payment_with_adyen_auto_capture.yaml
+++ /dev/null
@@ -1,50 +0,0 @@
-interactions:
-- request:
- body: '{"amount": {"value": "8000", "currency": "USD"}, "reference": "UGF5bWVudDoxMTUw",
- "paymentMethod": {"type": "scheme", "encryptedCardNumber": "test_4646464646464644",
- "encryptedExpiryMonth": "test_03", "encryptedExpiryYear": "test_2030", "encryptedSecurityCode":
- "test_737"}, "returnUrl": "https://example.com/plugins/mirumee.payments.adyen/additional-actions?payment=UGF5bWVudDoxMTUw&checkout=d72ba46f-95ce-4971-b548-2f65c51309b6",
- "merchantAccount": "SaleorECOM", "channel": "web", "shopperEmail": "", "applicationInfo":
- {"adyenLibrary": {"name": "adyen-python-api-library", "version": "4.0.0"}}}'
- headers:
- Accept:
- - '*/*'
- Accept-Encoding:
- - gzip, deflate
- Connection:
- - keep-alive
- Content-Length:
- - '596'
- Content-Type:
- - application/json
- User-Agent:
- - adyen-python-api-library/4.0.0
- x-api-key:
- - test_key
- method: POST
- uri: https://checkout-test.adyen.com/v64/payments
- response:
- body:
- string: '{"additionalData":{"paymentMethod":"visa"},"pspReference":"852610008487439C","resultCode":"Authorised","amount":{"currency":"USD","value":8000},"merchantReference":"UGF5bWVudDoxMTUw"}'
- headers:
- Connection:
- - Keep-Alive
- Content-Type:
- - application/json;charset=UTF-8
- Date:
- - Thu, 07 Jan 2021 08:34:47 GMT
- Keep-Alive:
- - timeout=15, max=100
- Server:
- - Apache
- Set-Cookie:
- - JSESSIONID=C26ACD22ECF45C1DD3B450E96D302D4F.test103e; Path=/checkout; Secure;
- HttpOnly
- Transfer-Encoding:
- - chunked
- pspReference:
- - 881610008487259D
- status:
- code: 200
- message: OK
-version: 1
diff --git a/saleor/payment/gateways/adyen/tests/cassettes/test_plugin/test_process_payment_with_auto_capture.yaml b/saleor/payment/gateways/adyen/tests/cassettes/test_plugin/test_process_payment_with_auto_capture.yaml
deleted file mode 100644
index 90530ed135..0000000000
--- a/saleor/payment/gateways/adyen/tests/cassettes/test_plugin/test_process_payment_with_auto_capture.yaml
+++ /dev/null
@@ -1,97 +0,0 @@
-interactions:
-- request:
- body: '{"amount": {"value": "8000", "currency": "USD"}, "reference": "UGF5bWVudDoxMzY1",
- "paymentMethod": {"type": "scheme", "encryptedCardNumber": "test_4646464646464644",
- "encryptedExpiryMonth": "test_03", "encryptedExpiryYear": "test_2030", "encryptedSecurityCode":
- "test_737"}, "returnUrl": "https://example.com/plugins/mirumee.payments.adyen/additional-actions?payment=UGF5bWVudDoxMzY1&checkout=4c3b18ff-b18a-43f3-a255-bc3f89607e95",
- "merchantAccount": "SaleorECOM", "channel": "web", "shopperEmail": "", "applicationInfo":
- {"adyenLibrary": {"name": "adyen-python-api-library", "version": "4.0.0"}}}'
- headers:
- Accept:
- - '*/*'
- Accept-Encoding:
- - gzip, deflate
- Connection:
- - keep-alive
- Content-Length:
- - '596'
- Content-Type:
- - application/json
- User-Agent:
- - adyen-python-api-library/4.0.0
- x-api-key:
- - test_key
- method: POST
- uri: https://checkout-test.adyen.com/v64/payments
- response:
- body:
- string: '{"additionalData":{"paymentMethod":"visa"},"pspReference":"853610014786939F","resultCode":"Authorised","amount":{"currency":"USD","value":8000},"merchantReference":"UGF5bWVudDoxMzY1"}'
- headers:
- Connection:
- - Keep-Alive
- Content-Type:
- - application/json;charset=UTF-8
- Date:
- - Thu, 07 Jan 2021 10:19:46 GMT
- Keep-Alive:
- - timeout=15, max=100
- Server:
- - Apache
- Set-Cookie:
- - JSESSIONID=B07375A76CF0E7D06A7A34DF1515466A.test104e; Path=/checkout; Secure;
- HttpOnly
- Transfer-Encoding:
- - chunked
- pspReference:
- - 881610014786858J
- status:
- code: 200
- message: '200'
-- request:
- body: '{"merchantAccount": "SaleorECOM", "modificationAmount": {"value": "8000",
- "currency": "USD"}, "originalReference": "853610014786939F", "reference": "UGF5bWVudDoxMzY1",
- "applicationInfo": {"adyenLibrary": {"name": "adyen-python-api-library", "version":
- "4.0.0"}}}'
- headers:
- Accept:
- - '*/*'
- Accept-Encoding:
- - gzip, deflate
- Connection:
- - keep-alive
- Content-Length:
- - '262'
- Content-Type:
- - application/json
- User-Agent:
- - adyen-python-api-library/4.0.0
- x-api-key:
- - test_key
- method: POST
- uri: https://pal-test.adyen.com/pal/servlet/Payment/v64/capture
- response:
- body:
- string: '{"pspReference":"853610014787942J","response":"[capture-received]"}'
- headers:
- Adyen-ServerState:
- - MEDIUM
- Connection:
- - Keep-Alive
- Content-Type:
- - application/json;charset=utf-8
- Date:
- - Thu, 07 Jan 2021 10:19:47 GMT
- Keep-Alive:
- - timeout=15, max=100
- Server:
- - Apache
- Set-Cookie:
- - JSESSIONID=F1D910A5A3FFBDEF31D3B9BBFC4D7554.test4e; Path=/pal; Secure; HttpOnly
- Transfer-Encoding:
- - chunked
- pspReference:
- - 853610014787942J
- status:
- code: 200
- message: '200'
-version: 1
diff --git a/saleor/payment/gateways/adyen/tests/cassettes/test_plugin/test_process_payment_with_klarna.yaml b/saleor/payment/gateways/adyen/tests/cassettes/test_plugin/test_process_payment_with_klarna.yaml
deleted file mode 100644
index 6cf2ea05fe..0000000000
--- a/saleor/payment/gateways/adyen/tests/cassettes/test_plugin/test_process_payment_with_klarna.yaml
+++ /dev/null
@@ -1,63 +0,0 @@
-interactions:
-- request:
- body: '{"amount": {"value": "8000", "currency": "USD"}, "reference": "UGF5bWVudDo1NzU=",
- "paymentMethod": {"type": "klarna_account"}, "returnUrl": "https://example.com/plugins/mirumee.payments.adyen/additional-actions?payment=UGF5bWVudDo1NzU%3D&checkout=7eaddd6c-e06f-4deb-bc3e-02162cb3ac10",
- "merchantAccount": "SaleorECOM", "browserInfo": {"acceptHeader": "*/*", "colorDepth":
- 24, "language": "en-US", "javaEnabled": false, "screenHeight": 1080, "screenWidth":
- 1920, "userAgent": ["Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML,
- like Gecko)", "Chrome/89.0.4389.90 Safari/537.36"], "timeZoneOffset": -120},
- "channel": "web", "shopperEmail": "", "shopperLocale": "en_US", "shopperReference":
- "", "countryCode": "US", "lineItems": [{"quantity": 2, "amountExcludingTax":
- "1000", "taxPercentage": 0, "description": "Test product, ", "id": "123", "taxAmount":
- "0", "amountIncludingTax": "1000"}, {"quantity": 1, "amountExcludingTax": "1000",
- "taxPercentage": 0, "description": "Test product 1, ", "id": "d04373e383314c1b84e131da9758676e",
- "taxAmount": "0", "amountIncludingTax": "1000"}, {"quantity": 1, "amountExcludingTax":
- "2000", "taxPercentage": 0, "description": "Test product 2, ", "id": "70e61111f589431c914905a079bd07e8",
- "taxAmount": "0", "amountIncludingTax": "2000"}, {"quantity": 1, "amountExcludingTax":
- "3000", "taxPercentage": 0, "description": "Test product 3, ", "id": "f05ce7f70c9441feb75aa05c4f0ab82c",
- "taxAmount": "0", "amountIncludingTax": "3000"}, {"quantity": 1, "amountExcludingTax":
- "1000", "taxPercentage": 0, "description": "Shipping - DHL", "id": "Shipping:3137",
- "taxAmount": "0", "amountIncludingTax": "1000"}], "applicationInfo": {"adyenLibrary":
- {"name": "adyen-python-api-library", "version": "4.0.0"}}}'
- headers:
- Accept:
- - '*/*'
- Accept-Encoding:
- - gzip, deflate
- Connection:
- - keep-alive
- Content-Length:
- - '1738'
- Content-Type:
- - application/json
- User-Agent:
- - adyen-python-api-library/4.0.0
- x-api-key:
- - test_key
- method: POST
- uri: https://checkout-test.adyen.com/v64/payments
- response:
- body:
- string: '{"resultCode":"RedirectShopper","action":{"paymentData":"Ab02b4c0!BQABAgAA76AO+anrthj\/B9KKYMWsHCZsmr1Jdvwxx9XFf3VdZfejwNjgAD9v19LJTHPpe4ANzhYoWzPKy3KvHexH7BLQLHaJ8Q4xSQ0l4DsrecLnJGUqJScsxbIErcB05tCNvXINtVd88EP9U6Eyq7oFLN1S8VXXaEuc5F2jcCuLm7VDYf+ZCAJXuutAcQT6h15iLRyr84ey2PtgKRDBQJu3MOzAOrYhvBEZHNxh+WXA0chmEDmz\/V\/+AVvbgWOmv9LEmfcjsM09cePNEltaA+F7qIPnHXO4Zz3LDKn\/mhOYyYbLsJM5CuPt\/lfARt8uvCoW9JsSf5RU1nRjV9ZiQmOVcY5aFLTvogya6Al\/vpetBXJsmXanJfRZCqAWYR6QMUlqNjUqlHGY6Jssa340xdfAQ2bcsSd16HhRqan3tUigqvmqbX8P9O6HmZXOL81EXJcVt4ZwkQ90Vp8OU5DTvfgK6vTIQZhf7FHqPzskWrS40e5ZvRLkvdwJFYVVct5OoAgcHuuy2bb0VH\/oa5xbXY4xDnZr1n\/ijFCX7xEI3aemcVjhFj\/hUCS2EjDwzGiosUgxGTe321D8HnGFmV2rflBUhqOU\/IDKcb5ubdMPt67UBmnm2bzfT9dj+QW5KGju2sgY+D0Ri+ztlxv3KPU9xrSOlkxlw+HEOD073dMr7I+\/9AMXzRDaNOhrFiOqNiMFnK1jEOsLAEp7ImtleSI6IkFGMEFBQTEwM0NBNTM3RUFFRDg3QzI0REQ1MzkwOUI4MEE3OEE5MjNFMzgyM0Q2OERBQ0M5NEI5RkY4MzA1REMifTe\/b8fJiynX+INPiS4wJMmgjt5P7uYKE1DwL\/Mz6dDAvFeumx1ixD\/ZUSLsaBJEt0DefJK0xbRJcfrglH3qubR9q09W8YLMKgtAjcaXotQr9RRqKKz0bje3VrvsFQsjDDN5aSGM8ZFHYYPlNOP2jTevD0zvF26SMntqkCQndnxGlQh53ILnmwDZc4g8Il1lRqJYm+75T+eL3qIgvDDZCPTHNrbO5KCxwwUmG4xkYtA8qT7fdJiKP9fypo4oi5ORpaovYYpBlVgohRtruNvMgLA0sXoSsQHvI10i+MhIFbrnlSIELUeUaJSMqXKqcIsNKvMAkw5FNdO3eACmVnRgHbETQl5NQj2vh+WoUBD38lLsTvLqoJOT3qWV9s7eopFP5gTdbsnxCCKvifgFg7rS1hDmgHqdONbT+AB9Q8W7mmz9WBesE4eOXpt2nRVkq40lU7e5CcWY5NS+EO633m9pvHE3RUhRS5jznSMJDRM6LGMfMBF7890IzVnhVpNQ7Z9Ogxcqi3K9BEC+OT4oo0Vb8LXwX2mj1xgkFhTsHGGUDCnaZnXYSELlVCq6gBYoIWLrg0l5pJDT4PzHFupnOW5FJSNVHQyzkOY2BpKNuIIobYS9mAFyEwzfP0G3sciup7uBxzIwR9sZvNmraaW2Iu0PcaUQLHGFL9YMosJC2sFKauhwUTLBS08NbhwgEfU5S403qe0bQxrUGGlVl92rqyLwm2DBF+QbZHeyGWfbldnEOsk0CrzGhEE\/KN8CWyL94\/BNFYwKnpFss7UqQUsvT\/Fp9xZumQUxaMkeGs0pXEoKYHWc0r4Y08Su7Do+AA3s\/xchuccmo0wIYv3Gqpl6td2tECFV2\/MPqntEbtcMPzA3tjTHsIJzSwKehshZD3ZrqHKC+8\/8ZeU\/Y9fyIpipHorOW21O3xJdCC3Mn1M23hnB34gTVBLsWGvtbthNGxtDCdA7+\/kFWuRhq\/VA9J2RQnTRv97x5olHUfkTNBEAz+dz9JtSMCI0YPPSp6PQodRyZUREVzjKJ\/kzqSdvVLaXkF1O1fO+u+j6gQ0IiNADC\/4VQddFmv98kjgiSZALNI\/NF+TUt2BFYsDZ4C5KQMYZJTFZqJCHzgYV+RSmoTm0+7hDSeWmhs+M62De5Td\/tytWTqwNP1RcW\/HZWldR24qV8iCtxTOzdam3bXYCTxq2aZcgoH+wtz5ixPhVxPfRS3gECzicFAoNoEjajlqDf1WQkE778KQF4UYyIDv+xSb+AOPBy7+VVG3DAlmUOo53BSe+gDw4IQmnVZPV2RNY\/3OlAxYhUDwaaD+KIPfmezv1ryzehukIaUoJT9zc01vvQHnyjUfx\/Utt+bFFn3c1++ALJ7kL9c6ofoyqHRSpTBb1ceGjM5X0\/gvNj0Tz5t+96htq6LFPnEDSRdpClbnrhzhJdN47eOEVnoGEqwQM0JH+2oPTNcc92nRRRJh+ZUivehTdqZSRiqtQM6hl1u6900Hr6RQ4DDXHmZ3XKK77viHe+\/z3tWSpqHGcPFtIktt+hO2B3Nn9mMR5CcmH6MaNflFqx08ysUZmeQZ5EL1\/kRuZyYxzuOmOL5jyHoYkFqZD\/UsshgEyNEqTXfZ9+Cn2cj+uVDMKqbXsuWtxO8hdS9D25fveDN+P18znUEdPu\/\/kX+f58ZI0ryAvJQmA1iOs7q8lOJlPOZn5CxR9YWb0XRvEnKgVx20TrEa6+t9w7b4o0bFbuRIC7C5hO+MO2DBse4rEghkhu8bDHt+Z\/GC49lSPlwQBlya7x\/MOI3EXCxgdTroWiF81XydQjeqO6RmgfrLNxJH+4x13cFQlKHB6ZfWDAarSsjKeXCUu\/LYGgECHshAWtx7O+Ols19uQAtG51Iu7IyJ0uvc3+KtH++akbq87DpXfBongb1q9SwreSEK7eS2+CUlTdZ5nkgsjktrG7bevQ83Al7YFidxZUa23fh7S2p6jlCJtC07u04N7K387wKCFHcO8\/WnyuzFHgn\/ljkrZFFYu0JOYqqY8D\/+RMmonheT7HklFdn3i\/mOnaBHP6ULcLqKyq1OkYM3x1LK9OGBSW7wvPxVbJGvl8ljL+MiOtIJOH8qBIdcQ7GeF+aORXqlEx9+OBy64SL9wbr8LZqh8+UjfzGocqeYsQVvipDxxFtlihKqQRdinZiH0FnogX2MTNvjItjJnETq4FQWWvN+CL4Ixr8dh1HYZM0CO8fkiqBWP\/sozp2Lf2Hs8CpFWUiTQRV1HnKc2qqQFDon4iK44sg3CYG+LF23ZmBINFOIbQhbEFjMQOCyzpd2WGVllbhDbFjIk\/81DakFAUejAOLm9HwOOpKs7c5QmmwgRa+BRfmkdNhO\/LUCstWhzoahl58idEibzL0\/EIRiKsLEnzkSWo6LfLkLW1xIloB1ruE3k375\/hf+a62n5v9+Azo9uV0efiGKRwHslDo2XippkBP2Ah+OsJVVZtNHd8OWEXKkLAfzbz+sLiRl6XG+w+BuWQZXnUGx6TNoxM1ujKIM4m2Ac17nK0f2udFF0H\/seKwqV4j04NfpuJD1kxUcGkObDLAYcenSOXryCdcYHnSRJ3f\/pSaA+5O4neIs7i8zWP17iXYz\/DxyXJBL4\/sfpoLxTH9ok","paymentMethodType":"klarna_account","url":"https:\/\/checkoutshopper-test.adyen.com\/checkoutshopper\/checkoutPaymentRedirect?redirectData=X6XtfGC3%21eyJHbHVlcGFnZURhdGEiOnsiYnJhbmRDb2RlIjoia2xhcm5hX2FjY291bnQiLCJtZXJjaGFudEFjY291bnQiOiJTYWxlb3JFQ09NIiwicmVkaXJlY3RVcmwiOiJodHRwczpcL1wvcGF5LnBsYXlncm91bmQua2xhcm5hLmNvbVwvbmFcLzhjeXRWOWsiLCJyZXR1cm5VcmwiOiJodHRwOlwvXC9taXJ1bWVlLmNvbVwvcGx1Z2luc1wvbWlydW1lZS5wYXltZW50cy5hZHllblwvYWRkaXRpb25hbC1hY3Rpb25zP3BheW1lbnQ9VUdGNWJXVnVkRG8xTnpVJTNEJmNoZWNrb3V0PTdlYWRkZDZjLWUwNmYtNGRlYi1iYzNlLTAyMTYyY2IzYWMxMCJ9fQ%3D%3DcG7JT5J23o%2FBUhXODtb1brDG%2FH7Ys%2Fl3nbssvr%2B4Ijs%3D","method":"GET","type":"redirect"},"details":[{"key":"redirectResult","type":"text"}],"paymentData":"Ab02b4c0!BQABAgAA76AO+anrthj\/B9KKYMWsHCZsmr1Jdvwxx9XFf3VdZfejwNjgAD9v19LJTHPpe4ANzhYoWzPKy3KvHexH7BLQLHaJ8Q4xSQ0l4DsrecLnJGUqJScsxbIErcB05tCNvXINtVd88EP9U6Eyq7oFLN1S8VXXaEuc5F2jcCuLm7VDYf+ZCAJXuutAcQT6h15iLRyr84ey2PtgKRDBQJu3MOzAOrYhvBEZHNxh+WXA0chmEDmz\/V\/+AVvbgWOmv9LEmfcjsM09cePNEltaA+F7qIPnHXO4Zz3LDKn\/mhOYyYbLsJM5CuPt\/lfARt8uvCoW9JsSf5RU1nRjV9ZiQmOVcY5aFLTvogya6Al\/vpetBXJsmXanJfRZCqAWYR6QMUlqNjUqlHGY6Jssa340xdfAQ2bcsSd16HhRqan3tUigqvmqbX8P9O6HmZXOL81EXJcVt4ZwkQ90Vp8OU5DTvfgK6vTIQZhf7FHqPzskWrS40e5ZvRLkvdwJFYVVct5OoAgcHuuy2bb0VH\/oa5xbXY4xDnZr1n\/ijFCX7xEI3aemcVjhFj\/hUCS2EjDwzGiosUgxGTe321D8HnGFmV2rflBUhqOU\/IDKcb5ubdMPt67UBmnm2bzfT9dj+QW5KGju2sgY+D0Ri+ztlxv3KPU9xrSOlkxlw+HEOD073dMr7I+\/9AMXzRDaNOhrFiOqNiMFnK1jEOsLAEp7ImtleSI6IkFGMEFBQTEwM0NBNTM3RUFFRDg3QzI0REQ1MzkwOUI4MEE3OEE5MjNFMzgyM0Q2OERBQ0M5NEI5RkY4MzA1REMifTe\/b8fJiynX+INPiS4wJMmgjt5P7uYKE1DwL\/Mz6dDAvFeumx1ixD\/ZUSLsaBJEt0DefJK0xbRJcfrglH3qubR9q09W8YLMKgtAjcaXotQr9RRqKKz0bje3VrvsFQsjDDN5aSGM8ZFHYYPlNOP2jTevD0zvF26SMntqkCQndnxGlQh53ILnmwDZc4g8Il1lRqJYm+75T+eL3qIgvDDZCPTHNrbO5KCxwwUmG4xkYtA8qT7fdJiKP9fypo4oi5ORpaovYYpBlVgohRtruNvMgLA0sXoSsQHvI10i+MhIFbrnlSIELUeUaJSMqXKqcIsNKvMAkw5FNdO3eACmVnRgHbETQl5NQj2vh+WoUBD38lLsTvLqoJOT3qWV9s7eopFP5gTdbsnxCCKvifgFg7rS1hDmgHqdONbT+AB9Q8W7mmz9WBesE4eOXpt2nRVkq40lU7e5CcWY5NS+EO633m9pvHE3RUhRS5jznSMJDRM6LGMfMBF7890IzVnhVpNQ7Z9Ogxcqi3K9BEC+OT4oo0Vb8LXwX2mj1xgkFhTsHGGUDCnaZnXYSELlVCq6gBYoIWLrg0l5pJDT4PzHFupnOW5FJSNVHQyzkOY2BpKNuIIobYS9mAFyEwzfP0G3sciup7uBxzIwR9sZvNmraaW2Iu0PcaUQLHGFL9YMosJC2sFKauhwUTLBS08NbhwgEfU5S403qe0bQxrUGGlVl92rqyLwm2DBF+QbZHeyGWfbldnEOsk0CrzGhEE\/KN8CWyL94\/BNFYwKnpFss7UqQUsvT\/Fp9xZumQUxaMkeGs0pXEoKYHWc0r4Y08Su7Do+AA3s\/xchuccmo0wIYv3Gqpl6td2tECFV2\/MPqntEbtcMPzA3tjTHsIJzSwKehshZD3ZrqHKC+8\/8ZeU\/Y9fyIpipHorOW21O3xJdCC3Mn1M23hnB34gTVBLsWGvtbthNGxtDCdA7+\/kFWuRhq\/VA9J2RQnTRv97x5olHUfkTNBEAz+dz9JtSMCI0YPPSp6PQodRyZUREVzjKJ\/kzqSdvVLaXkF1O1fO+u+j6gQ0IiNADC\/4VQddFmv98kjgiSZALNI\/NF+TUt2BFYsDZ4C5KQMYZJTFZqJCHzgYV+RSmoTm0+7hDSeWmhs+M62De5Td\/tytWTqwNP1RcW\/HZWldR24qV8iCtxTOzdam3bXYCTxq2aZcgoH+wtz5ixPhVxPfRS3gECzicFAoNoEjajlqDf1WQkE778KQF4UYyIDv+xSb+AOPBy7+VVG3DAlmUOo53BSe+gDw4IQmnVZPV2RNY\/3OlAxYhUDwaaD+KIPfmezv1ryzehukIaUoJT9zc01vvQHnyjUfx\/Utt+bFFn3c1++ALJ7kL9c6ofoyqHRSpTBb1ceGjM5X0\/gvNj0Tz5t+96htq6LFPnEDSRdpClbnrhzhJdN47eOEVnoGEqwQM0JH+2oPTNcc92nRRRJh+ZUivehTdqZSRiqtQM6hl1u6900Hr6RQ4DDXHmZ3XKK77viHe+\/z3tWSpqHGcPFtIktt+hO2B3Nn9mMR5CcmH6MaNflFqx08ysUZmeQZ5EL1\/kRuZyYxzuOmOL5jyHoYkFqZD\/UsshgEyNEqTXfZ9+Cn2cj+uVDMKqbXsuWtxO8hdS9D25fveDN+P18znUEdPu\/\/kX+f58ZI0ryAvJQmA1iOs7q8lOJlPOZn5CxR9YWb0XRvEnKgVx20TrEa6+t9w7b4o0bFbuRIC7C5hO+MO2DBse4rEghkhu8bDHt+Z\/GC49lSPlwQBlya7x\/MOI3EXCxgdTroWiF81XydQjeqO6RmgfrLNxJH+4x13cFQlKHB6ZfWDAarSsjKeXCUu\/LYGgECHshAWtx7O+Ols19uQAtG51Iu7IyJ0uvc3+KtH++akbq87DpXfBongb1q9SwreSEK7eS2+CUlTdZ5nkgsjktrG7bevQ83Al7YFidxZUa23fh7S2p6jlCJtC07u04N7K387wKCFHcO8\/WnyuzFHgn\/ljkrZFFYu0JOYqqY8D\/+RMmonheT7HklFdn3i\/mOnaBHP6ULcLqKyq1OkYM3x1LK9OGBSW7wvPxVbJGvl8ljL+MiOtIJOH8qBIdcQ7GeF+aORXqlEx9+OBy64SL9wbr8LZqh8+UjfzGocqeYsQVvipDxxFtlihKqQRdinZiH0FnogX2MTNvjItjJnETq4FQWWvN+CL4Ixr8dh1HYZM0CO8fkiqBWP\/sozp2Lf2Hs8CpFWUiTQRV1HnKc2qqQFDon4iK44sg3CYG+LF23ZmBINFOIbQhbEFjMQOCyzpd2WGVllbhDbFjIk\/81DakFAUejAOLm9HwOOpKs7c5QmmwgRa+BRfmkdNhO\/LUCstWhzoahl58idEibzL0\/EIRiKsLEnzkSWo6LfLkLW1xIloB1ruE3k375\/hf+a62n5v9+Azo9uV0efiGKRwHslDo2XippkBP2Ah+OsJVVZtNHd8OWEXKkLAfzbz+sLiRl6XG+w+BuWQZXnUGx6TNoxM1ujKIM4m2Ac17nK0f2udFF0H\/seKwqV4j04NfpuJD1kxUcGkObDLAYcenSOXryCdcYHnSRJ3f\/pSaA+5O4neIs7i8zWP17iXYz\/DxyXJBL4\/sfpoLxTH9ok","redirect":{"method":"GET","url":"https:\/\/checkoutshopper-test.adyen.com\/checkoutshopper\/checkoutPaymentRedirect?redirectData=X6XtfGC3%21eyJHbHVlcGFnZURhdGEiOnsiYnJhbmRDb2RlIjoia2xhcm5hX2FjY291bnQiLCJtZXJjaGFudEFjY291bnQiOiJTYWxlb3JFQ09NIiwicmVkaXJlY3RVcmwiOiJodHRwczpcL1wvcGF5LnBsYXlncm91bmQua2xhcm5hLmNvbVwvbmFcLzhjeXRWOWsiLCJyZXR1cm5VcmwiOiJodHRwOlwvXC9taXJ1bWVlLmNvbVwvcGx1Z2luc1wvbWlydW1lZS5wYXltZW50cy5hZHllblwvYWRkaXRpb25hbC1hY3Rpb25zP3BheW1lbnQ9VUdGNWJXVnVkRG8xTnpVJTNEJmNoZWNrb3V0PTdlYWRkZDZjLWUwNmYtNGRlYi1iYzNlLTAyMTYyY2IzYWMxMCJ9fQ%3D%3DcG7JT5J23o%2FBUhXODtb1brDG%2FH7Ys%2Fl3nbssvr%2B4Ijs%3D"}}'
- headers:
- Connection:
- - Keep-Alive
- Content-Type:
- - application/json;charset=UTF-8
- Date:
- - Mon, 12 Apr 2021 12:27:32 GMT
- Keep-Alive:
- - timeout=15, max=100
- Server:
- - Apache
- Set-Cookie:
- - JSESSIONID=8440B0ACF5E10F5E3413D31678BAE570.test103e; Path=/checkout; Secure;
- HttpOnly
- Transfer-Encoding:
- - chunked
- pspReference:
- - 881618230452065H
- status:
- code: 200
- message: '200'
-version: 1
diff --git a/saleor/payment/gateways/adyen/tests/cassettes/test_plugin/test_refund_payment.yaml b/saleor/payment/gateways/adyen/tests/cassettes/test_plugin/test_refund_payment.yaml
deleted file mode 100644
index 209c6daf5e..0000000000
--- a/saleor/payment/gateways/adyen/tests/cassettes/test_plugin/test_refund_payment.yaml
+++ /dev/null
@@ -1,49 +0,0 @@
-interactions:
-- request:
- body: '{"merchantAccount": "SaleorECOM", "modificationAmount": {"value": "8000",
- "currency": "USD"}, "originalReference": "882595494831959A", "reference": "UGF5bWVudDoxMTU4",
- "applicationInfo": {"adyenLibrary": {"name": "adyen-python-api-library", "version":
- "4.0.0"}}}'
- headers:
- Accept:
- - '*/*'
- Accept-Encoding:
- - gzip, deflate
- Connection:
- - keep-alive
- Content-Length:
- - '262'
- Content-Type:
- - application/json
- User-Agent:
- - adyen-python-api-library/4.0.0
- x-api-key:
- - test_key
- method: POST
- uri: https://pal-test.adyen.com/pal/servlet/Payment/v64/refund
- response:
- body:
- string: '{"pspReference":"882610009233471H","response":"[refund-received]"}'
- headers:
- Adyen-ServerState:
- - MEDIUM
- Connection:
- - Keep-Alive
- Content-Type:
- - application/json;charset=utf-8
- Date:
- - Thu, 07 Jan 2021 08:47:13 GMT
- Keep-Alive:
- - timeout=15, max=100
- Server:
- - Apache
- Set-Cookie:
- - JSESSIONID=34EEEA766BB7A07B0C79B65D3598AC98.test103e; Path=/pal; Secure; HttpOnly
- Transfer-Encoding:
- - chunked
- pspReference:
- - 882610009233471H
- status:
- code: 200
- message: OK
-version: 1
diff --git a/saleor/payment/gateways/adyen/tests/cassettes/test_plugin/test_void_payment.yaml b/saleor/payment/gateways/adyen/tests/cassettes/test_plugin/test_void_payment.yaml
deleted file mode 100644
index a292c02428..0000000000
--- a/saleor/payment/gateways/adyen/tests/cassettes/test_plugin/test_void_payment.yaml
+++ /dev/null
@@ -1,48 +0,0 @@
-interactions:
-- request:
- body: '{"merchantAccount": "SaleorECOM", "originalReference": "852610010025849H",
- "reference": "UGF5bWVudDoxMTY4", "applicationInfo": {"adyenLibrary": {"name":
- "adyen-python-api-library", "version": "4.0.0"}}}'
- headers:
- Accept:
- - '*/*'
- Accept-Encoding:
- - gzip, deflate
- Connection:
- - keep-alive
- Content-Length:
- - '202'
- Content-Type:
- - application/json
- User-Agent:
- - adyen-python-api-library/4.0.0
- x-api-key:
- - test_key
- method: POST
- uri: https://pal-test.adyen.com/pal/servlet/Payment/v64/cancel
- response:
- body:
- string: '{"pspReference":"852610010936232E","response":"[cancel-received]"}'
- headers:
- Adyen-ServerState:
- - HIGH
- Connection:
- - Keep-Alive
- Content-Type:
- - application/json;charset=utf-8
- Date:
- - Thu, 07 Jan 2021 09:15:36 GMT
- Keep-Alive:
- - timeout=15, max=100
- Server:
- - Apache
- Set-Cookie:
- - JSESSIONID=879F4733269764C93FF1C794B1143DB9.test3e; Path=/pal; Secure; HttpOnly
- Transfer-Encoding:
- - chunked
- pspReference:
- - 852610010936232E
- status:
- code: 200
- message: OK
-version: 1
diff --git a/saleor/payment/gateways/adyen/tests/conftest.py b/saleor/payment/gateways/adyen/tests/conftest.py
deleted file mode 100644
index 94b32b6277..0000000000
--- a/saleor/payment/gateways/adyen/tests/conftest.py
+++ /dev/null
@@ -1,257 +0,0 @@
-from decimal import Decimal
-from unittest import mock
-
-import Adyen
-import pytest
-from requests_hardened import HTTPSession
-
-from .....checkout import calculations
-from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-from .....plugins.manager import get_plugins_manager
-from .... import TransactionKind
-from ....models import Transaction
-from ....utils import create_payment
-from ..plugin import AdyenGatewayPlugin
-
-
[email protected](scope="module")
-def vcr_config():
- return {
- "filter_headers": [("x-api-key", "test_key")],
- }
-
-
-def adyen_plugin(settings, channel_USD):
- def fun(
- api_key=None,
- merchant_account=None,
- return_url=None,
- client_key=None,
- origin_url=None,
- adyen_auto_capture=None,
- auto_capture=None,
- apple_pay_cert=None,
- ):
- api_key = api_key or "test_key"
- merchant_account = merchant_account or "SaleorECOM"
- return_url = return_url or "http://127.0.0.1:3000/"
- client_key = client_key or "test_origin_key"
- origin_url = origin_url or "http://127.0.0.1:3000"
- adyen_auto_capture = adyen_auto_capture or False
- auto_capture = auto_capture or False
- settings.PLUGINS = ["saleor.payment.gateways.adyen.plugin.AdyenGatewayPlugin"]
- manager = get_plugins_manager(allow_replica=False)
-
- with mock.patch.object(HTTPSession, "request"):
- manager.save_plugin_configuration(
- AdyenGatewayPlugin.PLUGIN_ID,
- channel_USD.slug,
- {
- "active": True,
- "configuration": [
- {"name": "api-key", "value": api_key},
- {"name": "merchant-account", "value": merchant_account},
- {"name": "return-url", "value": return_url},
- {"name": "client-key", "value": client_key},
- {"name": "origin-url", "value": origin_url},
- {"name": "adyen-auto-capture", "value": adyen_auto_capture},
- {"name": "auto-capture", "value": auto_capture},
- {"name": "supported-currencies", "value": "USD"},
- {"name": "apple-pay-cert", "value": apple_pay_cert},
- ],
- },
- )
-
- manager = get_plugins_manager(allow_replica=False)
- manager.get_all_plugins()
- return manager.plugins_per_channel[channel_USD.slug][0]
-
- return fun
-
-
-def payment_adyen_for_checkout(checkout_with_items, address, checkout_delivery):
- checkout_with_items.billing_address = address
- checkout_with_items.shipping_address = address
- checkout_with_items.assigned_delivery = checkout_delivery(checkout_with_items)
- checkout_with_items.save()
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout_with_items)
- checkout_info = fetch_checkout_info(checkout_with_items, lines, manager)
- total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
- )
- payment = create_payment(
- gateway=AdyenGatewayPlugin.PLUGIN_ID,
- payment_token="",
- total=total.gross.amount,
- currency=checkout_with_items.currency,
- email=checkout_with_items.email,
- customer_ip_address="",
- checkout=checkout_with_items,
- return_url="https://www.example.com",
- )
- return payment
-
-
-def inactive_payment_adyen_for_checkout(payment_adyen_for_checkout):
- payment_adyen_for_checkout.is_active = False
- payment_adyen_for_checkout.save(update_fields=["is_active"])
- return payment_adyen_for_checkout
-
-
-def payment_adyen_for_order(order_with_lines):
- payment = create_payment(
- gateway=AdyenGatewayPlugin.PLUGIN_ID,
- payment_token="",
- total=Decimal("80.00"),
- currency=order_with_lines.currency,
- email=order_with_lines.user_email,
- customer_ip_address="",
- checkout=None,
- order=order_with_lines,
- return_url="https://www.example.com",
- )
-
- Transaction.objects.create(
- payment=payment,
- action_required=False,
- kind=TransactionKind.AUTH,
- token="token",
- is_success=True,
- amount=order_with_lines.total_gross_amount,
- currency=order_with_lines.currency,
- error="",
- gateway_response={},
- action_required_data={},
- )
- return payment
-
-
-def notification():
- def fun(
- event_code=None,
- success=None,
- psp_reference=None,
- merchant_reference=None,
- value=None,
- ):
- event_code = event_code or "AUTHORISATION"
- success = success or "true"
- psp_reference = psp_reference or "852595499936560C"
- merchant_reference = merchant_reference or "UGF5bWVudDoxNw=="
- value = value or 1130
-
- return {
- "additionalData": {},
- "eventCode": event_code,
- "success": success,
- "eventDate": "2019-06-28T18:03:50+01:00",
- "merchantAccountCode": "SaleorECOM",
- "pspReference": psp_reference,
- "merchantReference": merchant_reference,
- "amount": {"value": value, "currency": "USD"},
- }
-
- return fun
-
-
-def notification_with_hmac_signature():
- return {
- "additionalData": {
- "expiryDate": "12/2012",
- " NAME1 ": "VALUE1",
- "cardSummary": "7777",
- "totalFraudScore": "10",
- "hmacSignature": "D4bKVtjx5AlBL2eeQZIh1p7G1Lh6vWjzwkDlzC+PoMo=",
- "NAME2": " VALUE2 ",
- "fraudCheck-6-ShopperIpUsage": "10",
- },
- "amount": {"currency": "GBP", "value": 20150},
- "eventCode": "AUTHORISATION",
- "eventDate": "2020-07-24T12:40:22+02:00",
- "merchantAccountCode": "SaleorPOS",
- "merchantReference": "8313842560770001",
- "paymentMethod": "visa",
- "pspReference": "test_AUTHORISATION_4",
- "reason": "REFUSED",
- "success": "false",
- }
-
-
-def adyen_payment_method():
- return {
- "type": "scheme",
- "encryptedCardNumber": "test_4646464646464644",
- "encryptedExpiryMonth": "test_03",
- "encryptedExpiryYear": "test_2030",
- "encryptedSecurityCode": "test_737",
- }
-
-
-def adyen_additional_data_for_3ds():
- user_agent = (
- "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)",
- "Chrome/89.0.4389.90 Safari/537.36",
- )
- return {
- "paymentMethod": {
- "type": "scheme",
- "encryptedCardNumber": "test_4917610000000000",
- "encryptedExpiryMonth": "test_03",
- "encryptedExpiryYear": "test_2030",
- "encryptedSecurityCode": "test_737",
- "brand": "visa",
- },
- "browserInfo": {
- "acceptHeader": "*/*",
- "colorDepth": 24,
- "language": "en-US",
- "javaEnabled": False,
- "screenHeight": 1080,
- "screenWidth": 1920,
- "userAgent": user_agent,
- "timeZoneOffset": -120,
- },
- }
-
-
-def adyen_additional_data_for_klarna():
- user_agent = (
- "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)",
- "Chrome/89.0.4389.90 Safari/537.36",
- )
- return {
- "paymentMethod": {
- "type": "klarna_account",
- },
- "browserInfo": {
- "acceptHeader": "*/*",
- "colorDepth": 24,
- "language": "en-US",
- "javaEnabled": False,
- "screenHeight": 1080,
- "screenWidth": 1920,
- "userAgent": user_agent,
- "timeZoneOffset": -120,
- },
- }
-
-
-def adyen_check_balance_response():
- return Adyen.client.AdyenResult(
- message={
- "pspReference": "851634546949980A",
- "resultCode": "Success",
- "balance": {"currency": "GBP", "value": 10000},
- }
- )
diff --git a/saleor/payment/gateways/adyen/tests/test_adyen_version.py b/saleor/payment/gateways/adyen/tests/test_adyen_version.py
deleted file mode 100644
index 461163dbe2..0000000000
--- a/saleor/payment/gateways/adyen/tests/test_adyen_version.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from Adyen.settings import API_CHECKOUT_VERSION, API_PAYMENT_VERSION
-
-
-def test_adyen_api_version_not_changed():
- # We shouldn't bump the Adyen API version when we make a path release.
- # We could bump Adyen API when we make a major or minor release.
- # If we bump Adyen API we should provide it as breaking changes because
- # Saleor clients may require to update part of their code (e.g. in mobile devices).
- assert API_CHECKOUT_VERSION == "v64"
- assert API_PAYMENT_VERSION == "v64"
diff --git a/saleor/payment/gateways/adyen/tests/test_plugin.py b/saleor/payment/gateways/adyen/tests/test_plugin.py
deleted file mode 100644
index b7f316953d..0000000000
--- a/saleor/payment/gateways/adyen/tests/test_plugin.py
+++ /dev/null
@@ -1,718 +0,0 @@
-import json
-from decimal import Decimal
-from unittest import mock
-
-import Adyen
-import pytest
-from django.core.exceptions import ValidationError
-from requests.exceptions import ConnectTimeout, RequestException, SSLError
-from requests_hardened import HTTPSession
-
-from .....plugins.models import PluginConfiguration
-from .... import PaymentError, TransactionKind
-from ....interface import GatewayResponse, PaymentMethodInfo
-from ....models import Payment, Transaction
-from ....utils import create_payment_information, create_transaction
-
-
[email protected]("saleor.payment.gateways.adyen.plugin.api_call")
-def test_process_additional_action(
- mocked_api_call,
- dummy_payment_data,
- payment_dummy,
- checkout_ready_to_complete,
- adyen_plugin,
-):
- expected_message = {"resultCode": "authorised", "pspReference": "ref-id"}
- mocked_app_response = mock.MagicMock(message=expected_message)
-
- mocked_api_call.return_value = mocked_app_response
- plugin = adyen_plugin(auto_capture=False)
- dummy_payment_data.data = {
- "additional-data": "payment-data",
- }
-
- kind = TransactionKind.AUTH
- response = plugin._process_additional_action(dummy_payment_data, kind)
-
- assert response == GatewayResponse(
- is_success=True,
- action_required=False,
- action_required_data=None,
- kind=kind,
- amount=dummy_payment_data.amount,
- currency=dummy_payment_data.currency,
- transaction_id="ref-id",
- error=None,
- psp_reference="ref-id",
- payment_method_info=PaymentMethodInfo(),
- legacy_adyen_plugin_result_code=expected_message.get("resultCode"),
- legacy_adyen_plugin_payment_method="",
- )
- mocked_api_call.assert_called_with(
- dummy_payment_data.data, plugin.adyen.checkout.payments_details
- )
-
-
-def test_get_payment_gateway_for_checkout(
- adyen_plugin, checkout_with_single_item, checkout_info, address, checkout_lines_info
-):
- checkout_with_single_item.billing_address = address
- checkout_with_single_item.save()
- adyen_plugin = adyen_plugin()
- response = adyen_plugin.get_payment_gateways(
- currency=None,
- checkout_info=checkout_info,
- checkout_lines=checkout_lines_info,
- previous_value=None,
- )[0]
- assert response.id == adyen_plugin.PLUGIN_ID
- assert response.name == adyen_plugin.PLUGIN_NAME
- config = response.config
- assert len(config) == 2
- assert config[0] == {
- "field": "client_key",
- "value": adyen_plugin.config.connection_params["client_key"],
- }
- assert config[1]["field"] == "config"
- config = json.loads(config[1]["value"])
- assert isinstance(config, dict)
-
-
-def test_process_payment(
- payment_adyen_for_checkout, checkout_with_items, adyen_plugin, adyen_payment_method
-):
- payment_info = create_payment_information(
- payment_adyen_for_checkout,
- additional_data={"paymentMethod": adyen_payment_method},
- )
- adyen_plugin = adyen_plugin()
- response = adyen_plugin.process_payment(payment_info, None)
- assert response.is_success is True
- assert response.action_required is False
- assert response.kind == TransactionKind.AUTH
- assert response.amount == Decimal("80.00")
- assert response.currency == checkout_with_items.currency
- assert response.transaction_id == "882609854544793A" # ID returned by Adyen
- assert response.error is None
- assert response.action_required_data is None
- assert response.payment_method_info == PaymentMethodInfo(brand="visa", type="card")
-
-
[email protected]("saleor.payment.gateways.adyen.plugin.call_capture")
-def test_process_payment_with_adyen_auto_capture(
- capture_mock,
- payment_adyen_for_checkout,
- checkout_with_items,
- adyen_plugin,
- adyen_payment_method,
-):
- payment_info = create_payment_information(
- payment_adyen_for_checkout,
- additional_data={"paymentMethod": adyen_payment_method},
- )
- adyen_plugin = adyen_plugin(adyen_auto_capture=True)
- response = adyen_plugin.process_payment(payment_info, None)
- # ensure call_capture is not called
- assert not capture_mock.called
- assert response.is_success is True
- assert response.action_required is False
- # kind should still be capture as Adyen had adyen_auto_capture set to True
- assert response.kind == TransactionKind.CAPTURE
- assert response.amount == Decimal("80.00")
- assert response.currency == checkout_with_items.currency
- assert response.transaction_id == "852610008487439C" # ID returned by Adyen
- assert response.error is None
-
-
-def test_process_payment_with_auto_capture(
- payment_adyen_for_checkout, checkout_with_items, adyen_plugin, adyen_payment_method
-):
- payment_info = create_payment_information(
- payment_adyen_for_checkout,
- additional_data={"paymentMethod": adyen_payment_method},
- )
- adyen_plugin = adyen_plugin(auto_capture=True)
- response = adyen_plugin.process_payment(payment_info, None)
- assert response.is_success is True
- assert response.action_required is False
- assert response.kind == TransactionKind.CAPTURE
- assert response.amount == Decimal("80.00")
- assert response.currency == checkout_with_items.currency
- assert response.transaction_id == "853610014787942J" # ID returned by Adyen
- assert response.error is None
- assert response.action_required_data is None
-
-
-def test_process_payment_with_3ds_redirect(
- payment_adyen_for_checkout,
- adyen_additional_data_for_3ds,
- checkout_with_items,
- adyen_plugin,
-):
- payment_adyen_for_checkout.extra_data = ""
- payment_adyen_for_checkout.save(update_fields=["extra_data"])
- payment_info = create_payment_information(
- payment_adyen_for_checkout, additional_data=adyen_additional_data_for_3ds
- )
- adyen_plugin = adyen_plugin(auto_capture=True)
- response = adyen_plugin.process_payment(payment_info, None)
- assert response.is_success is True
- assert response.action_required is True
- assert response.kind == TransactionKind.AUTH
- assert response.amount == Decimal("80.00")
- assert response.currency == checkout_with_items.currency
- assert response.error is None
-
- action_required_data = response.action_required_data
- assert action_required_data["type"] == "redirect"
- assert action_required_data["paymentMethodType"] == "scheme"
- assert action_required_data["paymentData"]
-
- payment_data = action_required_data["paymentData"]
- payment_adyen_for_checkout.refresh_from_db()
- assert payment_adyen_for_checkout.extra_data == json.dumps(
- [{"payment_data": payment_data, "parameters": ["MD", "PaRes"]}]
- )
-
-
-def test_process_payment_with_klarna(
- payment_adyen_for_checkout,
- adyen_additional_data_for_klarna,
- checkout_with_items,
- address_usa,
- adyen_plugin,
-):
- payment_adyen_for_checkout.extra_data = ""
- payment_adyen_for_checkout.save(update_fields=["extra_data"])
- checkout_with_items.billing_address = address_usa
- checkout_with_items.shipping_address = address_usa
- checkout_with_items.save(update_fields=["billing_address", "shipping_address"])
-
- line = checkout_with_items.lines.first()
- line.quantity = 2
- line.save(update_fields=["quantity"])
-
- payment_info = create_payment_information(
- payment_adyen_for_checkout, additional_data=adyen_additional_data_for_klarna
- )
- adyen_plugin = adyen_plugin(auto_capture=True)
- response = adyen_plugin.process_payment(payment_info, None)
- assert response.is_success is True
- assert response.action_required is True
- assert response.kind == TransactionKind.AUTH
- assert response.amount == Decimal("80.00")
- assert response.currency == checkout_with_items.currency
- assert response.error is None
-
- action_required_data = response.action_required_data
- assert action_required_data["type"] == "redirect"
- assert action_required_data["paymentMethodType"] == "klarna_account"
- assert action_required_data["paymentData"]
-
- payment_data = action_required_data["paymentData"]
- payment_adyen_for_checkout.refresh_from_db()
- assert payment_adyen_for_checkout.extra_data == json.dumps(
- [{"payment_data": payment_data, "parameters": ["redirectResult"]}]
- )
-
-
[email protected]("saleor.payment.gateways.adyen.plugin.api_call")
-def test_process_payment_additional_action(
- api_call_mock, payment_adyen_for_checkout, checkout_with_items, adyen_plugin
-):
- payment_adyen_for_checkout.extra_data = ""
- payment_adyen_for_checkout.save(update_fields=["extra_data"])
- payment_data = "Ab02b4c0!B"
- action_data = {
- "method": "GET",
- "paymentData": payment_data,
- "paymentMethodType": "ideal",
- "type": "redirect",
- "url": "https://test.adyen.com/hpp/redirectIdeal.shtml?brandCode=ideal",
- }
- message = {
- "resultCode": "RedirectShopper",
- "action": action_data,
- "details": [{"key": "payload", "type": "text"}],
- "pspReference": "882595494831959A",
- }
- api_call_mock.return_value.message = message
-
- payment_info = create_payment_information(
- payment_adyen_for_checkout,
- additional_data={"paymentMethod": {"paymentdata": ""}},
- )
- adyen_plugin = adyen_plugin(auto_capture=True)
- response = adyen_plugin.process_payment(payment_info, None)
- assert response.is_success is True
- assert response.action_required is True
- assert response.kind == TransactionKind.AUTH
- assert response.amount == Decimal("80.00")
- assert response.currency == checkout_with_items.currency
- assert response.transaction_id == "882595494831959A"
- assert response.error is None
- assert response.action_required_data == action_data
-
- payment_adyen_for_checkout.refresh_from_db()
- assert payment_adyen_for_checkout.extra_data == json.dumps(
- [{"payment_data": payment_data, "parameters": ["payload"]}]
- )
-
-
[email protected]("saleor.payment.gateways.adyen.plugin.api_call")
-def test_process_payment_additional_action_payment_does_not_exists(
- api_call_mock, payment_adyen_for_checkout, checkout_with_items, adyen_plugin
-):
- action_data = {
- "method": "GET",
- "paymentData": "Ab02b4c0!B",
- "paymentMethodType": "ideal",
- "type": "redirect",
- "url": "https://test.adyen.com/hpp/redirectIdeal.shtml?brandCode=ideal",
- }
- message = {
- "resultCode": "RedirectShopper",
- "action": action_data,
- "details": [{"key": "payload", "type": "text"}],
- "pspReference": "882595494831959A",
- }
- api_call_mock.return_value.message = message
-
- payment_info = create_payment_information(
- payment_adyen_for_checkout,
- additional_data={"paymentMethod": {"paymentdata": ""}},
- )
-
- Payment.objects.all().delete()
-
- adyen_plugin = adyen_plugin(auto_capture=True)
-
- with pytest.raises(PaymentError) as e:
- adyen_plugin.process_payment(payment_info, None)
-
- assert str(e.value) == "Payment cannot be performed. Payment does not exists."
-
-
[email protected]("saleor.payment.gateways.adyen.plugin.api_call")
-def test_process_payment_additional_action_checkout_does_not_exists(
- api_call_mock, payment_adyen_for_checkout, checkout_with_items, adyen_plugin
-):
- action_data = {
- "method": "GET",
- "paymentData": "Ab02b4c0!B",
- "paymentMethodType": "ideal",
- "type": "redirect",
- "url": "https://test.adyen.com/hpp/redirectIdeal.shtml?brandCode=ideal",
- }
- message = {
- "resultCode": "RedirectShopper",
- "action": action_data,
- "details": [{"key": "payload", "type": "text"}],
- "pspReference": "882595494831959A",
- }
- api_call_mock.return_value.message = message
-
- payment_info = create_payment_information(
- payment_adyen_for_checkout,
- additional_data={"paymentMethod": {"paymentdata": ""}},
- )
-
- payment_adyen_for_checkout.checkout = None
- payment_adyen_for_checkout.save()
-
- adyen_plugin = adyen_plugin(auto_capture=True)
-
- with pytest.raises(PaymentError) as e:
- adyen_plugin.process_payment(payment_info, None)
-
- assert (
- str(e.value)
- == "Payment cannot be performed. Checkout for this payment does not exist."
- )
-
-
-def test_confirm_payment(payment_adyen_for_order, adyen_plugin):
- payment_info = create_payment_information(
- payment_adyen_for_order,
- )
- gateway_response = GatewayResponse(
- kind=TransactionKind.ACTION_TO_CONFIRM,
- action_required=False,
- transaction_id="882595494831959A",
- is_success=True,
- amount=payment_info.amount,
- currency=payment_info.currency,
- error="",
- )
-
- action_transaction = create_transaction(
- payment=payment_adyen_for_order,
- payment_information=payment_info,
- kind=TransactionKind.ACTION_TO_CONFIRM,
- gateway_response=gateway_response,
- )
- adyen_plugin = adyen_plugin()
- response = adyen_plugin.confirm_payment(payment_info, None)
-
- assert response is not None
- assert response.is_success is True
- assert response.kind == TransactionKind.AUTH
- assert response.amount == action_transaction.amount
- assert response.currency == action_transaction.currency
-
-
-def test_confirm_payment_pending_order(payment_adyen_for_checkout, adyen_plugin):
- payment_info = create_payment_information(
- payment_adyen_for_checkout,
- )
- gateway_response = GatewayResponse(
- kind=TransactionKind.ACTION_TO_CONFIRM,
- action_required=False,
- transaction_id="882595494831959A",
- is_success=True,
- amount=payment_info.amount,
- currency=payment_info.currency,
- error="",
- legacy_adyen_plugin_result_code="pending",
- )
- action_transaction = create_transaction(
- payment=payment_adyen_for_checkout,
- payment_information=payment_info,
- kind=TransactionKind.ACTION_TO_CONFIRM,
- gateway_response=gateway_response,
- )
- adyen_plugin = adyen_plugin()
- response = adyen_plugin.confirm_payment(payment_info, None)
-
- assert response is not None
- assert response.is_success is True
- assert response.kind == TransactionKind.PENDING
- assert response.amount == action_transaction.amount
- assert response.currency == action_transaction.currency
-
-
-def test_confirm_already_processed_payment(payment_adyen_for_order, adyen_plugin):
- payment_info = create_payment_information(
- payment_adyen_for_order,
- )
- gateway_response = GatewayResponse(
- kind=TransactionKind.ACTION_TO_CONFIRM,
- action_required=False,
- transaction_id="882595494831959A",
- is_success=True,
- amount=payment_info.amount,
- currency=payment_info.currency,
- error="",
- )
- create_transaction(
- payment=payment_adyen_for_order,
- payment_information=payment_info,
- kind=TransactionKind.ACTION_TO_CONFIRM,
- gateway_response=gateway_response,
- )
- gateway_response.kind = TransactionKind.AUTH
- action_transaction = create_transaction(
- payment=payment_adyen_for_order,
- payment_information=payment_info,
- kind=TransactionKind.AUTH,
- gateway_response=gateway_response,
- )
- adyen_plugin = adyen_plugin()
- response = adyen_plugin.confirm_payment(payment_info, None)
-
- assert response is not None
- assert response.transaction_already_processed is True
- assert response.is_success is True
- assert response.kind == TransactionKind.AUTH
- assert response.amount == action_transaction.amount
- assert response.currency == action_transaction.currency
- assert payment_adyen_for_order.transactions.count() == 3
-
-
-def test_confirm_payment_with_adyen_auto_capture(payment_adyen_for_order, adyen_plugin):
- payment_info = create_payment_information(
- payment_adyen_for_order,
- )
- gateway_response = GatewayResponse(
- kind=TransactionKind.ACTION_TO_CONFIRM,
- action_required=False,
- transaction_id="882595494831959A",
- is_success=True,
- amount=payment_info.amount,
- currency=payment_info.currency,
- error="",
- )
-
- auth_transaction = create_transaction(
- payment=payment_adyen_for_order,
- payment_information=payment_info,
- kind=TransactionKind.ACTION_TO_CONFIRM,
- gateway_response=gateway_response,
- )
- adyen_plugin = adyen_plugin(adyen_auto_capture=True)
- response = adyen_plugin.confirm_payment(payment_info, None)
-
- assert response is not None
- assert response.is_success is True
- assert response.kind == TransactionKind.CAPTURE
- assert response.amount == auth_transaction.amount
- assert response.currency == auth_transaction.currency
-
-
[email protected](reason="To finish when additional auth data schema will be known")
-def test_confirm_payment_with_additional_details(payment_adyen_for_order, adyen_plugin):
- return # test it when we will have additional auth data
- payment_info = create_payment_information(
- payment_adyen_for_order,
- )
- adyen_plugin = adyen_plugin()
- adyen_plugin.confirm_payment(payment_info, None)
-
-
-def test_confirm_payment_without_additional_data(payment_adyen_for_order, adyen_plugin):
- Transaction.objects.create(
- payment=payment_adyen_for_order,
- action_required=False,
- kind=TransactionKind.ACTION_TO_CONFIRM,
- token="token",
- is_success=False,
- amount="100",
- currency="EUR",
- error="",
- gateway_response={},
- action_required_data={},
- )
-
- payment_info = create_payment_information(payment_adyen_for_order)
- response = adyen_plugin().confirm_payment(payment_info, None)
-
- assert not response.is_success
- assert not response.action_required
- assert response.kind == TransactionKind.AUTH
- assert response.error is not None
- assert payment_info.graphql_payment_id in response.error
-
-
-def test_refund_payment(payment_adyen_for_order, order_with_lines, adyen_plugin):
- payment_info = create_payment_information(
- payment_adyen_for_order,
- # additional_data=...
- )
- gateway_response = GatewayResponse(
- kind=TransactionKind.AUTH,
- action_required=False,
- transaction_id="882595494831959A",
- is_success=True,
- amount=payment_info.amount,
- currency=payment_info.currency,
- error="",
- )
-
- create_transaction(
- payment=payment_adyen_for_order,
- payment_information=payment_info,
- kind=TransactionKind.AUTH,
- gateway_response=gateway_response,
- )
- response = adyen_plugin().refund_payment(payment_info, None)
- assert response.is_success is True
- assert response.action_required is False
- assert response.kind == TransactionKind.REFUND_ONGOING
- assert response.amount == Decimal("80.00")
- assert response.currency == order_with_lines.currency
- assert response.transaction_id == "882610009233471H" # ID returned by Adyen
-
-
-def test_void_payment(
- payment_adyen_for_order, order_with_lines, adyen_plugin, adyen_payment_method
-):
- payment_info = create_payment_information(
- payment_adyen_for_order,
- payment_token="852610010025849H",
- additional_data={"paymentMethod": adyen_payment_method},
- )
- gateway_response = GatewayResponse(
- kind=TransactionKind.AUTH,
- action_required=False,
- transaction_id="852610010025849H",
- is_success=True,
- amount=payment_info.amount,
- currency=payment_info.currency,
- error="",
- )
-
- create_transaction(
- payment=payment_adyen_for_order,
- payment_information=payment_info,
- kind=TransactionKind.AUTH,
- gateway_response=gateway_response,
- )
- response = adyen_plugin().void_payment(payment_info, None)
- assert response.is_success is True
- assert response.action_required is False
- assert response.kind == TransactionKind.VOID
- assert response.amount == Decimal("80.00")
- assert response.currency == order_with_lines.currency
- assert response.transaction_id == "852610010936232E" # ID returned by Adyen
-
-
-def test_capture_payment(
- payment_adyen_for_order, order_with_lines, adyen_plugin, adyen_payment_method
-):
- payment_info = create_payment_information(
- payment_adyen_for_order,
- payment_token="882595494831959A",
- additional_data={"paymentMethod": adyen_payment_method},
- )
- gateway_response = GatewayResponse(
- kind=TransactionKind.AUTH,
- action_required=False,
- transaction_id="882595494831959A",
- is_success=True,
- amount=payment_info.amount,
- currency=payment_info.currency,
- error="",
- )
-
- create_transaction(
- payment=payment_adyen_for_order,
- payment_information=payment_info,
- kind=TransactionKind.AUTH,
- gateway_response=gateway_response,
- )
- response = adyen_plugin().capture_payment(payment_info, None)
- assert response.is_success is True
- assert response.action_required is False
- assert response.kind == TransactionKind.CAPTURE
- assert response.amount == Decimal("80.00")
- assert response.currency == order_with_lines.currency
- assert response.transaction_id == "852610007697063J" # ID returned by Adyen
-
-
[email protected](HTTPSession, "request")
-def test_validate_plugin_configuration_incorrect_certificate(
- mocked_request, adyen_plugin
-):
- plugin = adyen_plugin(apple_pay_cert="cert")
- mocked_request.side_effect = SSLError()
- configuration = PluginConfiguration.objects.get()
- with pytest.raises(ValidationError):
- plugin.validate_plugin_configuration(configuration)
-
-
[email protected](HTTPSession, "request")
-def test_validate_plugin_configuration_correct_cert(mocked_request, adyen_plugin):
- plugin = adyen_plugin(apple_pay_cert="correct_cert")
- mocked_request.side_effect = RequestException()
- configuration = PluginConfiguration.objects.get()
- plugin.validate_plugin_configuration(configuration)
-
-
-def test_validate_plugin_configuration_without_apple_cert(adyen_plugin):
- plugin = adyen_plugin(apple_pay_cert="correct_cert")
- configuration = [
- {"name": "api-key", "value": "key"},
- ]
- plugin_configuration = PluginConfiguration.objects.get()
- plugin_configuration.configuration = configuration
- plugin.validate_plugin_configuration(plugin_configuration)
-
-
[email protected]("saleor.payment.gateways.adyen.plugin.api_call")
-def test_adyen_check_payment_balance(
- api_call_mock, adyen_plugin, adyen_check_balance_response
-):
- api_call_mock.return_value = adyen_check_balance_response
- plugin = adyen_plugin()
-
- data = {
- "gatewayId": "mirumee.payments.gateway",
- "method": "givex",
- "card": {
- "cvc": "9891",
- "code": "1234567910",
- "money": {"currency": "GBP", "amount": Decimal(100.0)},
- },
- }
-
- result = plugin.check_payment_balance(data, None)
-
- assert result["pspReference"] == "851634546949980A"
- assert result["resultCode"] == "Success"
- assert result["balance"] == {"currency": "GBP", "value": 10000}
- api_call_mock.assert_called_once_with(
- {
- "merchantAccount": "SaleorECOM",
- "paymentMethod": {
- "type": "givex",
- "number": "1234567910",
- "securityCode": "9891",
- },
- "amount": {"currency": "GBP", "value": "10000"},
- },
- plugin.adyen.checkout.client.call_checkout_api,
- action="paymentMethods/balance",
- )
-
-
[email protected]("saleor.payment.gateways.adyen.plugin.api_call")
-def test_adyen_check_payment_balance_adyen_raises_error(api_call_mock, adyen_plugin):
- api_call_mock.return_value = Adyen.AdyenError("Error")
- plugin = adyen_plugin()
-
- data = {
- "gatewayId": "mirumee.payments.gateway",
- "method": "givex",
- "card": {
- "cvc": "9891",
- "code": "1234567910",
- "money": {"currency": "GBP", "amount": Decimal(100.0)},
- },
- }
-
- result = plugin.check_payment_balance(data, None)
-
- assert result == "Error"
- api_call_mock.assert_called_once_with(
- {
- "merchantAccount": "SaleorECOM",
- "paymentMethod": {
- "type": "givex",
- "number": "1234567910",
- "securityCode": "9891",
- },
- "amount": {"currency": "GBP", "value": "10000"},
- },
- plugin.adyen.checkout.client.call_checkout_api,
- action="paymentMethods/balance",
- )
-
-
[email protected]("requests.post")
-def test_adyen_check_payment_timeout(request_post_mock, adyen_plugin):
- plugin = adyen_plugin()
-
- data = {
- "gatewayId": "mirumee.payments.gateway",
- "method": "givex",
- "card": {
- "cvc": "9891",
- "code": "1234567910",
- "money": {"currency": "GBP", "amount": Decimal(100.0)},
- },
- }
-
- request_post_mock.side_effect = ConnectTimeout()
- res = plugin.check_payment_balance(data, None)
- assert res.startswith("Unable to process the payment request")
diff --git a/saleor/payment/gateways/adyen/tests/utils/__init__.py b/saleor/payment/gateways/adyen/tests/utils/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/saleor/payment/gateways/adyen/tests/utils/test_apple_pay.py b/saleor/payment/gateways/adyen/tests/utils/test_apple_pay.py
deleted file mode 100644
index 876c295630..0000000000
--- a/saleor/payment/gateways/adyen/tests/utils/test_apple_pay.py
+++ /dev/null
@@ -1,143 +0,0 @@
-from unittest import mock
-
-import pytest
-from requests_hardened import HTTPSession
-
-from saleor.payment import PaymentError
-from saleor.payment.gateways.adyen.utils.apple_pay import (
- initialize_apple_pay_session,
- validate_payment_data_for_apple_pay,
-)
-
-
- ("validation_url", "merchant_identifier", "domain", "display_name", "certificate"),
- [
- (
- "https://apple-pay-gateway.apple.com/paymentservices/startSession",
- "merchant.com.identifier",
- "saleor.com",
- None,
- "certifiate data",
- ),
- (None, "merchant.com.identifier", "saleor.com", "Saleor", "certifiate data"),
- (
- "https://apple-pay-gateway.apple.com/paymentservices/startSession",
- None,
- "saleor.com",
- "Saleor",
- "certifiate data",
- ),
- (
- "https://apple-pay-gateway.apple.com/paymentservices/startSession",
- "merchant.com.identifier",
- None,
- "Saleor",
- "certifiate data",
- ),
- (
- "https://not-whitelisted-domain.com/paymentservices/startSession",
- "merchant.com.identifier",
- "saleor.com",
- "Saleor",
- "certifiate data",
- ),
- (
- "https://apple-pay-gateway.apple.com/paymentservices/startSession",
- "merchant.com.identifier",
- "saleor.com",
- "Saleor",
- None,
- ),
- ],
-)
-def test_validate_payment_data_for_apple_pay_raises_payment_error(
- validation_url, merchant_identifier, domain, display_name, certificate
-):
- with pytest.raises(PaymentError):
- validate_payment_data_for_apple_pay(
- validation_url, merchant_identifier, domain, display_name, certificate
- )
-
-
-def test_validate_payment_data_for_apple_pay():
- validation_url = "https://apple-pay-gateway.apple.com/paymentservices/startSession"
- merchant_identifier = "merchant.com.identifier"
- domain = "saleor.com"
- display_name = "Saleor "
- certificate = "certifiate data"
-
- validate_payment_data_for_apple_pay(
- validation_url, merchant_identifier, domain, display_name, certificate
- )
-
-
[email protected]("saleor.payment.gateways.adyen.utils.apple_pay.NamedTemporaryFile")
[email protected](HTTPSession, "request")
-def test_initialize_payment_for_apple_pay(mocked_request, mocked_tmp_file):
- mocked_cert_file_name = "cert-file-name"
- mocked_file = mock.MagicMock()
- mocked_file.__enter__.return_value = mocked_file
- mocked_file.name = mocked_cert_file_name
- mocked_tmp_file.return_value = mocked_file
-
- mocked_response = mock.Mock()
- mocked_response.ok = True
- mocked_response.json.return_value = {
- "epochTimestamp": 1604652056653,
- "expiresAt": 1604655656653,
- "merchantSessionIdentifier": "SSH5EFCB46BA25C4B14B3F37795A7F5B974_BB8E",
- }
- mocked_request.return_value = mocked_response
-
- validation_url = "https://apple-pay-gateway.apple.com/paymentservices/startSession"
- merchant_identifier = "merchant.com.identifier"
- domain = "saleor.com"
- display_name = "Saleor Shop"
- certificate = "certifiate data"
-
- initialize_apple_pay_session(
- validation_url,
- merchant_identifier,
- domain,
- display_name,
- certificate,
- )
-
- expected_data = {
- "merchantIdentifier": merchant_identifier,
- "displayName": display_name,
- "initiative": "web",
- "initiativeContext": domain,
- }
-
- mocked_request.assert_called_with(
- "POST",
- validation_url,
- json=expected_data,
- cert=mocked_cert_file_name,
- allow_redirects=False,
- )
-
-
[email protected](HTTPSession, "request")
-def test_initialize_payment_for_apple_pay_request_failed(mocked_request):
- mocked_response = mock.Mock()
- mocked_response.ok = False
- mocked_response.json.return_value = {}
- mocked_request.return_value = mocked_response
-
- validation_url = "https://apple-pay-gateway.apple.com/paymentservices/startSession"
- merchant_identifier = "merchant.com.identifier"
- domain = "saleor.com"
- display_name = "Saleor Shop"
- certificate = "certifiate data"
-
- with pytest.raises(PaymentError):
- initialize_apple_pay_session(
- validation_url,
- merchant_identifier,
- domain,
- display_name,
- certificate,
- )
diff --git a/saleor/payment/gateways/adyen/tests/utils/test_common.py b/saleor/payment/gateways/adyen/tests/utils/test_common.py
deleted file mode 100644
index e45c413ad7..0000000000
--- a/saleor/payment/gateways/adyen/tests/utils/test_common.py
+++ /dev/null
@@ -1,1091 +0,0 @@
-import json
-from decimal import Decimal
-from unittest import mock
-
-import pytest
-from prices import Money, TaxedMoney
-
-from saleor.checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-from saleor.core.prices import quantize_price
-from saleor.payment import PaymentError
-from saleor.payment.gateways.adyen.utils.common import (
- append_checkout_details,
- get_payment_method_info,
- get_request_data_for_check_payment,
- get_shopper_locale_value,
- request_data_for_gateway_config,
- request_data_for_payment,
- update_payment_with_action_required_data,
-)
-from saleor.payment.interface import PaymentMethodInfo
-from saleor.payment.utils import price_from_minor_unit, price_to_minor_unit
-from saleor.plugins.manager import get_plugins_manager
-
-from ...utils.common import prepare_address_request_data
-
-
- ("country_code", "shopper_locale"),
- [("JP", "ja_JP"), ("ZZ", "en_US"), ("US", "en_US")],
-)
-def test_get_shopper_locale_value(country_code, shopper_locale, settings):
- # when
- result = get_shopper_locale_value(country_code)
-
- # then
- assert result == shopper_locale
-
-
-def test_append_checkout_details(
- dummy_payment_data, payment_dummy, checkout_ready_to_complete
-):
- # given
- checkout_ready_to_complete.payments.add(payment_dummy)
- channel_id = checkout_ready_to_complete.channel_id
- line = checkout_ready_to_complete.lines.first()
- payment_data = {
- "reference": "test",
- }
- country_code = checkout_ready_to_complete.get_country()
-
- # when
- result = append_checkout_details(dummy_payment_data, payment_data)
-
- # then
- variant_channel_listing = line.variant.channel_listings.get(channel_id=channel_id)
- variant_price = variant_channel_listing.price_amount
- variant_currency = variant_channel_listing.currency
- price = price_to_minor_unit(variant_price, variant_currency)
-
- assert result == {
- "reference": "test",
- "shopperLocale": get_shopper_locale_value(country_code),
- "countryCode": country_code,
- "lineItems": [
- {
- "description": f"{line.variant.product.name}, {line.variant.name}",
- "quantity": line.quantity,
- "id": line.variant.sku,
- "taxAmount": "0",
- "taxPercentage": 0,
- "amountExcludingTax": price,
- "amountIncludingTax": price,
- },
- {
- "amountExcludingTax": "1000",
- "amountIncludingTax": "1000",
- "description": "Shipping - DHL",
- "id": f"Shipping:{checkout_ready_to_complete.assigned_delivery.shipping_method_id}",
- "quantity": 1,
- "taxAmount": "0",
- "taxPercentage": 0,
- },
- ],
- }
-
-
-def test_append_checkout_details_without_sku(
- dummy_payment_data, payment_dummy, checkout_ready_to_complete
-):
- # given
- checkout_ready_to_complete.payments.add(payment_dummy)
- channel_id = checkout_ready_to_complete.channel_id
- line = checkout_ready_to_complete.lines.first()
- line.variant.sku = None
- line.variant.save()
- payment_data = {
- "reference": "test",
- }
- country_code = checkout_ready_to_complete.get_country()
-
- # when
- result = append_checkout_details(dummy_payment_data, payment_data)
-
- # then
- variant_channel_listing = line.variant.channel_listings.get(channel_id=channel_id)
- variant_price = variant_channel_listing.price_amount
- variant_currency = variant_channel_listing.currency
- price = price_to_minor_unit(variant_price, variant_currency)
-
- assert result == {
- "reference": "test",
- "shopperLocale": get_shopper_locale_value(country_code),
- "countryCode": country_code,
- "lineItems": [
- {
- "description": f"{line.variant.product.name}, {line.variant.name}",
- "quantity": line.quantity,
- "id": line.variant.get_global_id(),
- "taxAmount": "0",
- "taxPercentage": 0,
- "amountExcludingTax": price,
- "amountIncludingTax": price,
- },
- {
- "amountExcludingTax": "1000",
- "amountIncludingTax": "1000",
- "description": "Shipping - DHL",
- "id": f"Shipping:{checkout_ready_to_complete.assigned_delivery.shipping_method_id}",
- "quantity": 1,
- "taxAmount": "0",
- "taxPercentage": 0,
- },
- ],
- }
-
-
[email protected]("saleor.plugins.manager.PluginsManager.calculate_checkout_line_total")
[email protected]("saleor.plugins.manager.PluginsManager.calculate_checkout_line_unit_price")
-def test_append_checkout_details_tax_included(
- mocked_calculate_checkout_line_unit_price,
- mocked_calculate_checkout_line_total,
- dummy_payment_data,
- payment_dummy,
- checkout_ready_to_complete,
-):
- # given
- line = checkout_ready_to_complete.lines.first()
- quantity = line.quantity
-
- net = Money(100, "USD")
- gross = Money(123, "USD")
- # tax 23 %
- unit_price = quantize_price(TaxedMoney(net=net, gross=gross), "USD")
- total_price = quantize_price(
- TaxedMoney(net=net * quantity, gross=gross * quantity), "USD"
- )
-
- country_code = checkout_ready_to_complete.get_country()
-
- mocked_calculate_checkout_line_unit_price.return_value = unit_price
- mocked_calculate_checkout_line_total.return_value = total_price
-
- checkout_ready_to_complete.payments.add(payment_dummy)
- payment_data = {
- "reference": "test",
- }
-
- # when
- result = append_checkout_details(dummy_payment_data, payment_data)
-
- # then
-
- expected_result = {
- "reference": "test",
- "shopperLocale": get_shopper_locale_value(country_code),
- "countryCode": country_code,
- "lineItems": [
- {
- "description": f"{line.variant.product.name}, {line.variant.name}",
- "quantity": line.quantity,
- "id": line.variant.sku,
- "taxAmount": price_to_minor_unit((gross - net).amount, "USD"),
- "taxPercentage": 2300,
- "amountExcludingTax": price_to_minor_unit(net.amount, "USD"),
- "amountIncludingTax": price_to_minor_unit(gross.amount, "USD"),
- },
- {
- "amountExcludingTax": "1000",
- "amountIncludingTax": "1000",
- "description": "Shipping - DHL",
- "id": f"Shipping:{checkout_ready_to_complete.assigned_delivery.shipping_method_id}",
- "quantity": 1,
- "taxAmount": "0",
- "taxPercentage": 0,
- },
- ],
- }
- assert result == expected_result
-
-
-def test_request_data_for_payment_payment_not_valid(
- dummy_payment_data, dummy_address_data
-):
- # given
- dummy_payment_data.data = {
- "originUrl": "https://www.example.com",
- "is_valid": False,
- }
- dummy_payment_data.billing = dummy_address_data
- native_3d_secure = False
-
- # when
- with pytest.raises(PaymentError) as e:
- request_data_for_payment(
- dummy_payment_data,
- "https://www.example.com",
- "MerchantTestAccount",
- native_3d_secure,
- )
-
- # then
- assert str(e._excinfo[1]) == "Payment data are not valid."
-
-
-def test_request_data_for_payment(dummy_payment_data, dummy_address_data):
- # given
- return_url = "https://www.example.com"
- merchant_account = "MerchantTestAccount"
- origin_url = "https://www.example.com"
- data = {
- "is_valid": True,
- "riskData": {"clientData": "test_client_data"},
- "paymentMethod": {"type": "scheme"},
- "browserInfo": {"acceptHeader": "*/*", "colorDepth": 30, "language": "pl"},
- "shopperIP": "123",
- "originUrl": origin_url,
- }
- dummy_payment_data.data = data
- dummy_payment_data.billing = dummy_address_data
- dummy_payment_data.shipping = dummy_address_data
- native_3d_secure = False
-
- # when
- result = request_data_for_payment(
- dummy_payment_data, return_url, merchant_account, native_3d_secure
- )
-
- # then
- assert result == {
- "amount": {
- "value": price_to_minor_unit(
- dummy_payment_data.amount, dummy_payment_data.currency
- ),
- "currency": dummy_payment_data.currency,
- },
- "reference": dummy_payment_data.graphql_payment_id,
- "paymentMethod": {"type": "scheme"},
- "returnUrl": return_url,
- "merchantAccount": merchant_account,
- "origin": return_url,
- "shopperIP": data["shopperIP"],
- "browserInfo": data["browserInfo"],
- "channel": "web",
- "shopperEmail": "[email protected]",
- "shopperName": {
- "firstName": dummy_payment_data.billing.first_name,
- "lastName": dummy_payment_data.billing.last_name,
- },
- "shopperReference": "[email protected]",
- "deliveryAddress": {
- "city": "WROCŁAW",
- "country": "PL",
- "houseNumberOrName": "Mirumee Software",
- "postalCode": "53-601",
- "stateOrProvince": "ZZ",
- "street": "Tęczowa 7",
- },
- "billingAddress": {
- "city": "WROCŁAW",
- "country": "PL",
- "houseNumberOrName": "Mirumee Software",
- "postalCode": "53-601",
- "stateOrProvince": "ZZ",
- "street": "Tęczowa 7",
- },
- }
-
-
-def test_request_data_for_payment_when_missing_city_address_field(
- dummy_payment_data, dummy_address_data
-):
- # given
- return_url = "https://www.example.com"
- merchant_account = "MerchantTestAccount"
- origin_url = "https://www.example.com"
- data = {
- "is_valid": True,
- "riskData": {"clientData": "test_client_data"},
- "paymentMethod": {"type": "scheme"},
- "browserInfo": {"acceptHeader": "*/*", "colorDepth": 30, "language": "pl"},
- "shopperIP": "123",
- "originUrl": origin_url,
- }
- dummy_payment_data.data = data
-
- dummy_address_data.city = ""
- dummy_address_data.country_area = "Fallback_for_city"
- dummy_payment_data.billing = dummy_address_data
- dummy_payment_data.shipping = dummy_address_data
- native_3d_secure = False
-
- # when
- result = request_data_for_payment(
- dummy_payment_data, return_url, merchant_account, native_3d_secure
- )
-
- # then
- assert result["deliveryAddress"] == {
- "city": dummy_address_data.country_area,
- "country": "PL",
- "houseNumberOrName": "Mirumee Software",
- "postalCode": "53-601",
- "stateOrProvince": dummy_address_data.country_area,
- "street": "Tęczowa 7",
- }
- assert result["billingAddress"] == {
- "city": dummy_address_data.country_area,
- "country": "PL",
- "houseNumberOrName": "Mirumee Software",
- "postalCode": "53-601",
- "stateOrProvince": dummy_address_data.country_area,
- "street": "Tęczowa 7",
- }
-
-
-def test_request_data_for_payment_when_missing_city_and_count_area(
- dummy_payment_data, dummy_address_data
-):
- # given
- return_url = "https://www.example.com"
- merchant_account = "MerchantTestAccount"
- origin_url = "https://www.example.com"
- data = {
- "is_valid": True,
- "riskData": {"clientData": "test_client_data"},
- "paymentMethod": {"type": "scheme"},
- "browserInfo": {"acceptHeader": "*/*", "colorDepth": 30, "language": "pl"},
- "shopperIP": "123",
- "originUrl": origin_url,
- }
- dummy_payment_data.data = data
-
- dummy_address_data.city = ""
- dummy_address_data.country_area = ""
- dummy_payment_data.billing = dummy_address_data
- dummy_payment_data.shipping = dummy_address_data
- native_3d_secure = False
-
- # when
- result = request_data_for_payment(
- dummy_payment_data, return_url, merchant_account, native_3d_secure
- )
-
- # then
- assert result["deliveryAddress"] == {
- "city": "ZZ",
- "country": "PL",
- "houseNumberOrName": "Mirumee Software",
- "postalCode": "53-601",
- "stateOrProvince": "ZZ",
- "street": "Tęczowa 7",
- }
- assert result["billingAddress"] == {
- "city": "ZZ",
- "country": "PL",
- "houseNumberOrName": "Mirumee Software",
- "postalCode": "53-601",
- "stateOrProvince": "ZZ",
- "street": "Tęczowa 7",
- }
-
-
-def test_request_data_for_payment_when_missing_postal_code(
- dummy_payment_data, dummy_address_data
-):
- # given
- return_url = "https://www.example.com"
- merchant_account = "MerchantTestAccount"
- origin_url = "https://www.example.com"
- data = {
- "is_valid": True,
- "riskData": {"clientData": "test_client_data"},
- "paymentMethod": {"type": "scheme"},
- "browserInfo": {"acceptHeader": "*/*", "colorDepth": 30, "language": "pl"},
- "shopperIP": "123",
- "originUrl": origin_url,
- }
- dummy_payment_data.data = data
-
- dummy_address_data.postal_code = ""
- dummy_payment_data.billing = dummy_address_data
- dummy_payment_data.shipping = dummy_address_data
- native_3d_secure = False
-
- # when
- result = request_data_for_payment(
- dummy_payment_data, return_url, merchant_account, native_3d_secure
- )
-
- # then
- assert result["deliveryAddress"] == {
- "city": "WROCŁAW",
- "country": "PL",
- "houseNumberOrName": "Mirumee Software",
- "postalCode": "ZZ",
- "stateOrProvince": "ZZ",
- "street": "Tęczowa 7",
- }
- assert result["billingAddress"] == {
- "city": "WROCŁAW",
- "country": "PL",
- "houseNumberOrName": "Mirumee Software",
- "postalCode": "ZZ",
- "stateOrProvince": "ZZ",
- "street": "Tęczowa 7",
- }
-
-
-def test_request_data_for_payment_without_shipping(
- dummy_payment_data, dummy_address_data
-):
- # given
- return_url = "https://www.example.com"
- merchant_account = "MerchantTestAccount"
- origin_url = "https://www.example.com"
- data = {
- "is_valid": True,
- "riskData": {"clientData": "test_client_data"},
- "paymentMethod": {"type": "scheme"},
- "browserInfo": {"acceptHeader": "*/*", "colorDepth": 30, "language": "pl"},
- "shopperIP": "123",
- "originUrl": origin_url,
- }
- dummy_payment_data.data = data
- dummy_payment_data.billing = dummy_address_data
- dummy_payment_data.shipping = None
- native_3d_secure = False
-
- # when
- result = request_data_for_payment(
- dummy_payment_data, return_url, merchant_account, native_3d_secure
- )
-
- # then
- assert result == {
- "amount": {
- "value": price_to_minor_unit(
- dummy_payment_data.amount, dummy_payment_data.currency
- ),
- "currency": dummy_payment_data.currency,
- },
- "reference": dummy_payment_data.graphql_payment_id,
- "paymentMethod": {"type": "scheme"},
- "returnUrl": return_url,
- "merchantAccount": merchant_account,
- "origin": return_url,
- "shopperIP": data["shopperIP"],
- "browserInfo": data["browserInfo"],
- "channel": "web",
- "shopperEmail": "[email protected]",
- "shopperName": {
- "firstName": dummy_payment_data.billing.first_name,
- "lastName": dummy_payment_data.billing.last_name,
- },
- "shopperReference": "[email protected]",
- "billingAddress": {
- "city": "WROCŁAW",
- "country": "PL",
- "houseNumberOrName": "Mirumee Software",
- "postalCode": "53-601",
- "stateOrProvince": "ZZ",
- "street": "Tęczowa 7",
- },
- }
-
-
-def test_request_data_for_payment_native_3d_secure(
- dummy_payment_data, dummy_address_data
-):
- # given
- return_url = "https://www.example.com"
- merchant_account = "MerchantTestAccount"
- origin_url = "https://www.example.com"
- data = {
- "is_valid": True,
- "riskData": {"clientData": "test_client_data"},
- "paymentMethod": {"type": "scheme"},
- "browserInfo": {"acceptHeader": "*/*", "colorDepth": 30, "language": "pl"},
- "shopperIP": "123",
- "originUrl": origin_url,
- }
- dummy_payment_data.data = data
- dummy_payment_data.shipping = dummy_address_data
- dummy_payment_data.billing = dummy_address_data
- native_3d_secure = True
-
- # when
- result = request_data_for_payment(
- dummy_payment_data, return_url, merchant_account, native_3d_secure
- )
-
- # then
- assert result == {
- "amount": {
- "value": price_to_minor_unit(
- dummy_payment_data.amount, dummy_payment_data.currency
- ),
- "currency": dummy_payment_data.currency,
- },
- "reference": dummy_payment_data.graphql_payment_id,
- "paymentMethod": {"type": "scheme"},
- "returnUrl": return_url,
- "merchantAccount": merchant_account,
- "origin": return_url,
- "shopperIP": data["shopperIP"],
- "browserInfo": data["browserInfo"],
- "channel": "web",
- "additionalData": {"allow3DS2": "true"},
- "shopperEmail": "[email protected]",
- "shopperName": {
- "firstName": dummy_payment_data.billing.first_name,
- "lastName": dummy_payment_data.billing.last_name,
- },
- "shopperReference": "[email protected]",
- "deliveryAddress": {
- "city": "WROCŁAW",
- "country": "PL",
- "houseNumberOrName": "Mirumee Software",
- "postalCode": "53-601",
- "stateOrProvince": "ZZ",
- "street": "Tęczowa 7",
- },
- "billingAddress": {
- "city": "WROCŁAW",
- "country": "PL",
- "houseNumberOrName": "Mirumee Software",
- "postalCode": "53-601",
- "stateOrProvince": "ZZ",
- "street": "Tęczowa 7",
- },
- }
-
-
-def test_request_data_for_payment_channel_different_than_web(
- dummy_payment_data, dummy_address_data
-):
- # given
- return_url = "https://www.example.com"
- merchant_account = "MerchantTestAccount"
- data = {"is_valid": True, "paymentMethod": {"type": "scheme"}, "channel": "iOS"}
- dummy_payment_data.data = data
- dummy_payment_data.billing = dummy_address_data
- dummy_payment_data.shipping = dummy_address_data
- native_3d_secure = True
-
- # when
- result = request_data_for_payment(
- dummy_payment_data, return_url, merchant_account, native_3d_secure
- )
-
- # then
- assert result == {
- "amount": {
- "value": price_to_minor_unit(
- dummy_payment_data.amount, dummy_payment_data.currency
- ),
- "currency": dummy_payment_data.currency,
- },
- "reference": dummy_payment_data.graphql_payment_id,
- "paymentMethod": {"type": "scheme"},
- "returnUrl": return_url,
- "merchantAccount": merchant_account,
- "channel": "iOS",
- "additionalData": {"allow3DS2": "true"},
- "shopperEmail": "[email protected]",
- "shopperName": {
- "firstName": dummy_payment_data.billing.first_name,
- "lastName": dummy_payment_data.billing.last_name,
- },
- "shopperReference": "[email protected]",
- "deliveryAddress": {
- "city": "WROCŁAW",
- "country": "PL",
- "houseNumberOrName": "Mirumee Software",
- "postalCode": "53-601",
- "stateOrProvince": "ZZ",
- "street": "Tęczowa 7",
- },
- "billingAddress": {
- "city": "WROCŁAW",
- "country": "PL",
- "houseNumberOrName": "Mirumee Software",
- "postalCode": "53-601",
- "stateOrProvince": "ZZ",
- "street": "Tęczowa 7",
- },
- }
-
-
[email protected]("method_type", ["klarna", "clearpay", "afterpaytouch"])
[email protected]("saleor.payment.gateways.adyen.utils.common.append_checkout_details")
-def test_request_data_for_payment_append_checkout_details(
- append_checkout_details_mock, method_type, dummy_payment_data, dummy_address_data
-):
- # given
- return_url = "https://www.example.com"
- merchant_account = "MerchantTestAccount"
- origin_url = "https://www.example.com"
- data = {
- "is_valid": True,
- "riskData": {"clientData": "test_client_data"},
- "paymentMethod": {"type": method_type},
- "browserInfo": {"acceptHeader": "*/*", "colorDepth": 30, "language": "pl"},
- "shopperIP": "123",
- "originUrl": origin_url,
- }
- dummy_payment_data.data = data
- dummy_payment_data.billing = dummy_address_data
- dummy_payment_data.shipping = dummy_address_data
-
- checkout_details_result = {
- "amount": {
- "value": price_to_minor_unit(
- dummy_payment_data.amount, dummy_payment_data.currency
- ),
- "currency": dummy_payment_data.currency,
- },
- "reference": dummy_payment_data.graphql_payment_id,
- "paymentMethod": {"type": "scheme"},
- "returnUrl": return_url,
- "merchantAccount": merchant_account,
- "origin": return_url,
- "shopperIP": data["shopperIP"],
- "browserInfo": data["browserInfo"],
- "shopperLocale": "test_shopper",
- "shopperName": {
- "firstName": dummy_payment_data.billing.first_name,
- "lastName": dummy_payment_data.billing.last_name,
- },
- "shopperReference": "[email protected]",
- "deliveryAddress": {
- "city": "WROCŁAW",
- "country": "PL",
- "houseNumberOrName": "Mirumee Software",
- "postalCode": "53-601",
- "stateOrProvince": "",
- "street": "Tęczowa 7",
- },
- "billingAddress": {
- "city": "WROCŁAW",
- "country": "PL",
- "houseNumberOrName": "Mirumee Software",
- "postalCode": "53-601",
- "stateOrProvince": "",
- "street": "Tęczowa 7",
- },
- }
- append_checkout_details_mock.return_value = checkout_details_result
- native_3d_secure = False
- # when
- result = request_data_for_payment(
- dummy_payment_data, return_url, merchant_account, native_3d_secure
- )
-
- # then
- assert result == checkout_details_result
-
-
- ("value", "currency", "expected_result"),
- [
- (Decimal(1000), "EUR", Decimal(10)),
- (Decimal(1), "PLN", Decimal("0.01")),
- (Decimal(51), "US", Decimal("0.51")),
- ],
-)
-def test_from_adyen_price(value, currency, expected_result):
- # when
- result = price_from_minor_unit(value, currency)
-
- # then
- assert result == expected_result
-
-
- ("value", "currency", "expected_result"),
- [
- (Decimal(10), "EUR", "1000"),
- (Decimal(1), "PLN", "100"),
- (Decimal(100), "US", "10000"),
- ],
-)
-def test_to_adyen_price(value, currency, expected_result):
- # when
- result = price_to_minor_unit(value, currency)
-
- # then
- assert result == expected_result
-
-
-def test_request_data_for_gateway_config(
- checkout_with_item, address, address_other_country
-):
- # given
- checkout_with_item.shipping_address = address
- checkout_with_item.billing_address = address_other_country
- assert address.country.code != address_other_country.country.code
-
- merchant_account = "test_account"
- manager = get_plugins_manager(allow_replica=False)
- lines_info, _ = fetch_checkout_lines(checkout_with_item)
- checkout_info = fetch_checkout_info(checkout_with_item, lines_info, manager)
-
- # when
- response_config = request_data_for_gateway_config(
- checkout_info, lines_info, merchant_account
- )
-
- # then
- assert response_config == {
- "merchantAccount": merchant_account,
- "countryCode": checkout_with_item.shipping_address.country,
- "channel": "web",
- "amount": {"currency": "USD", "value": "3000"},
- }
-
-
-def test_request_data_for_gateway_config_no_country(checkout, address, settings):
- # given
- merchant_account = "test_account"
- manager = get_plugins_manager(allow_replica=False)
- lines_info, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines_info, manager)
-
- # when
- response_config = request_data_for_gateway_config(
- checkout_info, lines_info, merchant_account
- )
-
- # then
- assert response_config == {
- "merchantAccount": merchant_account,
- "countryCode": settings.DEFAULT_COUNTRY,
- "channel": "web",
- "amount": {"currency": "USD", "value": "0"},
- }
-
-
-def test_update_payment_with_action_required_data_empty_extra_data(
- payment_adyen_for_checkout,
-):
- # given
- payment_adyen_for_checkout.extra_data = ""
- payment_adyen_for_checkout.save(update_fields=["extra_data"])
-
- action = {
- "paymentData": "test_data",
- }
- details = [
- {"key": "payload", "type": "text"},
- {"key": "secondParam", "type": "text"},
- ]
-
- # when
- update_payment_with_action_required_data(
- payment_adyen_for_checkout, action, details
- )
-
- # then
- payment_adyen_for_checkout.refresh_from_db()
- extra_data = json.loads(payment_adyen_for_checkout.extra_data)
- assert len(extra_data) == 1
- assert extra_data[0]["payment_data"] == action["paymentData"]
- assert set(extra_data[0]["parameters"]) == {"payload", "secondParam"}
-
-
-def test_update_payment_with_action_required_data_extra_data_as_list(
- payment_adyen_for_checkout,
-):
- # given
- payment_adyen_for_checkout.extra_data = json.dumps([{"test_data": "test"}])
- payment_adyen_for_checkout.save(update_fields=["extra_data"])
-
- action = {
- "paymentData": "test_data",
- }
- details = [
- {"key": "payload", "type": "text"},
- {"key": "secondParam", "type": "text"},
- ]
-
- # when
- update_payment_with_action_required_data(
- payment_adyen_for_checkout, action, details
- )
-
- # then
- payment_adyen_for_checkout.refresh_from_db()
- extra_data = json.loads(payment_adyen_for_checkout.extra_data)
- assert len(extra_data) == 2
- assert extra_data[1]["payment_data"] == action["paymentData"]
- assert set(extra_data[1]["parameters"]) == {"payload", "secondParam"}
-
-
-def test_update_payment_with_action_required_data_extra_data_as_dict(
- payment_adyen_for_checkout,
-):
- # given
- payment_adyen_for_checkout.extra_data = json.dumps({"test_data": "test"})
- payment_adyen_for_checkout.save(update_fields=["extra_data"])
-
- action = {
- "paymentData": "test_data",
- }
- details = [
- {"key": "payload", "type": "text"},
- {"key": "secondParam", "type": "text"},
- ]
-
- # when
- update_payment_with_action_required_data(
- payment_adyen_for_checkout, action, details
- )
-
- # then
- payment_adyen_for_checkout.refresh_from_db()
- extra_data = json.loads(payment_adyen_for_checkout.extra_data)
- assert len(extra_data) == 2
- assert extra_data[1]["payment_data"] == action["paymentData"]
- assert set(extra_data[1]["parameters"]) == {"payload", "secondParam"}
-
-
-def test_get_payment_method_info(dummy_payment_data):
- # given
- data = {"paymentMethod": {"type": "klarna"}}
- dummy_payment_data.data = data
-
- api_call_result_mock = mock.Mock()
- message = {"additionalData": {"paymentMethod": "visa-test"}}
- api_call_result_mock.message = message
-
- # when
- payment_method_info = get_payment_method_info(
- dummy_payment_data, api_call_result_mock
- )
-
- # then
- assert payment_method_info == PaymentMethodInfo(
- brand=message["additionalData"]["paymentMethod"],
- type=data["paymentMethod"]["type"],
- )
-
-
-def test_get_payment_method_info_scheme_payment_method_type(dummy_payment_data):
- # given
- data = {"paymentMethod": {"type": "scheme"}}
- dummy_payment_data.data = data
-
- api_call_result_mock = mock.Mock()
- message = {"additionalData": {"paymentMethod": "visa-test"}}
- api_call_result_mock.message = message
-
- # when
- payment_method_info = get_payment_method_info(
- dummy_payment_data, api_call_result_mock
- )
-
- # then
- assert payment_method_info == PaymentMethodInfo(
- brand=message["additionalData"]["paymentMethod"], type="card"
- )
-
-
-def test_get_payment_method_info_no_additional_data(dummy_payment_data):
- # given
- data = {"paymentMethod": {"type": "scheme"}}
- dummy_payment_data.data = data
-
- api_call_result_mock = mock.Mock()
- message = {}
- api_call_result_mock.message = message
-
- # when
- payment_method_info = get_payment_method_info(
- dummy_payment_data, api_call_result_mock
- )
-
- # then
- assert payment_method_info == PaymentMethodInfo(type="card")
-
-
-def test_prepare_address_request_data_address_is_none():
- assert not prepare_address_request_data(None)
-
-
-def test_prepare_address_request_data_without_city_country_code_and_areas(
- address_with_areas,
-):
- address = address_with_areas
- address.city = ""
- address.country_area = ""
- address.city_area = ""
- address.country = ""
- address.postal_code = ""
- address.save(
- update_fields=["city", "country", "postal_code", "city_area", "country_area"]
- )
- address.refresh_from_db()
-
- result = prepare_address_request_data(address)
-
- assert result["city"] == "ZZ"
- assert result["country"] == "ZZ"
- assert result["houseNumberOrName"] == "Mirumee Software"
- assert result["postalCode"] == "ZZ"
- assert result["stateOrProvince"] == "ZZ"
- assert result["street"] == "Tęczowa 7"
-
-
-def test_prepare_address_request_data_address_fulfilled(address_with_areas):
- result = prepare_address_request_data(address_with_areas)
-
- assert result["city"] == "WROCŁAW"
- assert result["country"] == "PL"
- assert result["houseNumberOrName"] == "Mirumee Software"
- assert result["postalCode"] == "53-601"
- assert result["stateOrProvince"] == "test_country_area"
- assert result["street"] == "Tęczowa 7"
-
-
-def test_prepare_address_request_data_without_company_name_and_street_addr_2(
- address_with_areas,
-):
- address = address_with_areas
- address.company_name = ""
- address.save(update_fields=["company_name"])
- address.refresh_from_db()
-
- result = prepare_address_request_data(address)
-
- assert result["city"] == "WROCŁAW"
- assert result["country"] == "PL"
- assert result["houseNumberOrName"] == ""
- assert result["postalCode"] == "53-601"
- assert result["stateOrProvince"] == "test_country_area"
- assert result["street"] == "Tęczowa 7"
-
-
-def test_prepare_address_request_data_with_company_name_and_street_addr_2(
- address_with_areas,
-):
- address = address_with_areas
- address.street_address_2 = "street_address_2"
- address.save(update_fields=["street_address_2"])
- address.refresh_from_db()
-
- result = prepare_address_request_data(address)
-
- assert result["city"] == "WROCŁAW"
- assert result["country"] == "PL"
- assert result["houseNumberOrName"] == "Mirumee Software"
- assert result["postalCode"] == "53-601"
- assert result["stateOrProvince"] == "test_country_area"
- assert result["street"] == "Tęczowa 7 street_address_2"
-
-
-def test_prepare_address_request_data_without_company_with_street_addr_2(
- address_with_areas,
-):
- address = address_with_areas
- address.company_name = ""
- address.street_address_2 = "street_address_2"
- address.save(update_fields=["company_name", "street_address_2"])
- address.refresh_from_db()
-
- result = prepare_address_request_data(address)
-
- assert result["city"] == "WROCŁAW"
- assert result["country"] == "PL"
- assert result["houseNumberOrName"] == "Tęczowa 7"
- assert result["postalCode"] == "53-601"
- assert result["stateOrProvince"] == "test_country_area"
- assert result["street"] == "street_address_2"
-
-
-def test_prepare_address_request_data_with_country_area_without_city_area(
- address_with_areas,
-):
- address = address_with_areas
- address.city_area = ""
- address.save(update_fields=["city_area"])
- address.refresh_from_db()
-
- result = prepare_address_request_data(address)
-
- assert result["city"] == "WROCŁAW"
- assert result["country"] == "PL"
- assert result["houseNumberOrName"] == "Mirumee Software"
- assert result["postalCode"] == "53-601"
- assert result["stateOrProvince"] == "test_country_area"
- assert result["street"] == "Tęczowa 7"
-
-
-def test_prepare_address_request_data_with_city_area_without_country_area(
- address_with_areas,
-):
- address = address_with_areas
- address.country_area = ""
- address.save(update_fields=["country_area"])
- address.refresh_from_db()
-
- result = prepare_address_request_data(address)
-
- assert result["city"] == "WROCŁAW"
- assert result["country"] == "PL"
- assert result["houseNumberOrName"] == "Mirumee Software"
- assert result["postalCode"] == "53-601"
- assert result["stateOrProvince"] == "ZZ"
- assert result["street"] == "Tęczowa 7"
-
-
-def test_get_request_data_for_check_payment():
- data = get_request_data_for_check_payment(
- {
- "method": "test",
- "card": {
- "code": "1243456",
- "cvc": "123",
- "money": {"amount": Decimal(10.05), "currency": "EUR"},
- },
- },
- merchant_account="TEST_ACCOUNT",
- )
-
- assert data["merchantAccount"] == "TEST_ACCOUNT"
- assert data["paymentMethod"]["type"] == "test"
- assert data["paymentMethod"]["number"] == "1243456"
- assert data["paymentMethod"]["securityCode"] == "123"
- assert data["amount"]["value"] == "1005"
- assert data["amount"]["currency"] == "EUR"
-
-
-def test_get_request_data_for_check_payment_without_money():
- data = get_request_data_for_check_payment(
- {"method": "test", "card": {"code": "1243456", "cvc": "123"}},
- merchant_account="TEST_ACCOUNT",
- )
-
- assert data["merchantAccount"] == "TEST_ACCOUNT"
- assert data["paymentMethod"]["type"] == "test"
- assert data["paymentMethod"]["number"] == "1243456"
- assert data["paymentMethod"]["securityCode"] == "123"
-
-
-def test_get_request_data_for_check_payment_without_cvc():
- data = get_request_data_for_check_payment(
- {
- "method": "test",
- "card": {
- "code": "1243456",
- "money": {"amount": Decimal(10.05), "currency": "EUR"},
- },
- },
- merchant_account="TEST_ACCOUNT",
- )
-
- assert data["merchantAccount"] == "TEST_ACCOUNT"
- assert data["paymentMethod"]["type"] == "test"
- assert data["paymentMethod"]["number"] == "1243456"
- assert data["amount"]["value"] == "1005"
- assert data["amount"]["currency"] == "EUR"
-
-
-def test_get_request_data_for_check_payment_without_cvc_and_money():
- data = get_request_data_for_check_payment(
- {"method": "test", "card": {"code": "1243456"}}, merchant_account="TEST_ACCOUNT"
- )
-
- assert data["merchantAccount"] == "TEST_ACCOUNT"
- assert data["paymentMethod"]["type"] == "test"
- assert data["paymentMethod"]["number"] == "1243456"
diff --git a/saleor/payment/gateways/adyen/tests/webhooks/__init__.py b/saleor/payment/gateways/adyen/tests/webhooks/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/saleor/payment/gateways/adyen/tests/webhooks/cassettes/test_handle_notifications/test_handle_authorization_with_auto_capture.yaml b/saleor/payment/gateways/adyen/tests/webhooks/cassettes/test_handle_notifications/test_handle_authorization_with_auto_capture.yaml
deleted file mode 100644
index 7b0ad7bdc3..0000000000
--- a/saleor/payment/gateways/adyen/tests/webhooks/cassettes/test_handle_notifications/test_handle_authorization_with_auto_capture.yaml
+++ /dev/null
@@ -1,49 +0,0 @@
-interactions:
-- request:
- body: '{"merchantAccount": "SaleorECOM", "modificationAmount": {"value": "8000",
- "currency": "USD"}, "originalReference": "853596537720508F", "reference": "UGF5bWVudDoxMTk5",
- "applicationInfo": {"adyenLibrary": {"name": "adyen-python-api-library", "version":
- "4.0.0"}}}'
- headers:
- Accept:
- - '*/*'
- Accept-Encoding:
- - gzip, deflate
- Connection:
- - keep-alive
- Content-Length:
- - '262'
- Content-Type:
- - application/json
- User-Agent:
- - adyen-python-api-library/4.0.0
- x-api-key:
- - test_key
- method: POST
- uri: https://pal-test.adyen.com/pal/servlet/Payment/v64/capture
- response:
- body:
- string: '{"pspReference":"853610013045881J","response":"[capture-received]"}'
- headers:
- Adyen-ServerState:
- - HIGH
- Connection:
- - Keep-Alive
- Content-Type:
- - application/json;charset=utf-8
- Date:
- - Thu, 07 Jan 2021 09:50:45 GMT
- Keep-Alive:
- - timeout=15, max=100
- Server:
- - Apache
- Set-Cookie:
- - JSESSIONID=F00A8F106CFADD404CBCDF6D896235D3.test4e; Path=/pal; Secure; HttpOnly
- Transfer-Encoding:
- - chunked
- pspReference:
- - 853610013045881J
- status:
- code: 200
- message: '200'
-version: 1
diff --git a/saleor/payment/gateways/adyen/tests/webhooks/test_get_or_create_adyen_partial_payments.py b/saleor/payment/gateways/adyen/tests/webhooks/test_get_or_create_adyen_partial_payments.py
deleted file mode 100644
index b68f4e2303..0000000000
--- a/saleor/payment/gateways/adyen/tests/webhooks/test_get_or_create_adyen_partial_payments.py
+++ /dev/null
@@ -1,84 +0,0 @@
-from decimal import Decimal
-
-from ...webhooks import get_or_create_adyen_partial_payments
-
-
-def test_get_or_create_adyen_partial_payments_with_additional_actions_response(
- payment_adyen_for_checkout,
-):
- # given
- notification_data = {
- "additionalData": {
- "order-2-paymentMethod": "visa",
- "threeds2.cardEnrolled": "false",
- "order-2-pspReference": "861643021198177D",
- "order-2-paymentAmount": "GBP 16.29",
- "recurringProcessingModel": "Subscription",
- "paymentMethod": "visa",
- "order-1-pspReference": "861643021155073F",
- "order-1-paymentAmount": "GBP 14.71",
- "order-1-paymentMethod": "givex",
- },
- "pspReference": "861643021198177D",
- "resultCode": "Authorised",
- "merchantReference": "UGF5bWVudDoyNw==",
- "paymentMethod": "visa",
- "shopperLocale": "en_GB",
- }
-
- checkout = payment_adyen_for_checkout.checkout
-
- # when
- get_or_create_adyen_partial_payments(notification_data, payment_adyen_for_checkout)
-
- # then
- partial_payments = list(checkout.payments.exclude(id=payment_adyen_for_checkout.id))
-
- assert len(partial_payments) == 2
- assert all(payment.is_active is False for payment in partial_payments)
- assert all(payment.partial is True for payment in partial_payments)
- assert all(payment.is_active is False for payment in partial_payments)
- assert any(payment.total == Decimal("14.71") for payment in partial_payments)
- assert any(payment.total == Decimal("16.29") for payment in partial_payments)
- assert any(
- payment.psp_reference == "861643021155073F" for payment in partial_payments
- )
- assert any(
- payment.psp_reference == "861643021198177D" for payment in partial_payments
- )
-
-
-def test_get_or_create_adyen_partial_payments_with_notification_payload(
- notification, payment_adyen_for_checkout
-):
- # given
- notification_data = notification()
- notification_data["additionalData"] = {
- "order-2-paymentMethod": "visa",
- "order-2-pspReference": "881643125782168B",
- "order-2-paymentAmount": "GBP 29.10",
- "order-1-pspReference": "861643125754056E",
- "order-1-paymentAmount": "GBP 41.90",
- "order-1-paymentMethod": "givex",
- }
-
- checkout = payment_adyen_for_checkout.checkout
-
- # when
- get_or_create_adyen_partial_payments(notification_data, payment_adyen_for_checkout)
-
- # then
- partial_payments = list(checkout.payments.exclude(id=payment_adyen_for_checkout.id))
-
- assert len(partial_payments) == 2
- assert all(payment.is_active is False for payment in partial_payments)
- assert all(payment.partial is True for payment in partial_payments)
- assert all(payment.is_active is False for payment in partial_payments)
- assert any(payment.total == Decimal("29.10") for payment in partial_payments)
- assert any(payment.total == Decimal("41.90") for payment in partial_payments)
- assert any(
- payment.psp_reference == "881643125782168B" for payment in partial_payments
- )
- assert any(
- payment.psp_reference == "861643125754056E" for payment in partial_payments
- )
diff --git a/saleor/payment/gateways/adyen/tests/webhooks/test_get_payment.py b/saleor/payment/gateways/adyen/tests/webhooks/test_get_payment.py
deleted file mode 100644
index e6bfe6a1cc..0000000000
--- a/saleor/payment/gateways/adyen/tests/webhooks/test_get_payment.py
+++ /dev/null
@@ -1,71 +0,0 @@
-import logging
-
-import graphene
-import pytest
-
-from ...webhooks import get_payment
-
-logger = logging.getLogger(__name__)
-
-
[email protected]("payment_id", ["123", "Test payment ID", "ó À È Ì Ò Ù Ỳ"])
-def test_get_payment_invalid_payment_id(payment_id, caplog):
- # given
- caplog.set_level(logging.WARNING)
-
- # when
- result = get_payment(payment_id)
-
- # then
- assert result is None
- assert f"Unable to decode the payment ID {payment_id}." in caplog.text
-
-
[email protected]("payment_id", [" ", None])
-def test_get_payment_missing_payment_id(payment_id, caplog):
- # given
- caplog.set_level(logging.WARNING)
-
- # when
- result = get_payment(payment_id)
-
- # then
- assert result is None
- assert "Missing payment ID." in caplog.text
-
-
-def test_get_payment_not_active_payment(payment_dummy, caplog):
- # given
- caplog.set_level(logging.WARNING)
-
- payment_dummy.is_active = False
- payment_dummy.save(update_fields=["is_active"])
-
- payment_id = graphene.Node.to_global_id("Payment", payment_dummy.pk)
- transaction_id = "psp reference"
-
- # when
- result = get_payment(payment_id, transaction_id)
-
- # then
- expected_msg = (
- f"Payment for {payment_id} ({payment_dummy.pk}) was not found. Reference "
- f"{transaction_id}"
- )
- assert not result
- assert expected_msg in caplog.text
-
-
-def test_get_payment_for_notification_related_to_transaction_item(payment_dummy):
- # given
-
- incorrect_payment_id = graphene.Node.to_global_id(
- "TransactionItem", payment_dummy.pk
- )
- transaction_id = "psp reference"
-
- # when
- result = get_payment(incorrect_payment_id, transaction_id)
-
- # then
- assert not result
diff --git a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_additional_actions.py b/saleor/payment/gateways/adyen/tests/webhooks/test_handle_additional_actions.py
deleted file mode 100644
index a7848face0..0000000000
--- a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_additional_actions.py
+++ /dev/null
@@ -1,887 +0,0 @@
-import json
-import uuid
-from decimal import Decimal
-from unittest import mock
-from urllib.parse import quote_plus
-
-import graphene
-import pytest
-
-from ......order import OrderEvents
-from ..... import PaymentError, TransactionKind
-from ...webhooks import handle_additional_actions
-
-ERROR_MSG_MISSING_PAYMENT = "Cannot perform payment. There is no active Adyen payment."
-ERROR_MSG_MISSING_CHECKOUT = (
- "Cannot perform payment. There is no checkout with this payment."
-)
-
-
[email protected]("saleor.payment.gateways.adyen.webhooks.payment_refund_or_void")
[email protected]("saleor.payment.gateways.adyen.webhooks.api_call")
-def test_handle_additional_actions_post(
- api_call_mock, _, payment_adyen_for_checkout, adyen_plugin
-):
- # given
- plugin = adyen_plugin()
- channel_slug = plugin.channel.slug
- payment_adyen_for_checkout.to_confirm = True
- payment_adyen_for_checkout.extra_data = json.dumps(
- [{"payment_data": "test_data", "parameters": ["payload"]}]
- )
- payment_adyen_for_checkout.save(update_fields=["to_confirm", "extra_data"])
-
- transaction_count = payment_adyen_for_checkout.transactions.all().count()
-
- checkout = payment_adyen_for_checkout.checkout
- payment_id = graphene.Node.to_global_id("Payment", payment_adyen_for_checkout.pk)
- checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
-
- request_mock = mock.Mock()
- request_mock.GET = {"payment": payment_id, "checkout": str(checkout.pk)}
- request_mock.POST = {"payload": "test"}
-
- payment_details_mock = mock.Mock()
- message = {
- "pspReference": "11111",
- "resultCode": "Test",
- }
- api_call_mock.return_value.message = message
-
- # when
- response = handle_additional_actions(
- request_mock, payment_details_mock, channel_slug
- )
-
- # then
- payment_adyen_for_checkout.refresh_from_db()
- assert response.status_code == 302
- assert f"checkout={quote_plus(checkout_id)}" in response.url
- assert f"resultCode={message['resultCode']}" in response.url
- assert f"payment={quote_plus(payment_id)}" in response.url
- transactions = payment_adyen_for_checkout.transactions.all()
- assert transactions.count() == transaction_count + 2 # TO_CONFIRM, AUTH
-
- assert transactions.first().kind == TransactionKind.ACTION_TO_CONFIRM
- assert transactions.last().kind == TransactionKind.AUTH
- assert payment_adyen_for_checkout.order
- assert payment_adyen_for_checkout.checkout is None
-
-
[email protected]("saleor.payment.gateways.adyen.webhooks.api_call")
-def test_handle_additional_actions_order_already_created(
- api_call_mock, payment_adyen_for_order, adyen_plugin, order
-):
- # given
- plugin = adyen_plugin()
- channel_slug = plugin.channel.slug
- payment_adyen_for_order.to_confirm = True
- payment_adyen_for_order.extra_data = json.dumps(
- [{"payment_data": "test_data", "parameters": ["payload"]}]
- )
- payment_adyen_for_order.save(update_fields=["to_confirm", "extra_data"])
-
- payment_id = graphene.Node.to_global_id("Payment", payment_adyen_for_order.pk)
- checkout_id = graphene.Node.to_global_id("Checkout", "1")
-
- request_mock = mock.Mock()
- request_mock.GET = {"payment": payment_id, "checkout": "1"}
- request_mock.POST = {"payload": "test"}
-
- payment_details_mock = mock.Mock()
- message = {
- "pspReference": "11111",
- "resultCode": "Test",
- }
- api_call_mock.return_value.message = message
-
- # when
- response = handle_additional_actions(
- request_mock, payment_details_mock, channel_slug
- )
-
- # then
- payment_adyen_for_order.refresh_from_db()
- assert response.status_code == 302
- assert f"checkout={quote_plus(checkout_id)}" in response.url
- assert f"resultCode={message['resultCode']}" in response.url
- assert f"payment={quote_plus(payment_id)}" in response.url
-
- assert payment_adyen_for_order.order
- assert payment_adyen_for_order.checkout is None
-
-
- "custom_url",
- [
- "adyencheckout://your.package.name",
- "myiOSapp://path",
- "https://checkout.saleor.com/",
- ],
-)
[email protected]("saleor.payment.gateways.adyen.webhooks.api_call")
-def test_handle_additional_actions_handles_return_urls(
- api_call_mock, custom_url, payment_adyen_for_checkout, adyen_plugin
-):
- # given
- plugin = adyen_plugin()
- channel_slug = plugin.channel.slug
- payment_adyen_for_checkout.return_url = custom_url
- payment_adyen_for_checkout.to_confirm = True
- payment_adyen_for_checkout.extra_data = json.dumps(
- [{"payment_data": "test_data", "parameters": ["payload"]}]
- )
- payment_adyen_for_checkout.save(
- update_fields=["to_confirm", "extra_data", "return_url"]
- )
-
- checkout = payment_adyen_for_checkout.checkout
- payment_id = graphene.Node.to_global_id("Payment", payment_adyen_for_checkout.pk)
-
- request_mock = mock.Mock()
- request_mock.GET = {"payment": payment_id, "checkout": str(checkout.pk)}
- request_mock.POST = {"payload": "test"}
-
- payment_details_mock = mock.Mock()
- message = {
- "pspReference": "11111",
- "resultCode": "Test",
- }
- api_call_mock.return_value.message = message
-
- # when
- response = handle_additional_actions(
- request_mock, payment_details_mock, channel_slug
- )
-
- # then
- payment_adyen_for_checkout.refresh_from_db()
- assert response.status_code == 302
-
-
[email protected]("saleor.payment.gateways.adyen.webhooks.api_call")
-def test_handle_additional_actions_sets_psp_reference(
- api_call_mock, payment_adyen_for_checkout, adyen_plugin
-):
- # given
- plugin = adyen_plugin()
- channel_slug = plugin.channel.slug
- payment_adyen_for_checkout.to_confirm = True
- payment_adyen_for_checkout.extra_data = json.dumps(
- {"payment_data": "test_data", "parameters": ["payload"]}
- )
- payment_adyen_for_checkout.save(update_fields=["to_confirm", "extra_data"])
-
- checkout = payment_adyen_for_checkout.checkout
- payment_id = graphene.Node.to_global_id("Payment", payment_adyen_for_checkout.pk)
-
- request_mock = mock.Mock()
- request_mock.GET = {
- "payment": payment_id,
- "checkout": str(checkout.pk),
- "payload": "test",
- }
-
- expected_psp_reference = "psp-11111"
- payment_details_mock = mock.Mock()
- message = {
- "pspReference": expected_psp_reference,
- "resultCode": "authorised",
- }
- api_call_mock.return_value.message = message
-
- # when
- handle_additional_actions(request_mock, payment_details_mock, channel_slug)
-
- # then
- payment_adyen_for_checkout.refresh_from_db()
- assert payment_adyen_for_checkout.psp_reference == expected_psp_reference
-
-
[email protected]("saleor.payment.gateways.adyen.webhooks.api_call")
-def test_handle_additional_actions_get(
- api_call_mock, payment_adyen_for_checkout, adyen_plugin
-):
- # given
- plugin = adyen_plugin()
- channel_slug = plugin.channel.slug
- payment_adyen_for_checkout.to_confirm = True
- payment_adyen_for_checkout.extra_data = json.dumps(
- {"payment_data": "test_data", "parameters": ["payload"]}
- )
- payment_adyen_for_checkout.save(update_fields=["to_confirm", "extra_data"])
-
- transaction_count = payment_adyen_for_checkout.transactions.all().count()
-
- checkout = payment_adyen_for_checkout.checkout
- payment_id = graphene.Node.to_global_id("Payment", payment_adyen_for_checkout.pk)
- checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
-
- request_mock = mock.Mock()
- request_mock.GET = {
- "payment": payment_id,
- "checkout": str(checkout.pk),
- "payload": "test",
- }
-
- payment_details_mock = mock.Mock()
- message = {
- "pspReference": "11111",
- "resultCode": "Test",
- }
- api_call_mock.return_value.message = message
-
- # when
- response = handle_additional_actions(
- request_mock, payment_details_mock, channel_slug
- )
-
- # then
- payment_adyen_for_checkout.refresh_from_db()
- assert response.status_code == 302
- assert f"checkout={quote_plus(checkout_id)}" in response.url
- assert f"resultCode={message['resultCode']}" in response.url
- assert f"payment={quote_plus(payment_id)}" in response.url
- transactions = payment_adyen_for_checkout.transactions.all()
- assert transactions.count() == transaction_count + 2 # TO_CONFIRM, AUTH
- assert transactions.first().kind == TransactionKind.ACTION_TO_CONFIRM
- assert transactions.last().kind == TransactionKind.AUTH
- assert payment_adyen_for_checkout.order
- assert payment_adyen_for_checkout.checkout is None
-
-
[email protected]("saleor.payment.gateways.adyen.webhooks.api_call")
-def test_handle_additional_actions_with_adyen_partial_data(
- api_call_mock, payment_adyen_for_checkout, adyen_plugin
-):
- # given
- plugin = adyen_plugin()
- payment = payment_adyen_for_checkout
- channel_slug = plugin.channel.slug
- payment.to_confirm = True
- payment.extra_data = json.dumps(
- {"payment_data": "test_data", "parameters": ["payload"]}
- )
- payment.save(update_fields=["to_confirm", "extra_data"])
-
- transaction_count = payment.transactions.all().count()
-
- checkout = payment.checkout
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
-
- request_mock = mock.Mock()
- request_mock.GET = {
- "payment": payment_id,
- "checkout": str(checkout.pk),
- "payload": "test",
- }
-
- payment_details_mock = mock.Mock()
- message = {
- "additionalData": {
- "order-2-paymentMethod": "visa",
- "threeds2.cardEnrolled": "false",
- "order-2-pspReference": "861643021198177D",
- "order-2-paymentAmount": "GBP 16.29",
- "recurringProcessingModel": "Subscription",
- "paymentMethod": "visa",
- "order-1-pspReference": "861643021155073F",
- "order-1-paymentAmount": "GBP 14.71",
- "order-1-paymentMethod": "givex",
- },
- "pspReference": "861643021198177D",
- "resultCode": "Authorised",
- "merchantReference": "UGF5bWVudDoyNw==",
- "paymentMethod": "visa",
- "shopperLocale": "en_GB",
- }
- api_call_mock.return_value.message = message
-
- # when
- response = handle_additional_actions(
- request_mock, payment_details_mock, channel_slug
- )
-
- # then
- payment.refresh_from_db()
- assert response.status_code == 302
- assert f"checkout={quote_plus(checkout_id)}" in response.url
- assert f"resultCode={message['resultCode']}" in response.url
- assert f"payment={quote_plus(payment_id)}" in response.url
- transactions = payment.transactions.all()
- assert transactions.count() == transaction_count + 2 # TO_CONFIRM, AUTH
- assert transactions.first().kind == TransactionKind.ACTION_TO_CONFIRM
- assert transactions.last().kind == TransactionKind.AUTH
- assert payment.order
- assert payment.checkout is None
-
- external_events = payment.order.events.filter(
- type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
- )
- assert external_events.count() == 1
-
- external_event = external_events.first()
- event_message = external_event.parameters["message"]
- assert "Partial payment" in event_message
- assert "GBP 16.29" in event_message
- assert "GBP 14.71" in event_message
- assert "861643021198177D" in event_message
- assert "861643021155073F" in event_message
- assert "givex" in event_message
- assert "visa" in event_message
-
- partial_payments = list(payment.order.payments.exclude(id=payment.id))
- assert len(partial_payments) == 2
- assert all(payment.is_active is False for payment in partial_payments)
- assert all(payment.partial is True for payment in partial_payments)
- assert all(payment.is_active is False for payment in partial_payments)
- assert any(payment.total == Decimal("16.29") for payment in partial_payments)
- assert any(payment.total == Decimal("14.71") for payment in partial_payments)
- assert any(
- payment.psp_reference == "861643021198177D" for payment in partial_payments
- )
- assert any(
- payment.psp_reference == "861643021155073F" for payment in partial_payments
- )
-
-
[email protected]("saleor.payment.gateways.adyen.webhooks.api_call")
-def test_handle_additional_actions_with_adyen_partial_data_without_amount(
- api_call_mock, payment_adyen_for_checkout, adyen_plugin
-):
- # given
- plugin = adyen_plugin()
- payment = payment_adyen_for_checkout
- channel_slug = plugin.channel.slug
- payment.to_confirm = True
- payment.extra_data = json.dumps(
- {"payment_data": "test_data", "parameters": ["payload"]}
- )
- payment.save(update_fields=["to_confirm", "extra_data"])
-
- transaction_count = payment.transactions.all().count()
-
- checkout = payment.checkout
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
-
- request_mock = mock.Mock()
- request_mock.GET = {
- "payment": payment_id,
- "checkout": str(checkout.pk),
- "payload": "test",
- }
-
- payment_details_mock = mock.Mock()
- message = {
- "additionalData": {
- "order-2-paymentMethod": "visa",
- "threeds2.cardEnrolled": "false",
- "order-2-pspReference": "861643021198177D",
- "recurringProcessingModel": "Subscription",
- "paymentMethod": "visa",
- "order-1-pspReference": "861643021155073F",
- "order-1-paymentAmount": "GBP 14.71",
- "order-1-paymentMethod": "givex",
- },
- "pspReference": "861643021198177D",
- "resultCode": "Authorised",
- "merchantReference": "UGF5bWVudDoyNw==",
- "paymentMethod": "visa",
- "shopperLocale": "en_GB",
- }
- api_call_mock.return_value.message = message
-
- # when
- response = handle_additional_actions(
- request_mock, payment_details_mock, channel_slug
- )
-
- # then
- payment.refresh_from_db()
- assert response.status_code == 302
- assert f"checkout={quote_plus(checkout_id)}" in response.url
- assert f"resultCode={message['resultCode']}" in response.url
- assert f"payment={quote_plus(payment_id)}" in response.url
- transactions = payment.transactions.all()
- assert transactions.count() == transaction_count + 2 # TO_CONFIRM, AUTH
- assert transactions.first().kind == TransactionKind.ACTION_TO_CONFIRM
- assert transactions.last().kind == TransactionKind.AUTH
- assert payment.order
- assert payment.checkout is None
-
- external_events = payment.order.events.filter(
- type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
- )
- assert external_events.count() == 1
-
- external_event = external_events.first()
- event_message = external_event.parameters["message"]
- assert "Partial payment" in event_message
- assert "GBP 65.29" in event_message
- assert "GBP 14.71" in event_message
- assert "861643021198177D" in event_message
- assert "861643021155073F" in event_message
- assert "givex" in event_message
- assert "visa" in event_message
-
- partial_payments = list(payment.order.payments.exclude(id=payment.id))
- assert len(partial_payments) == 2
- assert all(payment.is_active is False for payment in partial_payments)
- assert all(payment.partial is True for payment in partial_payments)
- assert all(payment.is_active is False for payment in partial_payments)
- assert any(payment.total == Decimal("65.29") for payment in partial_payments)
- assert any(payment.total == Decimal("14.71") for payment in partial_payments)
- assert any(
- payment.psp_reference == "861643021198177D" for payment in partial_payments
- )
- assert any(
- payment.psp_reference == "861643021155073F" for payment in partial_payments
- )
-
-
[email protected]("saleor.payment.gateways.adyen.webhooks.api_call")
-def test_handle_additional_actions_for_ideal(
- api_call_mock, payment_adyen_for_checkout, adyen_plugin
-):
- # given
- plugin = adyen_plugin()
- channel_slug = plugin.channel.slug
- payment_adyen_for_checkout.extra_data = json.dumps(
- {"payment_data": "extra_data", "parameters": ["payload"]}
- )
- payment_adyen_for_checkout.save(update_fields=["extra_data"])
-
- transaction_count = payment_adyen_for_checkout.transactions.all().count()
-
- checkout = payment_adyen_for_checkout.checkout
- payment_id = graphene.Node.to_global_id("Payment", payment_adyen_for_checkout.pk)
- checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
-
- request_mock = mock.Mock()
- request_mock.GET = {
- "payment": payment_id,
- "checkout": str(checkout.pk),
- "payload": "test",
- }
-
- payment_details_mock = mock.Mock()
- message = {
- "additionalData": {
- "bankAccount.ownerName": "A. Klaassen",
- "bankAccount.iban": "NL13TEST0123456789",
- },
- "pspReference": "861638465362046G",
- "resultCode": "Authorised",
- "merchantReference": payment_id,
- "paymentMethod": "ideal",
- "shopperLocale": "en_GB",
- }
-
- api_call_mock.return_value.message = message
-
- # when
- response = handle_additional_actions(
- request_mock, payment_details_mock, channel_slug
- )
-
- # then
- payment_adyen_for_checkout.refresh_from_db()
- assert response.status_code == 302
- assert f"checkout={quote_plus(checkout_id)}" in response.url
- assert f"resultCode={message['resultCode']}" in response.url
- assert f"payment={quote_plus(payment_id)}" in response.url
- transactions = payment_adyen_for_checkout.transactions.all()
- assert transactions.count() == transaction_count + 2 # TO_CONFIRM, CAPTURE
- assert transactions.first().kind == TransactionKind.ACTION_TO_CONFIRM
- assert transactions.last().kind == TransactionKind.CAPTURE
- assert payment_adyen_for_checkout.order
- assert payment_adyen_for_checkout.checkout is None
-
-
-def test_handle_additional_actions_more_action_required(payment_adyen_for_checkout):
- # given
- payment_adyen_for_checkout.extra_data = json.dumps(
- {"payment_data": "test_data", "parameters": ["payload"]}
- )
- payment_adyen_for_checkout.save(update_fields=["extra_data"])
-
- checkout = payment_adyen_for_checkout.checkout
- payment_id = graphene.Node.to_global_id("Payment", payment_adyen_for_checkout.pk)
- checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
-
- request_mock = mock.Mock()
- request_mock.GET = {"payment": payment_id, "checkout": str(checkout.pk)}
- request_mock.POST = {"payload": "test"}
-
- payment_details_mock = mock.Mock()
- message = {
- "resultCode": "Pending",
- "action": {
- "method": "GET",
- "paymentData": "123",
- "paymentMethodType": "ideal",
- "type": "redirect",
- "url": "https://test.adyen.com/hpp/redirectIdeal.shtml?brandCode=ideal",
- },
- }
- payment_details_mock.return_value.message = message
-
- # when
- response = handle_additional_actions(request_mock, payment_details_mock, "channel")
-
- # then
- assert response.status_code == 302
- assert f"resultCode={message['resultCode']}" in response.url
- assert f"method={message['action']['method']}" in response.url
- assert f"paymentData={message['action']['paymentData']}" in response.url
- assert f"paymentMethodType={message['action']['paymentMethodType']}" in response.url
- assert f"type={message['action']['type']}" in response.url
- assert f"checkout={quote_plus(checkout_id)}" in response.url
- assert f"payment={quote_plus(payment_id)}" in response.url
-
- transaction = payment_adyen_for_checkout.transactions.last()
- assert transaction.kind == TransactionKind.ACTION_TO_CONFIRM
- assert transaction.action_required is True
- assert payment_adyen_for_checkout.order is None
- assert payment_adyen_for_checkout.checkout
-
-
-def test_handle_additional_actions_payment_does_not_exist(payment_adyen_for_checkout):
- # given
- payment_adyen_for_checkout.extra_data = json.dumps(
- {"payment_data": "test_data", "parameters": ["payload"]}
- )
- payment_adyen_for_checkout.save(update_fields=["extra_data"])
-
- payment_id = graphene.Node.to_global_id("Payment", payment_adyen_for_checkout.pk)
- request_mock = mock.Mock()
- request_mock.GET = {
- "payment": payment_id,
- "checkout": payment_adyen_for_checkout.checkout.pk,
- }
- request_mock.POST = {"payload": "test"}
-
- payment_details_mock = mock.Mock()
- payment_details_mock.return_value.message = {
- "resultCode": "Test",
- }
-
- payment_adyen_for_checkout.delete()
-
- # when
- response = handle_additional_actions(request_mock, payment_details_mock, "channel")
-
- # then
- assert response.status_code == 404
- assert response.content.decode() == ERROR_MSG_MISSING_PAYMENT
-
-
-def test_handle_additional_actions_payment_lack_of_return_url(
- payment_adyen_for_checkout,
-):
- # given
- payment_adyen_for_checkout.extra_data = json.dumps(
- {"payment_data": "test_data", "parameters": ["payload"]}
- )
- payment_adyen_for_checkout.return_url = None
- payment_adyen_for_checkout.save(update_fields=["extra_data", "return_url"])
-
- payment_id = graphene.Node.to_global_id("Payment", payment_adyen_for_checkout.pk)
- request_mock = mock.Mock()
- request_mock.GET = {
- "payment": payment_id,
- "checkout": str(payment_adyen_for_checkout.checkout.pk),
- }
- request_mock.POST = {"payload": "test"}
-
- payment_details_mock = mock.Mock()
- payment_details_mock.return_value.message = {
- "resultCode": "Test",
- }
-
- # when
- response = handle_additional_actions(request_mock, payment_details_mock, "channel")
-
- # then
- assert response.status_code == 404
- assert (
- response.content.decode()
- == "Cannot perform payment. Lack of data about returnUrl."
- )
-
-
-def test_handle_additional_actions_no_payment_id_in_get(payment_adyen_for_checkout):
- # given
- payment_adyen_for_checkout.extra_data = json.dumps(
- {"payment_data": "test_data", "parameters": ["payload"]}
- )
- payment_adyen_for_checkout.save(update_fields=["extra_data"])
-
- request_mock = mock.Mock()
- request_mock.GET = {}
- request_mock.POST = {"payload": "test"}
-
- payment_details_mock = mock.Mock()
- message = {
- "resultCode": "Test",
- }
- payment_details_mock.return_value.message = message
-
- # when
- response = handle_additional_actions(request_mock, payment_details_mock, "channel")
-
- # then
- assert response.status_code == 404
-
-
-def test_handle_additional_actions_checkout_not_related_to_payment(
- payment_adyen_for_checkout,
-):
- # given
- payment_adyen_for_checkout.extra_data = json.dumps(
- {"payment_data": "test_data", "parameters": ["payload"]}
- )
- payment_adyen_for_checkout.save(update_fields=["extra_data"])
-
- payment_id = graphene.Node.to_global_id("Payment", payment_adyen_for_checkout.pk)
-
- request_mock = mock.Mock()
- request_mock.GET = {"payment": payment_id, "checkout": uuid.uuid4()}
- request_mock.POST = {"payload": "test"}
-
- payment_details_mock = mock.Mock()
- message = {
- "resultCode": "Test",
- }
- payment_details_mock.return_value.message = message
-
- # when
- response = handle_additional_actions(request_mock, payment_details_mock, "channel")
-
- # then
- assert response.status_code == 404
- assert response.content.decode() == ERROR_MSG_MISSING_CHECKOUT
-
-
-def test_handle_additional_actions_payment_does_not_have_checkout(
- payment_adyen_for_checkout,
-):
- # given
- payment_adyen_for_checkout.extra_data = json.dumps(
- {"payment_data": "test_data", "parameters": ["payload"]}
- )
- payment_adyen_for_checkout.checkout = None
- payment_adyen_for_checkout.save()
-
- payment_id = graphene.Node.to_global_id("Payment", payment_adyen_for_checkout.pk)
-
- request_mock = mock.Mock()
- request_mock.GET = {"payment": payment_id, "checkout": uuid.uuid4()}
- request_mock.POST = {"payload": "test"}
-
- payment_details_mock = mock.Mock()
- message = {
- "resultCode": "Test",
- }
- payment_details_mock.return_value.message = message
-
- # when
- response = handle_additional_actions(request_mock, payment_details_mock, "channel")
-
- # then
- assert response.status_code == 404
- assert response.content.decode() == ERROR_MSG_MISSING_CHECKOUT
-
-
[email protected]("saleor.payment.gateways.adyen.webhooks.api_call")
-def test_handle_additional_actions_api_call_error(
- api_call_mock,
- payment_adyen_for_checkout,
-):
- # given
- payment_adyen_for_checkout.extra_data = json.dumps(
- {"payment_data": "test_data", "parameters": ["payload"]}
- )
- payment_adyen_for_checkout.save()
-
- payment_id = graphene.Node.to_global_id("Payment", payment_adyen_for_checkout.pk)
-
- error_message = "Test error"
- api_call_mock.side_effect = PaymentError(error_message)
-
- request_mock = mock.Mock()
- request_mock.GET = {
- "payment": payment_id,
- "checkout": str(payment_adyen_for_checkout.checkout.pk),
- }
- request_mock.POST = {"payload": "test"}
-
- payment_details_mock = mock.Mock()
- message = {
- "resultCode": "Test",
- }
- payment_details_mock.return_value.message = message
-
- # when
- response = handle_additional_actions(request_mock, payment_details_mock, "channel")
-
- # then
- assert response.status_code == 400
- assert response.content.decode() == error_message
-
-
-def test_handle_additional_actions_payment_not_active(payment_adyen_for_checkout):
- # given
- payment_adyen_for_checkout.extra_data = json.dumps(
- {"payment_data": "test_data", "parameters": ["payload"]}
- )
- payment_adyen_for_checkout.is_active = False
- payment_adyen_for_checkout.save(update_fields=["extra_data", "is_active"])
-
- checkout = payment_adyen_for_checkout.checkout
- payment_id = graphene.Node.to_global_id("Payment", payment_adyen_for_checkout.pk)
-
- request_mock = mock.Mock()
- request_mock.GET = {"payment": payment_id, "checkout": checkout.pk}
- request_mock.POST = {"payload": "test"}
-
- payment_details_mock = mock.Mock()
- message = {
- "resultCode": "Test",
- }
- payment_details_mock.return_value.message = message
-
- # when
- response = handle_additional_actions(request_mock, payment_details_mock, "channel")
-
- # then
- assert response.status_code == 404
- assert response.content.decode() == ERROR_MSG_MISSING_PAYMENT
-
-
-def test_handle_additional_actions_payment_with_no_adyen_gateway(
- payment_adyen_for_checkout,
-):
- # given
- payment_adyen_for_checkout.extra_data = json.dumps(
- {"payment_data": "test_data", "parameters": ["payload"]}
- )
- payment_adyen_for_checkout.gateway = "test"
- payment_adyen_for_checkout.save(update_fields=["extra_data", "gateway"])
-
- checkout = payment_adyen_for_checkout.checkout
- payment_id = graphene.Node.to_global_id("Payment", payment_adyen_for_checkout.pk)
-
- request_mock = mock.Mock()
- request_mock.GET = {"payment": payment_id, "checkout": checkout.pk}
- request_mock.POST = {"payload": "test"}
-
- payment_details_mock = mock.Mock()
- message = {
- "resultCode": "Test",
- }
- payment_details_mock.return_value.message = message
-
- # when
- response = handle_additional_actions(request_mock, payment_details_mock, "channel")
-
- # then
- assert response.status_code == 404
- assert response.content.decode() == ERROR_MSG_MISSING_PAYMENT
-
-
[email protected]("saleor.payment.gateways.adyen.webhooks.api_call")
-def test_handle_additional_actions_lack_of_parameter_in_request(
- api_call_mock, payment_adyen_for_checkout
-):
- # given
- payment_adyen_for_checkout.extra_data = json.dumps(
- {"payment_data": "test_data", "parameters": ["payload", "second_param"]}
- )
- payment_adyen_for_checkout.save(update_fields=["extra_data"])
-
- checkout = payment_adyen_for_checkout.checkout
- payment_id = graphene.Node.to_global_id("Payment", payment_adyen_for_checkout.pk)
-
- request_mock = mock.Mock()
- request_mock.GET = {"payment": payment_id, "checkout": str(checkout.pk)}
- request_mock.POST = {"payload": "test"}
-
- payment_details_mock = mock.Mock()
- message = {
- "resultCode": "Test",
- }
- api_call_mock.return_value.message = message
-
- # when
- response = handle_additional_actions(request_mock, payment_details_mock, "channel")
-
- # then
- payment_adyen_for_checkout.refresh_from_db()
- assert response.status_code == 400
- assert (
- response.content.decode()
- == "Cannot perform payment. Lack of required parameters in request."
- )
-
-
[email protected]("saleor.payment.gateways.adyen.webhooks.payment_refund_or_void")
[email protected]("saleor.payment.gateways.adyen.webhooks.api_call")
-def test_handle_additional_actions_unavailable_variants(
- api_call_mock, payment_refund_or_void, payment_adyen_for_checkout, adyen_plugin
-):
- # given
- plugin = adyen_plugin()
-
- channel_slug = plugin.channel.slug
- payment_adyen_for_checkout.to_confirm = True
- payment_adyen_for_checkout.extra_data = json.dumps(
- [{"payment_data": "test_data", "parameters": ["payload"]}]
- )
- payment_adyen_for_checkout.save(update_fields=["to_confirm", "extra_data"])
-
- transaction_count = payment_adyen_for_checkout.transactions.all().count()
-
- checkout = payment_adyen_for_checkout.checkout
- payment_id = graphene.Node.to_global_id("Payment", payment_adyen_for_checkout.pk)
- checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
-
- # make the checkout line unavailable
- checkout.lines.first().variant.channel_listings.filter(
- channel=checkout.channel
- ).delete()
-
- request_mock = mock.Mock()
- request_mock.GET = {"payment": payment_id, "checkout": str(checkout.pk)}
- request_mock.POST = {"payload": "test"}
-
- payment_details_mock = mock.Mock()
- message = {
- "pspReference": "11111",
- "resultCode": "Test",
- }
- api_call_mock.return_value.message = message
-
- # when
- response = handle_additional_actions(
- request_mock, payment_details_mock, channel_slug
- )
-
- # then
- payment_adyen_for_checkout.refresh_from_db()
- assert response.status_code == 302
- assert f"checkout={quote_plus(checkout_id)}" in response.url
- assert f"resultCode={message['resultCode']}" in response.url
- assert f"payment={quote_plus(payment_id)}" in response.url
- transactions = payment_adyen_for_checkout.transactions.all()
- assert transactions.count() == transaction_count + 2 # TO_CONFIRM, AUTH
-
- assert transactions.first().kind == TransactionKind.ACTION_TO_CONFIRM
- assert transactions.last().kind == TransactionKind.AUTH
- assert payment_adyen_for_checkout.order is None
- assert payment_adyen_for_checkout.checkout
- payment_refund_or_void.assert_called_once_with(
- payment_adyen_for_checkout, mock.ANY, checkout.channel.slug
- )
diff --git a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_api_response.py b/saleor/payment/gateways/adyen/tests/webhooks/test_handle_api_response.py
deleted file mode 100644
index 241150adf1..0000000000
--- a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_api_response.py
+++ /dev/null
@@ -1,208 +0,0 @@
-from unittest.mock import patch
-
-from Adyen.client import AdyenResult
-from django.core.exceptions import ValidationError
-from django.utils import timezone
-
-from ......payment import ChargeStatus
-from ......payment.gateways.adyen.webhooks import handle_api_response
-
-
-@patch("saleor.payment.gateway.refund")
-@patch("saleor.payment.gateway.void")
-def test_handle_api_response_auto_capture_order_created_can_refund(
- void_mock, refund_mock, payment_adyen_for_checkout, adyen_plugin
-):
- payment_adyen_for_checkout.to_confirm = True
- payment_adyen_for_checkout.save(update_fields=["to_confirm"])
-
- plugin = adyen_plugin(adyen_auto_capture=True)
-
- adyen_response = AdyenResult(
- {
- "additionalData": {"paymentMethod": "visa"},
- "pspReference": "882635241694695D",
- "resultCode": "Authorised",
- "amount": {"currency": "USD", "value": 4211},
- "merchantReference": "UGF5bWVudDoxMDU=",
- }
- )
-
- handle_api_response(
- payment_adyen_for_checkout,
- payment_adyen_for_checkout.checkout,
- adyen_response,
- plugin.channel.slug,
- )
-
- payment_adyen_for_checkout.refresh_from_db()
-
- assert payment_adyen_for_checkout.charge_status == ChargeStatus.FULLY_CHARGED
- assert payment_adyen_for_checkout.order
- assert payment_adyen_for_checkout.can_refund()
- assert not payment_adyen_for_checkout.can_void()
- assert not refund_mock.called
- assert not void_mock.called
-
-
-@patch("saleor.payment.gateway.refund")
-@patch("saleor.payment.gateway.void")
-def test_handle_api_response_auto_capture_false_order_created_can_void(
- void_mock, refund_mock, payment_adyen_for_checkout, adyen_plugin
-):
- payment_adyen_for_checkout.to_confirm = True
- payment_adyen_for_checkout.save(update_fields=["to_confirm"])
-
- plugin = adyen_plugin()
-
- adyen_response = AdyenResult(
- {
- "additionalData": {"paymentMethod": "visa"},
- "pspReference": "882635241694695D",
- "resultCode": "Authorised",
- "amount": {"currency": "USD", "value": 4211},
- "merchantReference": "UGF5bWVudDoxMDU=",
- }
- )
-
- handle_api_response(
- payment_adyen_for_checkout,
- payment_adyen_for_checkout.checkout,
- adyen_response,
- plugin.channel.slug,
- )
-
- payment_adyen_for_checkout.refresh_from_db()
-
- assert payment_adyen_for_checkout.charge_status == ChargeStatus.NOT_CHARGED
- assert payment_adyen_for_checkout.order
- assert payment_adyen_for_checkout.can_void()
- assert not payment_adyen_for_checkout.can_refund()
- assert not refund_mock.called
- assert not void_mock.called
-
-
-@patch("saleor.payment.gateway.void")
-@patch("saleor.payment.gateway.refund")
-@patch("saleor.checkout.complete_checkout._get_order_data")
-def test_handle_api_response_auto_capture_false_cannot_create_order_void_payment(
- order_data_mock, refund_mock, void_mock, payment_adyen_for_checkout, adyen_plugin
-):
- order_data_mock.side_effect = ValidationError("Test error")
- payment_adyen_for_checkout.to_confirm = True
- payment_adyen_for_checkout.save(update_fields=["to_confirm"])
-
- plugin = adyen_plugin()
-
- adyen_response = AdyenResult(
- {
- "additionalData": {"paymentMethod": "visa"},
- "pspReference": "882635241694695D",
- "resultCode": "Authorised",
- "amount": {"currency": "USD", "value": 4211},
- "merchantReference": "UGF5bWVudDoxMDU=",
- }
- )
-
- handle_api_response(
- payment_adyen_for_checkout,
- payment_adyen_for_checkout.checkout,
- adyen_response,
- plugin.channel.slug,
- )
-
- payment_adyen_for_checkout.refresh_from_db()
-
- assert payment_adyen_for_checkout.charge_status == ChargeStatus.NOT_CHARGED
- assert not payment_adyen_for_checkout.order
-
- assert not payment_adyen_for_checkout.can_refund()
- assert not refund_mock.called
-
- assert payment_adyen_for_checkout.can_void()
- assert void_mock.call_count == 1
-
-
-@patch("saleor.payment.gateway.void")
-@patch("saleor.payment.gateway.refund")
-@patch("saleor.checkout.complete_checkout._get_order_data")
-def test_handle_api_response_auto_capture_cannot_create_order_refund_payment(
- order_data_mock, refund_mock, void_mock, payment_adyen_for_checkout, adyen_plugin
-):
- order_data_mock.side_effect = ValidationError("Test error")
- payment_adyen_for_checkout.to_confirm = True
- payment_adyen_for_checkout.save(update_fields=["to_confirm"])
-
- plugin = adyen_plugin(adyen_auto_capture=True)
-
- adyen_response = AdyenResult(
- {
- "additionalData": {"paymentMethod": "visa"},
- "pspReference": "882635241694695D",
- "resultCode": "Authorised",
- "amount": {"currency": "USD", "value": 4211},
- "merchantReference": "UGF5bWVudDoxMDU=",
- }
- )
-
- handle_api_response(
- payment_adyen_for_checkout,
- payment_adyen_for_checkout.checkout,
- adyen_response,
- plugin.channel.slug,
- )
-
- payment_adyen_for_checkout.refresh_from_db()
-
- assert payment_adyen_for_checkout.charge_status == ChargeStatus.FULLY_CHARGED
- assert not payment_adyen_for_checkout.order
-
- assert payment_adyen_for_checkout.can_refund()
- assert refund_mock.call_count == 1
-
- assert not payment_adyen_for_checkout.can_void()
- assert not void_mock.called
-
-
-@patch("saleor.payment.gateway.void")
-@patch("saleor.payment.gateway.refund")
-def test_handle_api_response_auto_capture_cannot_create_order_variant_deleted(
- refund_mock, void_mock, payment_adyen_for_checkout, adyen_plugin
-):
- payment_adyen_for_checkout.to_confirm = True
- payment_adyen_for_checkout.save(update_fields=["to_confirm"])
-
- checkout = payment_adyen_for_checkout.checkout
- checkout.lines.first().delete()
- checkout.price_expiration = timezone.now()
- checkout.save(update_fields=["price_expiration"])
-
- plugin = adyen_plugin(adyen_auto_capture=True)
-
- adyen_response = AdyenResult(
- {
- "additionalData": {"paymentMethod": "visa"},
- "pspReference": "882635241694695D",
- "resultCode": "Authorised",
- "amount": {"currency": "USD", "value": payment_adyen_for_checkout.total},
- "merchantReference": "UGF5bWVudDoxMDU=",
- }
- )
-
- handle_api_response(
- payment_adyen_for_checkout,
- payment_adyen_for_checkout.checkout,
- adyen_response,
- plugin.channel.slug,
- )
-
- payment_adyen_for_checkout.refresh_from_db()
-
- assert payment_adyen_for_checkout.charge_status == ChargeStatus.FULLY_CHARGED
- assert not payment_adyen_for_checkout.order
-
- assert payment_adyen_for_checkout.can_refund()
- assert refund_mock.call_count == 1
-
- assert not payment_adyen_for_checkout.can_void()
- assert not void_mock.called
diff --git a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py b/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py
deleted file mode 100644
index 1497ab709b..0000000000
--- a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py
+++ /dev/null
@@ -1,2245 +0,0 @@
-import logging
-from decimal import Decimal
-from unittest import mock
-from unittest.mock import MagicMock, patch
-
-import graphene
-import pytest
-from django.core.exceptions import ValidationError
-from django.utils import timezone
-
-from ......checkout import calculations
-from ......checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-from ......order import OrderEvents, OrderStatus
-from ......plugins.manager import get_plugins_manager
-from ......tests import race_condition
-from ......warehouse.models import Stock
-from ..... import ChargeStatus, TransactionKind
-from .....models import Transaction
-from .....utils import price_to_minor_unit, update_payment_charge_status
-from ...webhooks import (
- confirm_payment_and_set_back_to_confirm,
- create_new_transaction,
- handle_authorization,
- handle_cancel_or_refund,
- handle_cancellation,
- handle_capture,
- handle_failed_capture,
- handle_failed_refund,
- handle_not_created_order,
- handle_order_closed,
- handle_order_opened,
- handle_pending,
- handle_refund,
- handle_reversed_refund,
- webhook_not_implemented,
-)
-
-logger = logging.getLogger(__name__)
-
-
-def test_handle_authorization_for_order(
- notification, adyen_plugin, payment_adyen_for_order
-):
- payment = payment_adyen_for_order
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
- handle_authorization(notification, config)
-
- assert payment.transactions.count() == 2
- transaction = payment.transactions.last()
- assert transaction.is_success is True
- assert transaction.kind == TransactionKind.AUTH
- external_events = payment.order.events.filter(
- type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
- )
- assert external_events.count() == 1
-
-
-def test_handle_authorization_for_order_invalid_payment_id(
- notification, adyen_plugin, payment_adyen_for_order, caplog
-):
- payment = payment_adyen_for_order
- invalid_reference = "test invalid reference"
- notification = notification(
- merchant_reference=invalid_reference,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
- transaction_count = payment.transactions.count()
-
- caplog.set_level(logging.WARNING)
-
- handle_authorization(notification, config)
-
- payment.refresh_from_db()
- assert payment.transactions.count() == transaction_count
- assert f"Unable to decode the payment ID {invalid_reference}." in caplog.text
-
-
-def test_handle_multiple_authorization_notification(
- notification, adyen_plugin, payment_adyen_for_order
-):
- payment = payment_adyen_for_order
- payment.charge_status = ChargeStatus.NOT_CHARGED
- payment.save()
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- first_notification = notification(
- merchant_reference=payment_id,
- success="false",
- psp_reference="wrong",
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin(adyen_auto_capture=True).config
- handle_authorization(first_notification, config)
-
- payment.refresh_from_db()
- assert payment.charge_status == ChargeStatus.NOT_CHARGED
- capture_transaction = payment.transactions.get(kind=TransactionKind.CAPTURE)
- assert capture_transaction.is_success is False
- external_events = payment.order.events.filter(
- type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
- )
- assert external_events.count() == 1
-
- second_notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- handle_authorization(second_notification, config)
- payment.refresh_from_db()
- assert payment.charge_status == ChargeStatus.FULLY_CHARGED
- assert payment.captured_amount == payment.total
- capture_transaction = payment.transactions.filter(
- kind=TransactionKind.CAPTURE
- ).last()
- assert capture_transaction.is_success is True
- external_events = payment.order.events.filter(
- type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
- )
- assert external_events.count() == 2
-
-
-def test_handle_authorization_for_pending_order(
- notification, adyen_plugin, payment_adyen_for_order
-):
- payment = payment_adyen_for_order
- payment.charge_status = ChargeStatus.PENDING
- payment.save()
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin(adyen_auto_capture=True).config
- handle_authorization(notification, config)
-
- assert payment.transactions.count() == 2
- transaction = payment.transactions.last()
- assert transaction.is_success is True
- assert transaction.kind == TransactionKind.CAPTURE
- payment.refresh_from_db()
- assert payment.charge_status == ChargeStatus.FULLY_CHARGED
- external_events = payment.order.events.filter(
- type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
- )
- assert external_events.count() == 1
-
-
-def test_handle_authorization_sets_psp_reference(
- notification,
- adyen_plugin,
- payment_adyen_for_checkout,
- address,
-):
- # given
- checkout = payment_adyen_for_checkout.checkout
- checkout.shipping_address = address
-
- checkout.billing_address = address
- checkout.save()
-
- payment = payment_adyen_for_checkout
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
- )
- payment.is_active = True
- payment.order = None
- payment.total = total.gross.amount
- payment.currency = total.gross.currency
- payment.to_confirm = True
- payment.save()
-
- expected_psp_reference = "psp-123"
-
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- psp_reference=expected_psp_reference,
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
-
- # when
- handle_authorization(notification, config)
-
- # then
- payment.refresh_from_db()
- assert payment.psp_reference == expected_psp_reference
-
-
-def test_handle_authorization_for_checkout(
- notification,
- adyen_plugin,
- payment_adyen_for_checkout,
- address,
-):
- checkout = payment_adyen_for_checkout.checkout
- checkout.shipping_address = address
-
- checkout.billing_address = address
- checkout.save()
- checkout_token = str(checkout.token)
-
- payment = payment_adyen_for_checkout
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
- )
- payment.is_active = True
- payment.order = None
- payment.total = total.gross.amount
- payment.currency = total.gross.currency
- payment.to_confirm = True
- payment.save()
-
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
- handle_authorization(notification, config)
-
- payment.refresh_from_db()
- assert payment.transactions.count() == 2
- transaction = payment.transactions.exclude(
- kind=TransactionKind.ACTION_TO_CONFIRM
- ).get()
- assert transaction.is_success is True
- assert transaction.kind == TransactionKind.AUTH
- assert payment.checkout is None
- assert payment.order
- assert payment.order.checkout_token == checkout_token
- external_events = payment.order.events.filter(
- type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
- )
- assert external_events.count() == 1
-
-
-def test_handle_authorization_for_checkout_partial_payment(
- notification,
- adyen_plugin,
- payment_adyen_for_checkout,
- address,
-):
- checkout = payment_adyen_for_checkout.checkout
- checkout.shipping_address = address
-
- checkout.billing_address = address
- checkout.save()
-
- payment = payment_adyen_for_checkout
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
- )
- payment.is_active = True
- payment.order = None
- payment.total = total.gross.amount
- payment.currency = total.gross.currency
- payment.to_confirm = True
- payment.save()
-
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total - 5, payment.currency),
- )
- config = adyen_plugin().config
- handle_authorization(notification, config)
-
- payment.refresh_from_db()
- assert payment.transactions.count() == 0
- assert payment.checkout
- assert not payment.order
-
-
[email protected]("saleor.payment.gateways.adyen.plugin.call_refund")
-def test_handle_authorization_for_checkout_out_of_stock_after_payment(
- mock_refund,
- notification,
- adyen_plugin,
- payment_adyen_for_checkout,
- address,
-):
- refund_response = {"pspReference": "refund-psp"}
- mock_refund_response = MagicMock()
- mock_refund.return_value = mock_refund_response
- mock_refund_response.message = refund_response
-
- checkout = payment_adyen_for_checkout.checkout
- checkout.shipping_address = address
-
- checkout.billing_address = address
- checkout.save()
-
- payment = payment_adyen_for_checkout
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
- )
- payment.is_active = True
- payment.order = None
- payment.total = total.gross.amount
- payment.currency = total.gross.currency
- payment.to_confirm = True
- payment.save()
-
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- psp_reference="reference",
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin(adyen_auto_capture=True).config
-
- # when
- def call_after_finalizing_payment(*args, **kwargs):
- Stock.objects.all().update(quantity=0)
-
- with race_condition.RunBefore(
- "saleor.checkout.complete_checkout._create_order",
- call_after_finalizing_payment,
- ):
- handle_authorization(notification, config)
-
- # then
- payment.refresh_from_db()
- assert not payment.order
- assert payment.checkout
- assert (
- payment.transactions.filter(
- kind__in=[
- TransactionKind.ACTION_TO_CONFIRM,
- TransactionKind.CAPTURE,
- TransactionKind.REFUND_ONGOING,
- ]
- ).count()
- == 3
- )
-
-
-def test_handle_authorization_for_checkout_that_cannot_be_finalized(
- notification,
- adyen_plugin,
- payment_adyen_for_checkout,
- address,
-):
- # given
- checkout = payment_adyen_for_checkout.checkout
- checkout.shipping_address = address
-
- checkout.billing_address = address
- checkout.save()
-
- payment = payment_adyen_for_checkout
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
- )
- payment.is_active = True
- payment.order = None
- payment.total = total.gross.amount
- payment.currency = total.gross.currency
- payment.to_confirm = True
- payment.save()
-
- payment.transactions.create(
- token="reference",
- kind=TransactionKind.CAPTURE,
- is_success=True,
- action_required=False,
- currency=payment.currency,
- amount=payment.total,
- gateway_response={},
- )
- payment.transactions.create(
- token="refund-reference",
- is_success=True,
- kind=TransactionKind.REFUND_ONGOING,
- action_required=False,
- currency=payment.currency,
- amount=payment.total,
- gateway_response={},
- )
-
- checkout.lines.first().delete()
-
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- psp_reference="reference",
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin(adyen_auto_capture=True).config
-
- # when
- handle_authorization(notification, config)
-
- # then
- payment.refresh_from_db()
- assert not payment.order
- assert payment.checkout
- assert payment.transactions.count() == 2
-
-
-@patch("saleor.payment.gateway.refund")
-def test_handle_authorization_calls_refund_for_inactive_payment(
- mock_refund,
- notification,
- adyen_plugin,
- payment_adyen_for_checkout,
- address,
-):
- # given
- checkout = payment_adyen_for_checkout.checkout
- checkout.shipping_address = address
-
- checkout.billing_address = address
- checkout.save()
-
- payment = payment_adyen_for_checkout
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
- )
- payment.is_active = False
- payment.order = None
- payment.total = total.gross.amount
- payment.currency = total.gross.currency
- payment.to_confirm = True
- payment.save()
-
- Transaction.objects.bulk_create(
- [
- Transaction(
- payment_id=payment.id,
- token="reference",
- kind=TransactionKind.CAPTURE,
- is_success=True,
- action_required=False,
- currency=payment.currency,
- amount=payment.total,
- gateway_response={},
- already_processed=True,
- ),
- Transaction(
- payment_id=payment.id,
- token="refund-reference",
- is_success=True,
- kind=TransactionKind.REFUND_ONGOING,
- action_required=False,
- currency=payment.currency,
- amount=payment.total,
- gateway_response={},
- already_processed=True,
- ),
- Transaction(
- payment_id=payment.id,
- token="refund-reference",
- is_success=True,
- kind=TransactionKind.REFUND,
- action_required=False,
- currency=payment.currency,
- amount=payment.total,
- gateway_response={},
- already_processed=True,
- ),
- ]
- )
-
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- psp_reference="reference",
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin(adyen_auto_capture=True).config
-
- # when
- handle_authorization(notification, config)
-
- # then
- payment.refresh_from_db()
- assert not payment.order
- assert payment.checkout
- assert payment.captured_amount == Decimal(0)
- assert payment.transactions.count() == 3
-
-
-@patch("saleor.payment.gateway.void")
-def test_handle_authorization_for_checkout_one_of_variants_deleted(
- void_mock,
- notification,
- adyen_plugin,
- payment_adyen_for_checkout,
- address,
-):
- checkout = payment_adyen_for_checkout.checkout
- checkout.shipping_address = address
-
- checkout.billing_address = address
- checkout.save()
-
- payment = payment_adyen_for_checkout
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
- )
- payment.is_active = True
- payment.order = None
- payment.total = total.gross.amount
- payment.currency = total.gross.currency
- payment.to_confirm = True
- payment.save()
-
- checkout.lines.first().delete()
- checkout.price_expiration = timezone.now()
- checkout.save(update_fields=["price_expiration"])
-
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
- handle_authorization(notification, config)
-
- payment.refresh_from_db()
- assert void_mock.call_count == 1
- assert not payment.order
- assert payment.checkout
- assert payment.transactions.count() == 2
- transaction = payment.transactions.exclude(
- kind=TransactionKind.ACTION_TO_CONFIRM
- ).get()
- assert transaction.is_success is True
- assert transaction.kind == TransactionKind.AUTH
-
-
-def test_handle_authorization_with_adyen_auto_capture(
- notification, adyen_plugin, payment_adyen_for_checkout, address, shipping_method
-):
- checkout = payment_adyen_for_checkout.checkout
- checkout.shipping_address = address
-
- checkout.billing_address = address
- checkout.save()
-
- payment = payment_adyen_for_checkout
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
- )
- payment.is_active = True
- payment.order = None
- payment.total = total.gross.amount
- payment.currency = total.gross.currency
- payment.to_confirm = True
- payment.save()
-
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
-
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
-
- plugin = adyen_plugin(adyen_auto_capture=True)
- handle_authorization(notification, plugin.config)
-
- payment.refresh_from_db()
- assert payment.transactions.count() == 2
- transaction = payment.transactions.filter(kind=TransactionKind.CAPTURE).get()
- assert transaction.is_success is True
- external_events = payment.order.events.filter(
- type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
- )
- assert external_events.count() == 1
-
-
-@patch("saleor.payment.gateway.refund")
-def test_handle_authorization_with_adyen_auto_capture_and_inactive_payment(
- refund_mock, notification, adyen_plugin, inactive_payment_adyen_for_checkout
-):
- """Test that refund is called for inactive payments without an existing capture transaction."""
- # given
- payment = inactive_payment_adyen_for_checkout
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- assert payment.transactions.count() == 0
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- plugin = adyen_plugin(adyen_auto_capture=True)
-
- # when
- handle_authorization(notification, plugin.config)
-
- # then
- payment.refresh_from_db()
- assert payment.transactions.count() == 1
- txn = payment.transactions.first()
- assert txn.kind == TransactionKind.CAPTURE
- assert payment.charge_status == ChargeStatus.FULLY_CHARGED
- assert payment.captured_amount == txn.amount
- assert refund_mock.called
-
-
-@patch("saleor.payment.gateway.refund")
-def test_handle_authorization_adyen_auto_capture_inactive_payment_and_captured_txn(
- refund_mock, notification, adyen_plugin, inactive_payment_adyen_for_checkout
-):
- """Test that refund is called on inactive payments with existing capture transactions."""
- # given
- payment = inactive_payment_adyen_for_checkout
- psp_reference = "ABC"
- txn = payment.transactions.create(
- is_success=True,
- action_required=False,
- kind=TransactionKind.CAPTURE,
- amount=payment.total,
- currency=payment.currency,
- token=psp_reference,
- gateway_response={},
- )
- update_payment_charge_status(payment, txn)
- captured_amount = payment.captured_amount
- assert payment.transactions.count() == 1
-
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
-
- notification = notification(
- psp_reference=psp_reference,
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- plugin = adyen_plugin(adyen_auto_capture=True)
-
- # when
- handle_authorization(notification, plugin.config)
-
- # then
- payment.refresh_from_db()
- assert payment.transactions.count() == 1
- assert payment.charge_status == ChargeStatus.FULLY_CHARGED
- assert payment.captured_amount == captured_amount
- assert refund_mock.called
-
-
-@patch("saleor.payment.gateway.void")
-def test_handle_authorization_without_adyen_auto_capture_and_inactive_payment(
- void_mock, notification, adyen_plugin, inactive_payment_adyen_for_checkout
-):
- payment = inactive_payment_adyen_for_checkout
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- plugin = adyen_plugin(adyen_auto_capture=False)
-
- handle_authorization(notification, plugin.config)
- payment.refresh_from_db()
-
- assert payment.charge_status == ChargeStatus.NOT_CHARGED
- assert void_mock.called
-
-
-def test_handle_authorization_with_auto_capture(
- notification, adyen_plugin, payment_adyen_for_checkout
-):
- payment = payment_adyen_for_checkout
- payment.to_confirm = True
- payment.save()
-
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- psp_reference="853596537720508F",
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin(adyen_auto_capture=False, auto_capture=True).config
-
- handle_authorization(notification, config)
-
- payment.refresh_from_db()
- assert payment.transactions.count() == 2
- transaction = payment.transactions.filter(kind=TransactionKind.CAPTURE).get()
- assert transaction.is_success is True
- assert payment.charge_status == ChargeStatus.FULLY_CHARGED
- external_events = payment.order.events.filter(
- type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
- )
- assert external_events.count() == 1
-
-
-def test_handle_authorization_with_adyen_auto_capture_and_payment_charged(
- notification, adyen_plugin, payment_adyen_for_order
-):
- payment = payment_adyen_for_order
- payment.charge_status = ChargeStatus.FULLY_CHARGED
- payment.save()
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
- config.connection_params["adyen_auto_capture"] = True
- handle_authorization(notification, config)
-
- payment.refresh_from_db()
- assert payment.transactions.count() == 2
- assert payment.transactions.filter(kind=TransactionKind.CAPTURE).exists()
- external_events = payment.order.events.filter(
- type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
- )
- assert external_events.count() == 1
-
-
[email protected]("payment_is_active", [True, False])
-def test_handle_cancel(
- payment_is_active, notification, adyen_plugin, payment_adyen_for_order
-):
- payment = payment_adyen_for_order
- payment.charge_status = ChargeStatus.FULLY_CHARGED
- payment.is_active = payment_is_active
- payment.save()
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
-
- handle_cancellation(notification, config)
-
- payment.order.refresh_from_db()
- assert payment.transactions.count() == 2
- transaction = payment.transactions.filter(kind=TransactionKind.CANCEL).get()
- assert transaction.is_success is True
-
- assert payment.order.status == OrderStatus.CANCELED
- external_events = payment.order.events.filter(
- type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
- )
- assert external_events.count() == 1
-
-
-def test_handle_cancel_invalid_payment_id(
- notification, adyen_plugin, payment_adyen_for_order, caplog
-):
- payment = payment_adyen_for_order
- payment.charge_status = ChargeStatus.FULLY_CHARGED
- invalid_reference = "test invalid reference"
- notification = notification(
- merchant_reference=invalid_reference,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
- transaction_count = payment.transactions.count()
-
- caplog.set_level(logging.WARNING)
-
- handle_cancellation(notification, config)
-
- payment.order.refresh_from_db()
- assert payment.transactions.count() == transaction_count
-
- payment.refresh_from_db()
- assert payment.transactions.count() == transaction_count
- assert f"Unable to decode the payment ID {invalid_reference}." in caplog.text
-
-
-def test_handle_cancel_already_canceled(
- notification, adyen_plugin, payment_adyen_for_order
-):
- payment = payment_adyen_for_order
- payment.charge_status = ChargeStatus.FULLY_CHARGED
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
- create_new_transaction(notification, payment, TransactionKind.CANCEL)
-
- handle_cancellation(notification, config)
-
- assert payment.transactions.count() == 2
-
-
-def test_handle_capture_for_order(notification, adyen_plugin, payment_adyen_for_order):
- payment = payment_adyen_for_order
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
- handle_capture(notification, config)
-
- payment.refresh_from_db()
- assert payment.transactions.count() == 2
- transaction = payment.transactions.filter(kind=TransactionKind.CAPTURE).get()
- assert transaction.is_success is True
- assert payment.charge_status == ChargeStatus.FULLY_CHARGED
- external_events = payment.order.events.filter(
- type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
- )
- assert external_events.count() == 1
-
-
-def test_handle_capture_for_checkout(
- notification,
- adyen_plugin,
- payment_adyen_for_checkout,
- address,
-):
- checkout = payment_adyen_for_checkout.checkout
- checkout.shipping_address = address
-
- checkout.billing_address = address
- checkout.save()
- checkout_token = str(checkout.token)
-
- payment = payment_adyen_for_checkout
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
- )
- payment.is_active = True
- payment.order = None
- payment.total = total.gross.amount
- payment.currency = total.gross.currency
- payment.to_confirm = True
- payment.save()
-
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
- handle_capture(notification, config)
-
- payment.refresh_from_db()
- assert payment.transactions.count() == 2
- transaction = payment.transactions.exclude(
- kind=TransactionKind.ACTION_TO_CONFIRM
- ).get()
- assert transaction.is_success is True
- assert transaction.kind == TransactionKind.AUTH
- assert payment.checkout is None
- assert payment.order
- assert payment.order.checkout_token == checkout_token
- external_events = payment.order.events.filter(
- type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
- )
- assert external_events.count() == 1
-
-
-@patch("saleor.payment.gateway.refund")
-def test_handle_capture_inactive_payment(
- refund_mock,
- notification,
- adyen_plugin,
- inactive_payment_adyen_for_checkout,
- address,
-):
- """Test that refund is called on inactive payments without an existing capture transaction."""
- # given
- payment = inactive_payment_adyen_for_checkout
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- assert payment.transactions.count() == 0
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
-
- # when
- handle_capture(notification, config)
-
- # then
- payment.refresh_from_db()
- assert payment.transactions.count() == 1
- txn = payment.transactions.first()
- assert txn.kind == TransactionKind.CAPTURE
- assert payment.charge_status == ChargeStatus.FULLY_CHARGED
- assert payment.captured_amount == txn.amount
- assert refund_mock.called
-
-
-@patch("saleor.payment.gateway.refund")
-def test_handle_capture_inactive_payment_capture_txn_exists(
- refund_mock,
- notification,
- adyen_plugin,
- inactive_payment_adyen_for_checkout,
- address,
-):
- """Test that refund is called on inactive payments with existing capture transactions."""
- # given
- payment = inactive_payment_adyen_for_checkout
- psp_reference = "ABC"
- txn = payment.transactions.create(
- is_success=True,
- action_required=False,
- kind=TransactionKind.CAPTURE,
- amount=payment.total,
- currency=payment.currency,
- token=psp_reference,
- gateway_response={},
- )
- update_payment_charge_status(payment, txn)
- captured_amount = payment.captured_amount
- assert payment.transactions.count() == 1
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- psp_reference=psp_reference,
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
-
- # when
- handle_capture(notification, config)
-
- # then
- assert payment.transactions.count() == 1
- assert payment.charge_status == ChargeStatus.FULLY_CHARGED
- assert payment.captured_amount == captured_amount
- assert refund_mock.called
-
-
-@patch("saleor.payment.gateway.void")
-def test_handle_capture_for_checkout_order_not_created_checkout_line_variant_deleted(
- void_mock,
- notification,
- adyen_plugin,
- payment_adyen_for_checkout,
- address,
-):
- """Ensure that payment is not captured when a checkout line variant is deleted."""
-
- # given
- checkout = payment_adyen_for_checkout.checkout
- checkout.shipping_address = address
-
- checkout.billing_address = address
- checkout.save()
-
- payment = payment_adyen_for_checkout
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
- )
- payment.is_active = True
- payment.order = None
- payment.total = total.gross.amount
- payment.currency = total.gross.currency
- payment.to_confirm = True
- payment.save()
-
- checkout.lines.first().delete()
- checkout.price_expiration = timezone.now()
- checkout.save(update_fields=["price_expiration"])
-
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
-
- # when
- handle_capture(notification, config)
-
- # then
- payment.refresh_from_db()
- assert void_mock.call_count == 1
- assert not payment.order
- assert payment.checkout
-
- assert payment.transactions.count() == 2
- transaction = payment.transactions.exclude(
- kind=TransactionKind.ACTION_TO_CONFIRM
- ).get()
- assert transaction.is_success is True
- assert transaction.kind == TransactionKind.AUTH
-
-
-def test_handle_capture_invalid_payment_id(
- notification, adyen_plugin, payment_adyen_for_order, caplog
-):
- payment = payment_adyen_for_order
- invalid_reference = "test invalid reference"
- notification = notification(
- merchant_reference=invalid_reference,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
- transaction_count = payment.transactions.count()
-
- caplog.set_level(logging.WARNING)
-
- handle_capture(notification, config)
-
- payment.refresh_from_db()
- assert payment.transactions.count() == transaction_count
- assert f"Unable to decode the payment ID {invalid_reference}." in caplog.text
-
-
-def test_handle_capture_with_payment_already_charged(
- notification, adyen_plugin, payment_adyen_for_order
-):
- payment = payment_adyen_for_order
- payment.charge_status = ChargeStatus.FULLY_CHARGED
- payment.captured_amount = payment.total
- payment.save()
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
-
- handle_capture(notification, config)
-
- # Payment is already captured so no need to save capture transaction
- payment.refresh_from_db()
- assert payment.transactions.count() == 2
- external_events = payment.order.events.filter(
- type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
- )
- assert external_events.count() == 1
-
-
- "charge_status", [ChargeStatus.NOT_CHARGED, ChargeStatus.FULLY_CHARGED]
-)
-def test_handle_failed_capture(
- charge_status, notification, adyen_plugin, payment_adyen_for_order
-):
- payment = payment_adyen_for_order
- payment.charge_status = charge_status
- payment.captured_amount = payment.total
- payment.save()
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
-
- handle_failed_capture(notification, config)
-
- assert payment.transactions.count() == 2
- transaction = payment.transactions.filter(kind=TransactionKind.CAPTURE_FAILED).get()
- assert transaction.is_success is True
- payment.refresh_from_db()
- assert payment.charge_status == ChargeStatus.NOT_CHARGED
- external_events = payment.order.events.filter(
- type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
- )
- assert external_events.count() == 1
-
-
-def test_handle_failed_capture_invalid_payment_id(
- notification, adyen_plugin, payment_adyen_for_order, caplog
-):
- payment = payment_adyen_for_order
- payment.charge_status = ChargeStatus.FULLY_CHARGED
- payment.captured_amount = payment.total
- payment.save()
- invalid_reference = "test invalid reference"
- notification = notification(
- merchant_reference=invalid_reference,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
- transaction_count = payment.transactions.count()
-
- caplog.set_level(logging.WARNING)
-
- handle_failed_capture(notification, config)
-
- payment.refresh_from_db()
- assert payment.transactions.count() == transaction_count
- assert f"Unable to decode the payment ID {invalid_reference}." in caplog.text
-
-
-def test_handle_failed_capture_partial_charge(
- notification, adyen_plugin, payment_adyen_for_order
-):
- payment = payment_adyen_for_order
- payment.charge_status = ChargeStatus.FULLY_CHARGED
- payment.captured_amount += payment.total * 2
- payment.save()
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
-
- handle_failed_capture(notification, config)
-
- assert payment.transactions.count() == 2
- transaction = payment.transactions.filter(kind=TransactionKind.CAPTURE_FAILED).get()
- assert transaction.is_success is True
- payment.refresh_from_db()
- assert payment.charge_status == ChargeStatus.PARTIALLY_CHARGED
- external_events = payment.order.events.filter(
- type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
- )
- assert external_events.count() == 1
-
-
-def test_handle_pending(notification, adyen_plugin, payment_adyen_for_order):
- payment = payment_adyen_for_order
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
-
- handle_pending(notification, config)
-
- assert payment.transactions.count() == 2
- transaction = payment.transactions.filter(kind=TransactionKind.PENDING).get()
- assert transaction.is_success is True
- payment.refresh_from_db()
- assert payment.charge_status == ChargeStatus.PENDING
- external_events = payment.order.events.filter(
- type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
- )
- assert external_events.count() == 1
-
-
-def test_handle_pending_invalid_payment_id(
- notification, adyen_plugin, payment_adyen_for_order, caplog
-):
- payment = payment_adyen_for_order
- invalid_reference = "test invalid reference"
- notification = notification(
- merchant_reference=invalid_reference,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
- transaction_count = payment.transactions.count()
-
- caplog.set_level(logging.WARNING)
-
- handle_pending(notification, config)
-
- payment.refresh_from_db()
- assert payment.transactions.count() == transaction_count
- assert f"Unable to decode the payment ID {invalid_reference}." in caplog.text
-
-
-def test_handle_pending_with_adyen_auto_capture(
- notification, adyen_plugin, payment_adyen_for_order
-):
- payment = payment_adyen_for_order
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
- config.connection_params["adyen_auto_capture"] = True
-
- handle_pending(notification, config)
-
- # in case of autocapture we don't want to store the pending status as all payments
- # by default get capture status.
- assert payment.transactions.count() == 2
- assert payment.transactions.filter(kind=TransactionKind.PENDING).first()
- payment.refresh_from_db()
- assert payment.charge_status == ChargeStatus.PENDING
- external_events = payment.order.events.filter(
- type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
- )
- assert external_events.count() == 1
-
-
-def test_handle_pending_already_pending(
- notification, adyen_plugin, payment_adyen_for_order
-):
- payment = payment_adyen_for_order
- payment.charge_status = ChargeStatus.PENDING
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
- create_new_transaction(notification, payment, TransactionKind.PENDING)
-
- handle_pending(notification, config)
-
- assert payment.transactions.filter(kind=TransactionKind.PENDING).exists()
-
-
[email protected]("saleor.payment.gateways.adyen.webhooks.order_refunded")
-def test_handle_refund(
- mock_order_refunded, notification, adyen_plugin, payment_adyen_for_order
-):
- payment = payment_adyen_for_order
- payment.charge_status = ChargeStatus.FULLY_CHARGED
- payment.captured_amount = payment.total
- payment.save()
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
-
- handle_refund(notification, config)
-
- assert payment.transactions.count() == 2
- transaction = payment.transactions.filter(kind=TransactionKind.REFUND).get()
- assert transaction.is_success is True
- payment.refresh_from_db()
- assert payment.charge_status == ChargeStatus.FULLY_REFUNDED
- assert payment.captured_amount == Decimal("0.00")
-
- mock_order_refunded.assert_called_once_with(
- payment.order, None, None, transaction.amount, payment, mock.ANY
- )
- external_events = payment.order.events.filter(
- type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
- )
- assert external_events.count() == 1
-
-
-def test_handle_refund_invalid_payment_id(
- notification, adyen_plugin, payment_adyen_for_order, caplog
-):
- payment = payment_adyen_for_order
- payment.charge_status = ChargeStatus.FULLY_CHARGED
- payment.captured_amount = payment.total
- payment.save()
- invalid_reference = "test invalid reference"
- notification = notification(
- merchant_reference=invalid_reference,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
- transaction_count = payment.transactions.count()
-
- caplog.set_level(logging.WARNING)
-
- handle_refund(notification, config)
-
- payment.refresh_from_db()
- assert payment.transactions.count() == transaction_count
- assert f"Unable to decode the payment ID {invalid_reference}." in caplog.text
-
-
[email protected]("saleor.payment.gateways.adyen.webhooks.order_refunded")
-def test_handle_refund_already_refunded(
- mock_order_refunded, notification, adyen_plugin, payment_adyen_for_order
-):
- payment = payment_adyen_for_order
- payment.charge_status = ChargeStatus.FULLY_REFUNDED
- payment.captured_amount = Decimal("0.00")
- payment.save()
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- transaction = create_new_transaction(notification, payment, TransactionKind.REFUND)
- transaction.already_processed = True
- transaction.save()
-
- config = adyen_plugin().config
-
- handle_refund(notification, config)
-
- assert payment.transactions.count() == 2 # AUTH, REFUND
- assert not mock_order_refunded.called
-
-
-def test_handle_failed_refund_missing_transaction(
- notification, adyen_plugin, payment_adyen_for_order
-):
- payment = payment_adyen_for_order
- payment.charge_status = ChargeStatus.FULLY_CHARGED
- payment.captured_amount = payment.total
- payment.save()
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
-
- handle_failed_refund(notification, config)
-
- assert payment.transactions.count() == 1
- external_events = payment.order.events.filter(
- type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
- )
- assert external_events.count() == 1
-
-
-def test_handle_failed_refund_invalid_payment_id(
- notification, adyen_plugin, payment_adyen_for_order, caplog
-):
- payment = payment_adyen_for_order
- payment.charge_status = ChargeStatus.FULLY_CHARGED
- payment.captured_amount = payment.total
- payment.save()
- invalid_reference = "test invalid reference"
- notification = notification(
- merchant_reference=invalid_reference,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
- transaction_count = payment.transactions.count()
-
- caplog.set_level(logging.WARNING)
-
- handle_failed_refund(notification, config)
-
- payment.refresh_from_db()
- assert payment.transactions.count() == transaction_count
- assert f"Unable to decode the payment ID {invalid_reference}." in caplog.text
-
-
-def test_handle_failed_refund_with_transaction_refund_ongoing(
- notification, adyen_plugin, payment_adyen_for_order
-):
- payment = payment_adyen_for_order
- payment.charge_status = ChargeStatus.FULLY_CHARGED
- payment.captured_amount = payment.total
- payment.save()
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
- create_new_transaction(notification, payment, TransactionKind.REFUND_ONGOING)
- handle_failed_refund(notification, config)
-
- # ACTION_TO_CONFIRM, REFUND_ONGOING, REFUND_FAILED, FULLY_CHARGED
- assert payment.transactions.count() == 4
- assert payment.charge_status == ChargeStatus.FULLY_CHARGED
- assert payment.total == payment.captured_amount
- external_events = payment.order.events.filter(
- type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
- )
- assert external_events.count() == 1
-
-
-def test_handle_failed_refund_with_transaction_refund(
- notification, adyen_plugin, payment_adyen_for_order
-):
- payment = payment_adyen_for_order
- payment.charge_status = ChargeStatus.FULLY_REFUNDED
- payment.captured_amount = Decimal("0.0")
- payment.save()
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
- create_new_transaction(notification, payment, TransactionKind.REFUND)
- handle_failed_refund(notification, config)
-
- payment.refresh_from_db()
- assert payment.transactions.count() == 4 # REFUND, REFUND_FAILED, FULLY_CHARGED
- assert payment.charge_status == ChargeStatus.FULLY_CHARGED
- assert payment.total == payment.captured_amount
- external_events = payment.order.events.filter(
- type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
- )
- assert external_events.count() == 1
-
-
-def test_handle_reversed_refund(notification, adyen_plugin, payment_adyen_for_order):
- payment = payment_adyen_for_order
- payment.charge_status = ChargeStatus.FULLY_REFUNDED
- payment.captured_amount = Decimal("0.0")
- payment.save()
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
- handle_reversed_refund(notification, config)
-
- payment.refresh_from_db()
- assert payment.transactions.filter(kind=TransactionKind.REFUND_REVERSED).exists()
- assert payment.charge_status == ChargeStatus.FULLY_CHARGED
- assert payment.total == payment.captured_amount
- external_events = payment.order.events.filter(
- type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
- )
- assert external_events.count() == 1
-
-
-def test_handle_reversed_refund_invalid_payment_id(
- notification, adyen_plugin, payment_adyen_for_order, caplog
-):
- payment = payment_adyen_for_order
- payment.charge_status = ChargeStatus.FULLY_REFUNDED
- payment.captured_amount = Decimal("0.0")
- payment.save()
- invalid_reference = "test invalid reference"
- notification = notification(
- merchant_reference=invalid_reference,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
- transaction_count = payment.transactions.count()
-
- caplog.set_level(logging.WARNING)
-
- handle_reversed_refund(notification, config)
-
- payment.refresh_from_db()
- assert payment.transactions.count() == transaction_count
- assert f"Unable to decode the payment ID {invalid_reference}." in caplog.text
-
-
-def test_handle_reversed_refund_already_processed(
- notification, adyen_plugin, payment_adyen_for_order
-):
- payment = payment_adyen_for_order
- payment.charge_status = ChargeStatus.FULLY_CHARGED
- payment.captured_amount = payment.total
- payment.save()
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
- create_new_transaction(notification, payment, TransactionKind.REFUND_REVERSED)
- handle_reversed_refund(notification, config)
-
- assert payment.transactions.filter(kind=TransactionKind.REFUND_REVERSED).exists()
-
-
-def test_webhook_not_implemented(notification, adyen_plugin, payment_adyen_for_order):
- payment = payment_adyen_for_order
- payment.charge_status = ChargeStatus.FULLY_CHARGED
- payment.captured_amount = payment.total
- payment.save()
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
-
- webhook_not_implemented(notification, config)
-
- external_events = payment.order.events.filter(
- type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
- )
- assert external_events.count() == 1
-
-
-def test_webhook_not_implemented_invalid_payment_id(
- notification, adyen_plugin, payment_adyen_for_order, caplog
-):
- payment = payment_adyen_for_order
- payment.charge_status = ChargeStatus.FULLY_CHARGED
- payment.captured_amount = payment.total
- payment.save()
- invalid_reference = "test invalid reference"
- notification = notification(
- merchant_reference=invalid_reference,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- config = adyen_plugin().config
- transaction_count = payment.transactions.count()
-
- caplog.set_level(logging.WARNING)
-
- webhook_not_implemented(notification, config)
-
- payment.refresh_from_db()
- assert payment.transactions.count() == transaction_count
- assert f"Unable to decode the payment ID {invalid_reference}." in caplog.text
-
-
[email protected]("saleor.payment.gateways.adyen.webhooks.handle_refund")
-def test_handle_cancel_or_refund_action_refund(
- mock_handle_refund, notification, adyen_plugin, payment_adyen_for_order
-):
- payment = payment_adyen_for_order
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- config = adyen_plugin().config
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- notification["additionalData"]["modification.action"] = "refund"
-
- handle_cancel_or_refund(notification, config)
-
- mock_handle_refund.assert_called_once_with(notification, config)
-
-
[email protected]("saleor.payment.gateways.adyen.webhooks.handle_cancellation")
-def test_handle_cancel_or_refund_action_cancel(
- mock_handle_cancellation, notification, adyen_plugin, payment_adyen_for_order
-):
- payment = payment_adyen_for_order
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- config = adyen_plugin().config
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- notification["additionalData"]["modification.action"] = "cancel"
-
- handle_cancel_or_refund(notification, config)
-
- mock_handle_cancellation.assert_called_once_with(notification, config)
-
-
-def test_handle_cancel_or_refund_action_cancel_invalid_payment_id(
- notification, adyen_plugin, payment_adyen_for_order, caplog
-):
- payment = payment_adyen_for_order
- config = adyen_plugin().config
- invalid_reference = "test invalid reference"
- notification = notification(
- merchant_reference=invalid_reference,
- value=price_to_minor_unit(payment.total, payment.currency),
- )
- notification["additionalData"]["modification.action"] = "cancel"
-
- caplog.set_level(logging.WARNING)
-
- handle_cancel_or_refund(notification, config)
-
- assert f"Unable to decode the payment ID {invalid_reference}." in caplog.text
-
-
-def test_handle_not_created_order_order_created(
- payment_adyen_for_checkout, adyen_plugin, notification
-):
- payment_adyen_for_checkout.charge_status = ChargeStatus.FULLY_CHARGED
- payment_adyen_for_checkout.save(update_fields=["charge_status"])
-
- adyen_plugin()
- handle_not_created_order(
- notification(),
- payment_adyen_for_checkout,
- payment_adyen_for_checkout.checkout,
- TransactionKind.CAPTURE,
- get_plugins_manager(allow_replica=False),
- )
-
- payment_adyen_for_checkout.refresh_from_db()
-
- assert payment_adyen_for_checkout.order
-
-
-@patch("saleor.payment.gateway.refund")
-def test_handle_not_created_order_order_not_created_checkout_line_variant_deleted(
- refund_mock,
- payment_adyen_for_checkout,
- adyen_plugin,
- notification,
-):
- """Validate if order is not created when one of checkout line variant is deleted."""
-
- # given
- checkout = payment_adyen_for_checkout.checkout
- checkout.lines.first().variant.delete()
- checkout.price_expiration = timezone.now()
- checkout.save()
-
- payment_adyen_for_checkout.charge_status = ChargeStatus.FULLY_CHARGED
- payment_adyen_for_checkout.captured_amount = payment_adyen_for_checkout.total
- payment_adyen_for_checkout.save(update_fields=["charge_status", "captured_amount"])
-
- adyen_plugin()
-
- # when
- handle_not_created_order(
- notification(),
- payment_adyen_for_checkout,
- payment_adyen_for_checkout.checkout,
- TransactionKind.CAPTURE,
- get_plugins_manager(allow_replica=False),
- )
-
- # then
- assert refund_mock.call_count == 1
- payment_adyen_for_checkout.refresh_from_db()
- assert not payment_adyen_for_checkout.order
-
-
-@patch("saleor.payment.gateway.refund")
-@patch("saleor.checkout.complete_checkout._get_order_data")
-def test_handle_not_created_order_refund_when_create_order_raises(
- order_data_mock, refund_mock, payment_adyen_for_checkout, adyen_plugin, notification
-):
- order_data_mock.side_effect = ValidationError("Test error")
-
- payment_adyen_for_checkout.charge_status = ChargeStatus.FULLY_CHARGED
- payment_adyen_for_checkout.save(update_fields=["charge_status"])
-
- adyen_plugin()
- handle_not_created_order(
- notification(),
- payment_adyen_for_checkout,
- payment_adyen_for_checkout.checkout,
- TransactionKind.CAPTURE,
- get_plugins_manager(allow_replica=False),
- )
-
- assert payment_adyen_for_checkout.can_refund()
- assert refund_mock.call_count == 1
-
-
-@patch("saleor.payment.gateway.void")
-@patch("saleor.checkout.complete_checkout._get_order_data")
-def test_handle_not_created_order_void_when_create_order_raises(
- order_data_mock, void_mock, payment_adyen_for_checkout, adyen_plugin, notification
-):
- order_data_mock.side_effect = ValidationError("Test error")
-
- payment_adyen_for_checkout.charge_status = ChargeStatus.NOT_CHARGED
- payment_adyen_for_checkout.save(update_fields=["charge_status"])
-
- adyen_plugin()
- handle_not_created_order(
- notification(),
- payment_adyen_for_checkout,
- payment_adyen_for_checkout.checkout,
- TransactionKind.CAPTURE,
- get_plugins_manager(allow_replica=False),
- )
-
- assert payment_adyen_for_checkout.can_void()
- assert void_mock.call_count == 1
-
-
- "charge_status",
- [
- ChargeStatus.PARTIALLY_REFUNDED,
- ChargeStatus.REFUSED,
- ChargeStatus.FULLY_REFUNDED,
- ChargeStatus.CANCELLED,
- ],
-)
-def test_handle_not_created_order_return_none(
- charge_status, payment_adyen_for_checkout, adyen_plugin, notification
-):
- payment_adyen_for_checkout.charge_status = charge_status
- payment_adyen_for_checkout.save(update_fields=["charge_status"])
-
- assert not handle_not_created_order(
- notification(),
- payment_adyen_for_checkout,
- payment_adyen_for_checkout.checkout,
- TransactionKind.CAPTURE,
- get_plugins_manager(allow_replica=False),
- )
-
-
-def test_handle_not_created_order_create_new_success_transaction(
- payment_adyen_for_checkout, adyen_plugin, notification
-):
- payment_adyen_for_checkout.charge_status = ChargeStatus.NOT_CHARGED
- payment_adyen_for_checkout.save(update_fields=["charge_status"])
- payment_adyen_for_checkout.transactions.all().delete()
-
- adyen_plugin()
- handle_not_created_order(
- notification(),
- payment_adyen_for_checkout,
- payment_adyen_for_checkout.checkout,
- TransactionKind.CAPTURE,
- get_plugins_manager(allow_replica=False),
- )
-
- payment_adyen_for_checkout.refresh_from_db()
- assert payment_adyen_for_checkout.order
-
- all_payment_transactions = payment_adyen_for_checkout.transactions.all()
- assert len(all_payment_transactions) == 2
- assert all_payment_transactions[0].kind == TransactionKind.ACTION_TO_CONFIRM
- assert all_payment_transactions[1].kind == TransactionKind.AUTH
-
-
-@patch("saleor.payment.gateway.refund")
-@patch("saleor.checkout.complete_checkout._get_order_data")
-def test_handle_not_created_order_success_transaction_create_order_raises_and_refund(
- order_data_mock, refund_mock, payment_adyen_for_checkout, adyen_plugin, notification
-):
- order_data_mock.side_effect = ValidationError("Test error")
-
- payment_adyen_for_checkout.charge_status = ChargeStatus.FULLY_CHARGED
- payment_adyen_for_checkout.save(update_fields=["charge_status"])
- payment_adyen_for_checkout.transactions.all().delete()
-
- adyen_plugin()
- handle_not_created_order(
- notification(),
- payment_adyen_for_checkout,
- payment_adyen_for_checkout.checkout,
- TransactionKind.CAPTURE,
- get_plugins_manager(allow_replica=False),
- )
-
- payment_adyen_for_checkout.refresh_from_db()
- assert not payment_adyen_for_checkout.order
-
- all_payment_transactions = payment_adyen_for_checkout.transactions.all()
- assert len(all_payment_transactions) == 2
- assert all_payment_transactions[0].kind == TransactionKind.ACTION_TO_CONFIRM
- assert all_payment_transactions[1].kind == TransactionKind.AUTH
-
- assert payment_adyen_for_checkout.can_refund()
- assert refund_mock.call_count == 1
-
-
-@patch("saleor.payment.gateway.void")
-@patch("saleor.checkout.complete_checkout._get_order_data")
-def test_handle_not_created_order_success_transaction_create_order_raises_and_void(
- order_data_mock, void_mock, payment_adyen_for_checkout, adyen_plugin, notification
-):
- order_data_mock.side_effect = ValidationError("Test error")
-
- payment_adyen_for_checkout.charge_status = ChargeStatus.NOT_CHARGED
- payment_adyen_for_checkout.save(update_fields=["charge_status"])
- payment_adyen_for_checkout.transactions.all().delete()
-
- adyen_plugin()
- handle_not_created_order(
- notification(),
- payment_adyen_for_checkout,
- payment_adyen_for_checkout.checkout,
- TransactionKind.CAPTURE,
- get_plugins_manager(allow_replica=False),
- )
-
- payment_adyen_for_checkout.refresh_from_db()
- assert not payment_adyen_for_checkout.order
-
- all_payment_transactions = payment_adyen_for_checkout.transactions.all()
- assert len(all_payment_transactions) == 2
- assert all_payment_transactions[0].kind == TransactionKind.ACTION_TO_CONFIRM
- assert all_payment_transactions[1].kind == TransactionKind.AUTH
-
- assert payment_adyen_for_checkout.can_void()
- assert void_mock.call_count == 1
-
-
-def test_confirm_payment_and_set_back_to_confirm(
- payment_adyen_for_checkout, adyen_plugin, notification
-):
- plugin = adyen_plugin()
- payment_adyen_for_checkout.to_confirm = True
- payment_adyen_for_checkout.save(update_fields=["to_confirm"])
- create_new_transaction(
- notification(), payment_adyen_for_checkout, TransactionKind.ACTION_TO_CONFIRM
- )
-
- confirm_payment_and_set_back_to_confirm(
- payment_adyen_for_checkout,
- get_plugins_manager(allow_replica=False),
- plugin.channel.slug,
- )
-
- payment_adyen_for_checkout.refresh_from_db()
-
- assert payment_adyen_for_checkout.to_confirm
-
-
-def test_handle_order_opened(adyen_plugin, notification):
- assert not handle_order_opened(notification(), adyen_plugin().config)
-
-
-def test_handle_order_closed_payment_does_not_exist(
- notification, adyen_plugin, payment_adyen_for_checkout
-):
- payment = payment_adyen_for_checkout
- notification = notification(
- merchant_reference="xyz",
- value=price_to_minor_unit(payment.total, payment.currency),
- success="false",
- )
- config = adyen_plugin().config
- handle_order_closed(notification, config)
- payment.refresh_from_db()
- assert payment.transactions.count() == 0
- assert payment.checkout
- assert not payment.order
-
-
-def test_handle_order_closed_order_already_exists(
- notification, adyen_plugin, payment_adyen_for_order
-):
- payment = payment_adyen_for_order
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- success="true",
- )
- config = adyen_plugin().config
- handle_order_closed(notification, config)
-
- payment.refresh_from_db()
- assert payment.transactions.count() == 1
- assert not payment.checkout
- assert payment.order
- external_events = payment.order.events.filter(
- type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
- )
- assert external_events.count() == 0
-
-
-def test_handle_order_closed_success_false(
- notification, adyen_plugin, payment_adyen_for_checkout
-):
- payment = payment_adyen_for_checkout
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- success="false",
- )
- config = adyen_plugin().config
- handle_order_closed(notification, config)
-
- payment.refresh_from_db()
- assert payment.transactions.count() == 0
- assert payment.checkout
- assert not payment.order
-
-
-def test_handle_order_closed_success_true(
- notification, adyen_plugin, payment_adyen_for_checkout, address, shipping_method
-):
- checkout = payment_adyen_for_checkout.checkout
- checkout.shipping_address = address
-
- checkout.billing_address = address
- checkout.save()
- checkout_token = str(checkout.token)
-
- payment = payment_adyen_for_checkout
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
- )
- payment.is_active = True
- payment.order = None
- payment.total = total.gross.amount
- payment.currency = total.gross.currency
- payment.to_confirm = True
- payment.save()
-
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- success="true",
- )
- config = adyen_plugin().config
-
- handle_order_closed(notification, config)
-
- payment.refresh_from_db()
- assert payment.transactions.count() == 2
- transaction = payment.transactions.exclude(
- kind=TransactionKind.ACTION_TO_CONFIRM
- ).get()
- assert transaction.is_success is True
- assert transaction.kind == TransactionKind.AUTH
- assert payment.checkout is None
- assert payment.order
- assert payment.order.checkout_token == checkout_token
- external_events = payment.order.events.filter(
- type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
- )
- assert external_events.count() == 1
-
-
-def test_handle_order_closed_with_adyen_partial_payments_success_true(
- notification, adyen_plugin, payment_adyen_for_checkout, address, shipping_method
-):
- # given
- checkout = payment_adyen_for_checkout.checkout
- checkout.shipping_address = address
-
- checkout.billing_address = address
- checkout.save()
- checkout_token = str(checkout.token)
-
- payment = payment_adyen_for_checkout
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
- )
- payment.is_active = True
- payment.order = None
- payment.total = total.gross.amount
- payment.currency = total.gross.currency
- payment.to_confirm = True
- payment.save()
-
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification_data = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- success="true",
- )
- notification_data["additionalData"] = {
- "order-2-paymentMethod": "visa",
- "order-2-pspReference": "881643125782168B",
- "order-2-paymentAmount": "GBP 29.10",
- "order-1-pspReference": "861643125754056E",
- "order-1-paymentAmount": "GBP 41.90",
- "order-1-paymentMethod": "givex",
- }
- config = adyen_plugin().config
-
- # when
- handle_order_closed(notification_data, config)
-
- # then
- payment.refresh_from_db()
- assert payment.transactions.count() == 2
- transaction = payment.transactions.exclude(
- kind=TransactionKind.ACTION_TO_CONFIRM
- ).get()
- assert transaction.is_success is True
- assert transaction.kind == TransactionKind.AUTH
- assert payment.checkout is None
- assert payment.order
- assert payment.order.checkout_token == checkout_token
- external_events = payment.order.events.filter(
- type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
- )
- assert external_events.count() == 1
-
- external_event = external_events.first()
- event_message = external_event.parameters["message"]
- assert "Partial payment" in event_message
- assert "GBP 41.90" in event_message
- assert "GBP 29.10" in event_message
- assert "881643125782168B" in event_message
- assert "861643125754056E" in event_message
- assert "givex" in event_message
- assert "visa" in event_message
-
- partial_payments = list(payment.order.payments.exclude(id=payment.id))
- assert len(partial_payments) == 2
- assert all(payment.is_active is False for payment in partial_payments)
- assert all(payment.partial is True for payment in partial_payments)
- assert all(payment.is_active is False for payment in partial_payments)
- assert any(payment.total == Decimal("29.10") for payment in partial_payments)
- assert any(payment.total == Decimal("41.90") for payment in partial_payments)
- assert any(
- payment.psp_reference == "881643125782168B" for payment in partial_payments
- )
- assert any(
- payment.psp_reference == "861643125754056E" for payment in partial_payments
- )
-
-
-def test_handle_order_closed_with_adyen_partial_payments_success_true_without_amount(
- notification, adyen_plugin, payment_adyen_for_checkout, address, shipping_method
-):
- # given
- checkout = payment_adyen_for_checkout.checkout
- checkout.shipping_address = address
-
- checkout.billing_address = address
- checkout.save()
- checkout_token = str(checkout.token)
-
- payment = payment_adyen_for_checkout
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
- )
- payment.is_active = True
- payment.order = None
- payment.total = total.gross.amount
- payment.currency = total.gross.currency
- payment.to_confirm = True
- payment.save()
-
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification_data = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- success="true",
- )
- notification_data["additionalData"] = {
- "order-2-paymentMethod": "visa",
- "order-2-pspReference": "881643125782168B",
- "order-1-pspReference": "861643125754056E",
- "order-1-paymentAmount": "GBP 50.90",
- "order-1-paymentMethod": "givex",
- }
- config = adyen_plugin().config
-
- # when
- handle_order_closed(notification_data, config)
-
- # then
- payment.refresh_from_db()
- assert payment.transactions.count() == 2
- transaction = payment.transactions.exclude(
- kind=TransactionKind.ACTION_TO_CONFIRM
- ).get()
- assert transaction.is_success is True
- assert transaction.kind == TransactionKind.AUTH
- assert payment.checkout is None
- assert payment.order
- assert payment.order.checkout_token == checkout_token
- external_events = payment.order.events.filter(
- type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
- )
- assert external_events.count() == 1
-
- external_event = external_events.first()
- event_message = external_event.parameters["message"]
- assert "Partial payment" in event_message
- assert "GBP 50.90" in event_message
- assert "GBP 29.10" in event_message
- assert "881643125782168B" in event_message
- assert "861643125754056E" in event_message
- assert "givex" in event_message
- assert "visa" in event_message
-
- partial_payments = list(payment.order.payments.exclude(id=payment.id))
- assert len(partial_payments) == 2
- assert all(payment.is_active is False for payment in partial_payments)
- assert all(payment.partial is True for payment in partial_payments)
- assert all(payment.is_active is False for payment in partial_payments)
- assert any(payment.total == Decimal("29.10") for payment in partial_payments)
- assert any(payment.total == Decimal("50.90") for payment in partial_payments)
- assert any(
- payment.psp_reference == "881643125782168B" for payment in partial_payments
- )
- assert any(
- payment.psp_reference == "861643125754056E" for payment in partial_payments
- )
-
-
-@patch("saleor.payment.gateway.void")
[email protected]("saleor.payment.gateways.adyen.webhooks.call_refund")
-@patch("saleor.checkout.complete_checkout._get_order_data")
-def test_order_closed_with_adyen_partial_payments_unable_to_create_order(
- mock_order_data,
- mock_call_refund,
- mock_void,
- notification,
- adyen_plugin,
- payment_adyen_for_checkout,
- address,
-):
- # given
- mock_order_data.side_effect = ValidationError("Test error")
-
- checkout = payment_adyen_for_checkout.checkout
- checkout.shipping_address = address
-
- checkout.billing_address = address
- checkout.save()
-
- payment = payment_adyen_for_checkout
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
- )
- payment.is_active = True
- payment.order = None
- payment.total = total.gross.amount
- payment.currency = total.gross.currency
- payment.to_confirm = True
- payment.save()
-
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification_data = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- success="true",
- )
- notification_data["additionalData"] = {
- "order-2-paymentMethod": "visa",
- "order-2-pspReference": "881643125782168B",
- "order-2-paymentAmount": "GBP 29.10",
- "order-1-pspReference": "861643125754056E",
- "order-1-paymentAmount": "GBP 41.90",
- "order-1-paymentMethod": "givex",
- }
- merchant_account = "SaleorEcom"
- config = adyen_plugin(merchant_account=merchant_account).config
-
- # when
- handle_order_closed(notification_data, config)
-
- # then
- assert payment.checkout
- assert payment.order is None
- mock_call_refund.assert_any_call(
- amount=Decimal("41.90"),
- currency="GBP",
- merchant_account=merchant_account,
- token="861643125754056E",
- graphql_payment_id=mock.ANY,
- adyen_client=mock.ANY,
- )
- mock_call_refund.assert_any_call(
- amount=Decimal("29.10"),
- currency="GBP",
- merchant_account=merchant_account,
- token="881643125782168B",
- graphql_payment_id=mock.ANY,
- adyen_client=mock.ANY,
- )
-
-
-@patch("saleor.payment.gateway.void")
[email protected]("saleor.payment.gateways.adyen.webhooks.call_refund")
-def test_order_closed_with_not_active_payment(
- mock_call_refund,
- mock_void,
- notification,
- adyen_plugin,
- payment_adyen_for_checkout,
- address,
-):
- # given
-
- checkout = payment_adyen_for_checkout.checkout
- checkout.shipping_address = address
-
- checkout.billing_address = address
- checkout.save()
-
- payment = payment_adyen_for_checkout
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
- )
- payment.is_active = False
- payment.order = None
- payment.total = total.gross.amount
- payment.currency = total.gross.currency
- payment.to_confirm = True
- payment.save()
-
- payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- notification_data = notification(
- merchant_reference=payment_id,
- value=price_to_minor_unit(payment.total, payment.currency),
- success="true",
- )
- notification_data["additionalData"] = {
- "order-2-paymentMethod": "visa",
- "order-2-pspReference": "881643125782168B",
- "order-2-paymentAmount": "GBP 29.10",
- "order-1-pspReference": "861643125754056E",
- "order-1-paymentAmount": "GBP 41.90",
- "order-1-paymentMethod": "givex",
- }
- merchant_account = "SaleorEcom"
- config = adyen_plugin(merchant_account=merchant_account).config
-
- # when
- handle_order_closed(notification_data, config)
-
- # then
- assert payment.checkout
- assert payment.order is None
- mock_call_refund.assert_any_call(
- amount=Decimal("41.90"),
- currency="GBP",
- merchant_account=merchant_account,
- token="861643125754056E",
- graphql_payment_id=mock.ANY,
- adyen_client=mock.ANY,
- )
- mock_call_refund.assert_any_call(
- amount=Decimal("29.10"),
- currency="GBP",
- merchant_account=merchant_account,
- token="881643125782168B",
- graphql_payment_id=mock.ANY,
- adyen_client=mock.ANY,
- )
diff --git a/saleor/payment/gateways/adyen/tests/webhooks/test_prepare_api_request_data.py b/saleor/payment/gateways/adyen/tests/webhooks/test_prepare_api_request_data.py
deleted file mode 100644
index 48ce881a8b..0000000000
--- a/saleor/payment/gateways/adyen/tests/webhooks/test_prepare_api_request_data.py
+++ /dev/null
@@ -1,101 +0,0 @@
-from unittest import mock
-
-import pytest
-
-from ...webhooks import prepare_api_request_data
-
-
-def test_prepare_api_request_data_get():
- # given
- data = {
- "parameters": ["payload", "second_param"],
- "payment_data": "test data",
- }
-
- request_mock = mock.Mock()
- request_mock.GET = {
- "payload": "payload data",
- "second_param": "second param data",
- }
- request_mock.POST = {}
-
- # when
- request_data = prepare_api_request_data(request_mock, data)
-
- # then
- assert request_data == {
- "paymentData": data["payment_data"],
- "details": {"payload": "payload data", "second_param": "second param data"},
- }
-
-
-def test_prepare_api_request_data_post():
- # given
- data = {
- "parameters": ["payload", "second_param"],
- "payment_data": "test data",
- }
-
- request_mock = mock.Mock()
- request_mock.GET = {}
- request_mock.POST = {
- "payload": "payload data",
- "second_param": "second param data",
- }
-
- # when
- request_data = prepare_api_request_data(request_mock, data)
-
- # then
- assert request_data == {
- "paymentData": data["payment_data"],
- "details": {"payload": "payload data", "second_param": "second param data"},
- }
-
-
-def test_prepare_api_request_data_lack_of_info_in_data():
- # given
- data = {
- "parameters": ["payload", "second_param"],
- }
-
- request_mock = mock.Mock()
- request_mock.GET = {}
- request_mock.POST = {
- "payload": "payload data",
- "second_param": "second param data",
- }
-
- # when
- with pytest.raises(KeyError) as e:
- prepare_api_request_data(request_mock, data)
-
- # then
- assert (
- e._excinfo[1].args[0]
- == "Cannot perform payment. Lack of payment data and parameters information."
- )
-
-
-def test_prepare_api_request_data_lack_of_required_parameters_in_request():
- # given
- data = {
- "parameters": ["payload", "second_param"],
- "payment_data": "test data",
- }
-
- request_mock = mock.Mock()
- request_mock.GET = {}
- request_mock.POST = {
- "payload": "payload data",
- }
-
- # when
- with pytest.raises(KeyError) as e:
- prepare_api_request_data(request_mock, data)
-
- # then
- assert (
- e._excinfo[1].args[0]
- == "Cannot perform payment. Lack of required parameters in request."
- )
diff --git a/saleor/payment/gateways/adyen/tests/webhooks/test_validate_notification.py b/saleor/payment/gateways/adyen/tests/webhooks/test_validate_notification.py
deleted file mode 100644
index 9d27778ce5..0000000000
--- a/saleor/payment/gateways/adyen/tests/webhooks/test_validate_notification.py
+++ /dev/null
@@ -1,97 +0,0 @@
-from django.contrib.auth.hashers import make_password
-
-from ...webhooks import (
- validate_auth_user,
- validate_hmac_signature,
- validate_merchant_account,
-)
-
-
-def test_validate_hmac_signature(adyen_plugin, notification_with_hmac_signature):
- hmac_key = "8E60EDDCA27F96095AD5882EF0AA3B05844864710EC089B7967F796AC44AE76E"
- plugin = adyen_plugin()
- config = plugin.config
- config.connection_params["webhook_hmac"] = hmac_key
- assert validate_hmac_signature(notification_with_hmac_signature, config) is True
-
-
-def test_validate_hmac_signature_missing_key_in_saleor(
- adyen_plugin, notification_with_hmac_signature
-):
- plugin = adyen_plugin()
- config = plugin.config
- assert validate_hmac_signature(notification_with_hmac_signature, config) is False
-
-
-def test_validate_hmac_signature_missing_key_in_notification(
- adyen_plugin, notification
-):
- hmac_key = "8E60EDDCA27F96095AD5882EF0AA3B05844864710EC089B7967F796AC44AE76E"
- plugin = adyen_plugin()
- config = plugin.config
- config.connection_params["webhook_hmac"] = hmac_key
- assert validate_hmac_signature(notification(), config) is False
-
-
-def test_validate_hmac_signature_without_keys(adyen_plugin, notification):
- plugin = adyen_plugin()
- config = plugin.config
- assert validate_hmac_signature(notification(), config) is True
-
-
-def test_validate_auth_user(adyen_plugin):
- plugin = adyen_plugin()
- config = plugin.config
- config.connection_params["webhook_user"] = "[email protected]"
- password = make_password("admin")
- config.connection_params["webhook_user_password"] = password
- is_valid = validate_auth_user(
- headers={"Authorization": "Basic YWRtaW5AZXhhbXBsZS5jb206YWRtaW4="},
- gateway_config=config,
- )
- assert is_valid is True
-
-
-def validate_auth_user_when_header_is_missing(adyen_plugin):
- plugin = adyen_plugin()
- config = plugin.config
- config.connection_params["webhook_user"] = "[email protected]"
- password = make_password("admin")
- config.connection_params["webhook_user_password"] = password
- is_valid = validate_auth_user(headers={}, gateway_config=config)
- assert is_valid is False
-
-
-def test_validate_auth_user_when_user_is_missing(adyen_plugin):
- plugin = adyen_plugin()
- config = plugin.config
- is_valid = validate_auth_user(
- headers={"Authorization": "Basic YWRtaW5AZXhhbXBsZS5jb206YWRtaW4="},
- gateway_config=config,
- )
- assert is_valid is False
-
-
-def test_validate_auth_user_when_auth_is_disabled(adyen_plugin):
- plugin = adyen_plugin()
- config = plugin.config
- is_valid = validate_auth_user(headers={}, gateway_config=config)
- assert is_valid is True
-
-
-def test_validate_merchant_account(adyen_plugin, notification_with_hmac_signature):
- plugin = adyen_plugin()
- config = plugin.config
- notification_with_hmac_signature["merchantAccountCode"] = (
- config.connection_params.get("merchant_account")
- )
- assert validate_merchant_account(notification_with_hmac_signature, config) is True
-
-
-def test_validate_merchant_account_invalid_merchant_account(
- adyen_plugin, notification_with_hmac_signature
-):
- plugin = adyen_plugin()
- config = plugin.config
- notification_with_hmac_signature["merchantAccountCode"] = "test"
- assert validate_merchant_account(notification_with_hmac_signature, config) is False
diff --git a/saleor/payment/gateways/adyen/utils/__init__.py b/saleor/payment/gateways/adyen/utils/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/saleor/payment/gateways/adyen/utils/apple_pay.py b/saleor/payment/gateways/adyen/utils/apple_pay.py
deleted file mode 100644
index 211f219f3f..0000000000
--- a/saleor/payment/gateways/adyen/utils/apple_pay.py
+++ /dev/null
@@ -1,132 +0,0 @@
-import logging
-from tempfile import NamedTemporaryFile
-from urllib.parse import urlsplit
-
-import requests
-
-from .....core.http_client import HTTPClient
-from .... import PaymentError
-
-# https://developer.apple.com/documentation/apple_pay_on_the_web/
-# setting_up_your_server#3172427
-
-APPLE_DOMAINS = [
- "apple-pay-gateway.apple.com",
- "cn-apple-pay-gateway.apple.com",
- "apple-pay-gateway-nc-pod1.apple.com",
- "apple-pay-gateway-nc-pod2.apple.com",
- "apple-pay-gateway-nc-pod3.apple.com",
- "apple-pay-gateway-nc-pod4.apple.com",
- "apple-pay-gateway-nc-pod5.apple.com",
- "apple-pay-gateway-pr-pod1.apple.com",
- "apple-pay-gateway-pr-pod2.apple.com",
- "apple-pay-gateway-pr-pod3.apple.com",
- "apple-pay-gateway-pr-pod4.apple.com",
- "apple-pay-gateway-pr-pod5.apple.com",
- "cn-apple-pay-gateway-sh-pod1.apple.com",
- "cn-apple-pay-gateway-sh-pod2.apple.com",
- "cn-apple-pay-gateway-sh-pod3.apple.com",
- "cn-apple-pay-gateway-tj-pod1.apple.com",
- "cn-apple-pay-gateway-tj-pod2.apple.com",
- "cn-apple-pay-gateway-tj-pod3.apple.com",
- "apple-pay-gateway-cert.apple.com",
- "cn-apple-pay-gateway-cert.apple.com",
-]
-
-logger = logging.getLogger(__name__)
-
-
-def validate_payment_data_for_apple_pay(
- validation_url: str | None,
- merchant_identifier: str | None,
- domain: str | None,
- display_name: str | None,
- certificate,
-):
- if not certificate:
- raise PaymentError("Support for Apple Pay on the web is disabled.")
-
- required_fields = [
- (validation_url, "validationUrl"),
- (merchant_identifier, "merchantIdentifier"),
- (domain, "domain"),
- (display_name, "displayName"),
- ]
- for field, name in required_fields:
- if not field:
- raise PaymentError(f"Missing {name} in the input data.")
-
- domain = urlsplit(validation_url).netloc
- if domain not in APPLE_DOMAINS:
- raise PaymentError(
- "The domain of the validation url is not defined as an Apple Pay domain."
- )
-
-
-def initialize_apple_pay_session(
- validation_url: str,
- merchant_identifier: str,
- domain: str,
- display_name: str,
- certificate: str,
-) -> dict:
- request_data = {
- "merchantIdentifier": merchant_identifier,
- "displayName": display_name,
- "initiative": "web",
- "initiativeContext": domain,
- }
- try:
- response = make_request_to_initialize_apple_pay(
- validation_url, request_data, certificate
- )
- except requests.exceptions.RequestException as e:
- logger.warning("Failed to fetch the Apple Pay session", exc_info=True)
- raise PaymentError(
- "Unable to create Apple Pay payment session. Make sure that input data "
- " and certificate are correct."
- ) from e
- if not response.ok:
- # FIXME: shouldn't we forward some details here?
- raise PaymentError(
- "Unable to create Apple Pay payment session. Make sure that input data "
- " and certificate are correct."
- )
- return response.json()
-
-
-def make_request_to_initialize_apple_pay(
- validation_url: str, request_data: dict, certificate: str
-):
- with NamedTemporaryFile() as f:
- f.write(certificate.encode())
- f.flush() # ensure all data written
- return HTTPClient.send_request(
- "POST",
- validation_url,
- json=request_data,
- cert=f.name,
- allow_redirects=False,
- )
-
-
-def initialize_apple_pay(payment_data: dict, certificate: str) -> dict:
- # The Apple Pay on the web requires additional step
- validation_url = payment_data.get("validationUrl", "")
- merchant_identifier = payment_data.get("merchantIdentifier", "")
- domain = payment_data.get("domain", "")
- display_name = payment_data.get("displayName", "")
- validate_payment_data_for_apple_pay(
- validation_url=validation_url,
- merchant_identifier=merchant_identifier,
- domain=domain,
- display_name=display_name,
- certificate=certificate,
- )
- return initialize_apple_pay_session(
- validation_url=validation_url,
- merchant_identifier=merchant_identifier,
- domain=domain,
- display_name=display_name,
- certificate=certificate,
- )
diff --git a/saleor/payment/gateways/adyen/utils/common.py b/saleor/payment/gateways/adyen/utils/common.py
deleted file mode 100644
index 7f8c38864f..0000000000
--- a/saleor/payment/gateways/adyen/utils/common.py
+++ /dev/null
@@ -1,521 +0,0 @@
-import json
-import logging
-from collections.abc import Callable
-from decimal import Decimal
-from typing import TYPE_CHECKING, Any, Optional
-
-import Adyen
-from Adyen.httpclient import HTTPClient
-from django.conf import settings
-from django_countries.fields import Country
-from requests.exceptions import ConnectTimeout
-
-from .....checkout.calculations import (
- calculate_checkout_total,
- checkout_line_unit_price,
- checkout_shipping_price,
-)
-from .....checkout.fetch import (
- CheckoutInfo,
- CheckoutLineInfo,
- fetch_checkout_info,
- fetch_checkout_lines,
-)
-from .....checkout.models import Checkout
-from .....checkout.utils import get_checkout_metadata, is_shipping_required
-from .....core.telemetry import saleor_attributes, tracer
-from .....payment.models import Payment
-from .....plugins.manager import get_plugins_manager
-from .... import PaymentError
-from ....interface import GatewayConfig, PaymentMethodInfo
-from ....utils import price_to_minor_unit
-
-if TYPE_CHECKING:
- from ....interface import AddressData, PaymentData
-
-logger = logging.getLogger(__name__)
-
-
-# https://docs.adyen.com/checkout/payment-result-codes
-FAILED_STATUSES = ["refused", "error", "cancelled"]
-PENDING_STATUSES = ["pending", "received"]
-AUTH_STATUS = "authorised"
-
-# we'd like shorter timeout than default 30s for Adyen client,
-# library doesn't allow to set connection establ. timeout
-HTTP_TIMEOUT = 20
-
-
-def initialize_adyen_client(config: GatewayConfig) -> Adyen.Adyen:
- api_key = config.connection_params["api_key"]
-
- live_endpoint = config.connection_params.get("live")
- platform = "live" if live_endpoint else "test"
- adyen = Adyen.Adyen(
- xapikey=api_key, live_endpoint_prefix=live_endpoint, platform=platform
- )
- init_http_client(adyen)
- return adyen
-
-
-def init_http_client(adyen: Adyen.Adyen):
- adyen_client = adyen.client
- adyen_client.http_client = HTTPClient(
- user_agent_suffix=adyen_client.USER_AGENT_SUFFIX,
- lib_version=adyen_client.LIB_VERSION,
- force_request=adyen_client.http_force,
- timeout=HTTP_TIMEOUT,
- )
- adyen_client.http_init = True
-
-
-def get_tax_percentage_in_adyen_format(total_gross, total_net):
- tax_percentage_in_adyen_format = 0
- if total_gross and total_net:
- # get tax percent in adyen format
- gross_percentage = total_gross / total_net
- gross_percentage = gross_percentage.quantize(Decimal(".01")) # 1.23
- tax_percentage = gross_percentage * 100 - 100 # 23.00
- tax_percentage_in_adyen_format = int(tax_percentage * 100) # 2300
- return tax_percentage_in_adyen_format
-
-
-def api_call(
- request_data: dict[str, Any] | None, method: Callable, **kwargs
-) -> Adyen.Adyen:
- try:
- return method(request_data, **kwargs)
- except (Adyen.AdyenError, ValueError, TypeError, ConnectTimeout) as e:
- logger.warning("Unable to process the payment: %s", e)
- raise PaymentError(f"Unable to process the payment request: {e}.") from e
-
-
-def prepare_address_request_data(address: Optional["AddressData"]) -> dict | None:
- """Create address structure for Adyen request.
-
- The sample recieved from Adyen team:
-
- Customer enters only address 1: 2500 Valley Creek Way
- Ideal: houseNumberOrName: "2500", street: "Valley Creek Way"
- If above not possible: houseNumberOrName: "", street: "2500 Valley Creek Way"
-
- ***Note the blank string above
-
- Customer enters address 1 and address 2: 30 Granger Circle, 160 Bath Street
- Ideal: houseNumberOrName: "30 Granger Circle", street: "160 Bath Street"
- """
- house_number_or_name = ""
- if not address:
- return None
-
- city = address.city or address.country_area or "ZZ"
- country = str(address.country) if address.country else "ZZ"
- postal_code = address.postal_code or "ZZ"
- state_or_province = address.country_area or "ZZ"
-
- if address.company_name:
- house_number_or_name = address.company_name
- street = address.street_address_1
- if address.street_address_2:
- street += f" {address.street_address_2}"
- elif address.street_address_2:
- street = address.street_address_2
- house_number_or_name = address.street_address_1
- else:
- street = address.street_address_1
-
- return {
- "city": city,
- "country": country,
- "houseNumberOrName": house_number_or_name,
- "postalCode": postal_code,
- "stateOrProvince": state_or_province,
- "street": street,
- }
-
-
-def request_data_for_payment(
- payment_information: "PaymentData",
- return_url: str,
- merchant_account: str,
- native_3d_secure: bool,
-) -> dict[str, Any]:
- payment_data = payment_information.data or {}
-
- if not payment_data.pop("is_valid", True):
- raise PaymentError("Payment data are not valid.")
-
- extra_request_params = {}
- channel = payment_data.get("channel", "web")
- origin_url = payment_data.get("originUrl")
-
- browser_info = payment_data.get("browserInfo")
- if browser_info:
- extra_request_params["browserInfo"] = browser_info
-
- billing_address = payment_data.get("billingAddress")
- if billing_address:
- extra_request_params["billingAddress"] = billing_address
- elif billing_address := prepare_address_request_data(payment_information.billing):
- extra_request_params["billingAddress"] = billing_address
-
- delivery_address = payment_data.get("deliveryAddress")
- if delivery_address:
- extra_request_params["deliveryAddress"] = delivery_address
- elif delivery_address := prepare_address_request_data(payment_information.shipping):
- extra_request_params["deliveryAddress"] = delivery_address
-
- shopper_ip = payment_data.get("shopperIP")
- if shopper_ip:
- extra_request_params["shopperIP"] = shopper_ip
-
- device_fingerprint = payment_data.get("deviceFingerprint")
- if device_fingerprint:
- extra_request_params["deviceFingerprint"] = device_fingerprint
-
- if channel.lower() == "web" and origin_url:
- extra_request_params["origin"] = origin_url
-
- shopper_name = payment_data.get("shopperName")
- if shopper_name:
- extra_request_params["shopperName"] = shopper_name
-
- extra_request_params["channel"] = channel
-
- payment_method = payment_data.get("paymentMethod")
- if not payment_method:
- raise PaymentError("Unable to find the paymentMethod section.")
-
- method = payment_method.get("type", "")
- if native_3d_secure and "scheme" == method:
- extra_request_params["additionalData"] = {"allow3DS2": "true"}
-
- extra_request_params["shopperEmail"] = payment_information.customer_email
-
- if payment_information.billing:
- extra_request_params["shopperName"] = {
- "firstName": payment_information.billing.first_name,
- "lastName": payment_information.billing.last_name,
- }
- request_data = {
- "amount": {
- "value": price_to_minor_unit(
- payment_information.amount, payment_information.currency
- ),
- "currency": payment_information.currency,
- },
- "reference": payment_information.graphql_payment_id,
- "paymentMethod": payment_method,
- "returnUrl": return_url,
- "merchantAccount": merchant_account,
- "shopperEmail": payment_information.customer_email,
- "shopperReference": payment_information.customer_email,
- **extra_request_params,
- }
-
- methods_that_require_checkout_details = ["afterpaytouch", "clearpay"]
- # klarna in method - because there is a lot of variable klarna methods - like pay
- # later with klarna or pay with klarna etc
- if "klarna" in method or method in methods_that_require_checkout_details:
- # Some payment methods like afterpay or klarna, requires more context for
- # processing a payment. If user pick up such payment method we add more
- # checkout details to request
- request_data = append_checkout_details(payment_information, request_data)
- return request_data
-
-
-def get_shipping_data(manager, checkout_info, lines):
- address = checkout_info.shipping_address or checkout_info.billing_address
- currency = checkout_info.checkout.currency
- shipping_total = checkout_shipping_price(
- manager=manager,
- checkout_info=checkout_info,
- lines=lines,
- address=address,
- )
- total_gross = shipping_total.gross.amount
- total_net = shipping_total.net.amount
- tax_amount = shipping_total.tax.amount
- tax_percentage_in_adyen_format = get_tax_percentage_in_adyen_format(
- total_gross, total_net
- )
- return {
- "quantity": 1,
- "amountExcludingTax": price_to_minor_unit(total_net, currency),
- "taxPercentage": tax_percentage_in_adyen_format,
- "description": (
- f"Shipping - {checkout_info.get_delivery_method_info().delivery_method.name}"
- ),
- "id": f"Shipping:{checkout_info.get_delivery_method_info().delivery_method.id}",
- "taxAmount": price_to_minor_unit(tax_amount, currency),
- "amountIncludingTax": price_to_minor_unit(total_gross, currency),
- }
-
-
-def append_checkout_details(payment_information: "PaymentData", payment_data: dict):
- checkout = (
- Checkout.objects.prefetch_related(
- "shipping_method",
- )
- .filter(payments__id=payment_information.payment_id)
- .first()
- )
-
- if not checkout:
- raise PaymentError("Unable to calculate products for klarna.")
-
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- currency = payment_information.currency
- country_code = checkout.get_country()
-
- payment_data["shopperLocale"] = get_shopper_locale_value(country_code)
- payment_data["countryCode"] = country_code
-
- line_items = []
- for line_info in lines:
- unit_price = checkout_line_unit_price(
- manager=manager,
- checkout_info=checkout_info,
- lines=lines,
- checkout_line_info=line_info,
- )
- unit_gross = unit_price.gross.amount
- unit_net = unit_price.net.amount
- tax_amount = unit_price.tax.amount
- tax_percentage_in_adyen_format = get_tax_percentage_in_adyen_format(
- unit_gross, unit_net
- )
-
- line_data = {
- "quantity": line_info.line.quantity,
- "amountExcludingTax": price_to_minor_unit(unit_net, currency),
- "taxPercentage": tax_percentage_in_adyen_format,
- "description": (
- f"{line_info.variant.product.name}, {line_info.variant.name}"
- ),
- "id": line_info.variant.sku or line_info.variant.get_global_id(),
- "taxAmount": price_to_minor_unit(tax_amount, currency),
- "amountIncludingTax": price_to_minor_unit(unit_gross, currency),
- }
- line_items.append(line_data)
-
- if (
- checkout_info.get_delivery_method_info().delivery_method
- and is_shipping_required(lines)
- ):
- line_items.append(get_shipping_data(manager, checkout_info, lines))
-
- payment_data["lineItems"] = line_items
- return payment_data
-
-
-def get_shopper_locale_value(country_code: str):
- # Remove this function when "shopperLocale" will come from frontend site
- country_code_to_shopper_locale_value = {
- # https://docs.adyen.com/checkout/components-web/
- # localization-components#change-language
- "CN": "zh_CN",
- "DK": "da_DK",
- "NL": "nl_NL",
- "US": "en_US",
- "FI": "fi_FI",
- "FR": "fr_FR",
- "DR": "de_DE",
- "IT": "it_IT",
- "JP": "ja_JP",
- "KR": "ko_KR",
- "NO": "no_NO",
- "PL": "pl_PL",
- "BR": "pt_BR",
- "RU": "ru_RU",
- "ES": "es_ES",
- "SE": "sv_SE",
- }
- return country_code_to_shopper_locale_value.get(country_code, "en_US")
-
-
-def request_data_for_gateway_config(
- checkout_info: "CheckoutInfo",
- lines: list[CheckoutLineInfo] | None,
- merchant_account,
-) -> dict[str, Any]:
- manager = get_plugins_manager(allow_replica=False)
- checkout = checkout_info.checkout
- address = checkout_info.shipping_address or checkout_info.billing_address
- lines = lines or []
- total = calculate_checkout_total(
- manager=manager,
- checkout_info=checkout_info,
- lines=lines,
- address=address,
- )
-
- country = address.country if address else None
- if country:
- country_code = country.code
- else:
- country_code = Country(settings.DEFAULT_COUNTRY).code
- checkout_metadata = get_checkout_metadata(checkout)
- if checkout_metadata:
- channel = checkout_metadata.get_value_from_metadata("channel", "web")
- else:
- channel = "web"
-
- return {
- "merchantAccount": merchant_account,
- "countryCode": country_code,
- "channel": channel,
- "amount": {
- "value": price_to_minor_unit(total.gross.amount, checkout.currency),
- "currency": checkout.currency,
- },
- }
-
-
-def request_for_payment_refund(
- amount: Decimal,
- currency: str,
- graphql_payment_id: str,
- merchant_account: str,
- token: str,
-) -> dict[str, Any]:
- return {
- "merchantAccount": merchant_account,
- "modificationAmount": {
- "value": price_to_minor_unit(amount, currency),
- "currency": currency,
- },
- "originalReference": token,
- "reference": graphql_payment_id,
- }
-
-
-def request_for_payment_capture(
- payment_information: "PaymentData", merchant_account: str, token: str
-) -> dict[str, Any]:
- return {
- "merchantAccount": merchant_account,
- "modificationAmount": {
- "value": price_to_minor_unit(
- payment_information.amount, payment_information.currency
- ),
- "currency": payment_information.currency,
- },
- "originalReference": token,
- "reference": payment_information.graphql_payment_id,
- }
-
-
-def update_payment_with_action_required_data(
- payment: Payment, action: dict, details: list
-):
- action_required_data = {
- "payment_data": action["paymentData"],
- "parameters": [detail["key"] for detail in details],
- }
- if payment.extra_data:
- payment_extra_data = json.loads(payment.extra_data)
- try:
- payment_extra_data.append(action_required_data)
- extra_data = payment_extra_data
- except AttributeError:
- extra_data = [payment_extra_data, action_required_data]
- else:
- extra_data = [action_required_data]
-
- payment.extra_data = json.dumps(extra_data)
- payment.save(update_fields=["extra_data"])
-
-
-def call_refund(
- amount: Decimal,
- currency: str,
- graphql_payment_id: str,
- merchant_account: str,
- token: str,
- adyen_client: Adyen.Adyen,
-):
- request = request_for_payment_refund(
- amount,
- currency,
- graphql_payment_id,
- merchant_account=merchant_account,
- token=token,
- )
- with tracer.start_as_current_span("adyen.payment.refund") as span:
- span.set_attribute(saleor_attributes.COMPONENT, "payment")
- return api_call(request, adyen_client.payment.refund)
-
-
-def call_capture(
- payment_information: "PaymentData",
- merchant_account: str,
- token: str,
- adyen_client: Adyen.Adyen,
-):
- # https://docs.adyen.com/checkout/capture#make-an-api-call-to-capture-a-payment
-
- request = request_for_payment_capture(
- payment_information=payment_information,
- merchant_account=merchant_account,
- token=token,
- )
- with tracer.start_as_current_span("adyen.payment.capture") as span:
- span.set_attribute(saleor_attributes.COMPONENT, "payment")
- return api_call(request, adyen_client.payment.capture)
-
-
-def request_for_payment_cancel(
- payment_information: "PaymentData",
- merchant_account: str,
- token: str,
-):
- return {
- "merchantAccount": merchant_account,
- "originalReference": token,
- "reference": payment_information.graphql_payment_id,
- }
-
-
-def get_payment_method_info(
- payment_information: "PaymentData", api_call_result: Adyen.Adyen
-):
- additional_data = api_call_result.message.get("additionalData")
- payment_data = payment_information.data or {}
- payment_method = payment_data.get("paymentMethod", {}).get("type")
- brand = None
- if additional_data:
- brand = additional_data.get("paymentMethod")
- payment_method_info = PaymentMethodInfo(
- brand=brand,
- type="card" if payment_method == "scheme" else payment_method,
- )
- return payment_method_info
-
-
-def get_request_data_for_check_payment(data: dict, merchant_account: str) -> dict:
- amount_input = data["card"].get("money")
- security_code = data["card"].get("cvc")
-
- request_data: dict[str, Any] = {
- "merchantAccount": merchant_account,
- "paymentMethod": {
- "type": data["method"],
- "number": data["card"]["code"],
- },
- }
-
- if amount_input:
- currency = amount_input["currency"]
- value = amount_input["amount"]
- request_data["amount"] = {
- "value": price_to_minor_unit(value, currency),
- "currency": currency,
- }
-
- if security_code:
- request_data["paymentMethod"]["securityCode"] = security_code
-
- return request_data
diff --git a/saleor/payment/gateways/adyen/webhooks.py b/saleor/payment/gateways/adyen/webhooks.py
deleted file mode 100644
index 6dbf936d67..0000000000
--- a/saleor/payment/gateways/adyen/webhooks.py
+++ /dev/null
@@ -1,1225 +0,0 @@
-import base64
-import binascii
-import hashlib
-import hmac
-import json
-import logging
-from collections.abc import Callable, Iterable
-from decimal import Decimal
-from json.decoder import JSONDecodeError
-from typing import Any, cast
-from urllib.parse import urlencode, urlparse
-
-import Adyen
-import graphene
-from django.contrib.auth.hashers import check_password
-from django.core.exceptions import ValidationError
-from django.forms.models import model_to_dict
-from django.http import (
- HttpResponse,
- HttpResponseBadRequest,
- HttpResponseNotFound,
- QueryDict,
-)
-from django.http.request import HttpHeaders
-from django.http.response import HttpResponseRedirect
-from graphql import GraphQLError
-
-from ....checkout.calculations import calculate_checkout_total_with_gift_cards
-from ....checkout.complete_checkout import complete_checkout
-from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-from ....checkout.models import Checkout
-from ....core.prices import quantize_price
-from ....core.transactions import transaction_with_commit_on_errors
-from ....core.utils.url import prepare_url
-from ....graphql.core import SaleorContext
-from ....graphql.core.utils import from_global_id_or_error
-from ....order.actions import (
- cancel_order,
- order_authorized,
- order_charged,
- order_refunded,
-)
-from ....order.events import external_notification_event
-from ....order.fetch import fetch_order_info
-from ....payment.models import Payment, Transaction
-from ....plugins.manager import get_plugins_manager
-from ... import ChargeStatus, PaymentError, TransactionKind, gateway
-from ...gateway import payment_refund_or_void
-from ...interface import GatewayConfig, GatewayResponse
-from ...utils import (
- create_payment_information,
- create_transaction,
- gateway_postprocess,
- price_from_minor_unit,
- try_void_or_refund_inactive_payment,
-)
-from .utils.common import (
- FAILED_STATUSES,
- api_call,
- call_refund,
- initialize_adyen_client,
-)
-
-logger = logging.getLogger(__name__)
-
-
-def get_payment_id(
- payment_id: str | None,
- transaction_id: str | None = None,
-):
- if payment_id is None or not payment_id.strip():
- logger.warning("Missing payment ID. Reference %s", transaction_id)
- return None
- try:
- _type, db_payment_id = from_global_id_or_error(
- payment_id, only_type="Payment", raise_error=True
- )
- except (UnicodeDecodeError, binascii.Error, GraphQLError):
- logger.warning(
- "Unable to decode the payment ID %s. Reference %s",
- payment_id,
- transaction_id,
- )
- return None
- return db_payment_id
-
-
-def get_payment(
- payment_id: str | None,
- transaction_id: str | None = None,
- check_if_active=True,
-) -> Payment | None:
- transaction_id = transaction_id or ""
- db_payment_id = get_payment_id(payment_id)
- if not db_payment_id:
- return None
- payments = (
- Payment.objects.prefetch_related("order", "checkout")
- .select_for_update(of=("self",))
- .filter(id=db_payment_id, gateway="mirumee.payments.adyen")
- )
- if check_if_active:
- payments = payments.filter(is_active=True)
- payment = payments.first()
- if not payment:
- logger.warning(
- "Payment for %s (%s) was not found. Reference %s",
- payment_id,
- db_payment_id,
- transaction_id,
- )
- return payment
-
-
-def get_checkout(payment_id: int) -> Checkout | None:
- # Lock checkout in the same way as in checkoutComplete
- return (
- Checkout.objects.select_for_update(of=("self",))
- .prefetch_related(
- "gift_cards",
- "lines__variant__product",
- )
- .select_related("shipping_method__shipping_zone")
- .filter(payments__id=payment_id)
- .first()
- )
-
-
-def get_transaction(
- payment: "Payment",
- transaction_id: str | None,
- kind: str,
-) -> Transaction | None:
- transaction = payment.transactions.filter(kind=kind, token=transaction_id).last()
- return transaction
-
-
-def create_new_transaction(notification, payment, kind):
- transaction_id = notification.get("pspReference")
- currency = notification.get("amount", {}).get("currency")
- amount = price_from_minor_unit(
- notification.get("amount", {}).get("value"), currency
- )
- is_success = True if notification.get("success") == "true" else False
-
- gateway_response = GatewayResponse(
- kind=kind,
- action_required=False,
- transaction_id=transaction_id,
- is_success=is_success,
- amount=amount,
- currency=currency,
- error="",
- psp_reference=transaction_id,
- legacy_adyen_plugin_payment_method=notification.get("paymentMethod", "")
- .strip()
- .lower(),
- legacy_adyen_plugin_result_code=notification.get("resultCode", "")
- .strip()
- .lower(),
- )
- return create_transaction(
- payment,
- kind=kind,
- payment_information=None,
- action_required=False,
- gateway_response=gateway_response,
- )
-
-
-def create_payment_notification_for_order(
- payment: Payment, success_msg: str, failed_msg: str | None, is_success: bool
-):
- if not payment.order:
- # Order is not assigned
- return
- msg = success_msg if is_success else failed_msg
-
- external_notification_event(
- order=payment.order,
- user=None,
- app=None,
- message=msg,
- parameters={"service": payment.gateway, "id": payment.token},
- )
-
-
-def create_order(payment, checkout, manager):
- try:
- lines, unavailable_variant_pks = fetch_checkout_lines(checkout)
- if unavailable_variant_pks:
- payment_refund_or_void(payment, manager, checkout.channel.slug)
- raise ValidationError(
- "Some of the checkout lines variants are unavailable."
- )
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- checkout_total = calculate_checkout_total_with_gift_cards(
- manager=manager,
- checkout_info=checkout_info,
- lines=lines,
- address=checkout.shipping_address or checkout.billing_address,
- )
- # when checkout total value is different than total amount from payments
- # it means that some products has been removed during the payment was completed
- if checkout_total.gross.amount != payment.total:
- payment_refund_or_void(payment, manager, checkout_info.channel.slug)
- raise ValidationError(
- "Cannot create order - some products do not exist anymore."
- )
- order, _, _ = complete_checkout(
- checkout_info=checkout_info,
- lines=lines,
- manager=manager,
- payment_data={},
- store_source=False,
- user=checkout.user or None,
- app=None,
- )
- except ValidationError as e:
- logger.info(
- "Failed to create order from checkout %s.",
- checkout.pk,
- extra={"error": str(e)},
- )
- return None
- # Refresh the payment to assign the newly created order
- payment.refresh_from_db()
- return order
-
-
-def handle_not_created_order(notification, payment, checkout, kind, manager):
- """Process the notification in case when payment doesn't have assigned order."""
-
- # We don't want to create order for payment that is cancelled or refunded
- if payment.charge_status not in {
- ChargeStatus.NOT_CHARGED,
- ChargeStatus.PENDING,
- ChargeStatus.PARTIALLY_CHARGED,
- ChargeStatus.FULLY_CHARGED,
- }:
- return None
-
- transaction = create_new_transaction(
- notification, payment, TransactionKind.ACTION_TO_CONFIRM
- )
-
- # Only when we confirm that notification is success we will create the order
- if transaction.is_success and checkout:
- confirm_payment_and_set_back_to_confirm(payment, manager, checkout.channel.slug)
- payment.refresh_from_db() # refresh charge_status
- order = create_order(payment, checkout, manager)
- return order
- return None
-
-
-def handle_authorization(notification: dict[str, Any], gateway_config: GatewayConfig):
- """Handle authorization notification.
-
- Handler for processing an authorization notification from Adyen. The notification
- is async so we assume that it can be delivered in two different situations: order
- is already created, order is not created yet.
- - order is already created: we process notification and update the status of
- payment and order in case if we didn't do that previously.
- - order is not created yet: we create an order and update a payment's status.
- In case when checkout_complete raises an exception we will call a refund/void
- for a given payment.
- For both cases we will include an external event to Order history.
- No matter if Adyen has enabled auto capture on their side, we will always receive
- authorization notification. In that case, we can't determine if the payment on
- their side goes to authorization or captured status.
- """
-
- transaction_id = notification.get("pspReference")
- graphql_payment_id = notification.get("merchantReference")
- payment_id = get_payment_id(graphql_payment_id, transaction_id)
- if not payment_id:
- # We can't decode the merchantReference which should be a payment id in
- # graphql format
- return
-
- checkout = get_checkout(payment_id)
-
- payment = get_payment(
- notification.get("merchantReference"), transaction_id, check_if_active=False
- )
- if not payment:
- # We don't know anything about that payment
- return
-
- manager = get_plugins_manager(allow_replica=False)
- adyen_auto_capture = gateway_config.connection_params["adyen_auto_capture"]
- kind = TransactionKind.AUTH
- if adyen_auto_capture:
- kind = TransactionKind.CAPTURE
-
- amount = notification.get("amount", {})
- try:
- notification_payment_amount = price_from_minor_unit(
- amount.get("value"), amount.get("currency")
- )
- except TypeError:
- logger.exception("Cannot convert amount from minor unit")
- return
-
- if notification_payment_amount < payment.total:
- # If amount from the notification is lower than payment total then we have
- # a partial payment so we create an order in separate webhook (order_closed)
- # after payment finished.
- logger.info(
- "This is a partial payment notification. We can't create an order. pspReference: %s, paymentId: %x",
- transaction_id,
- payment.pk,
- )
- return
-
- transaction = get_transaction(payment, transaction_id, kind)
-
- if not payment.is_active:
- if not transaction:
- transaction = create_new_transaction(notification, payment, kind)
- transaction = cast(Transaction, transaction)
- try_void_or_refund_inactive_payment(payment, transaction, manager)
- return
-
- if not transaction:
- if not payment.order:
- handle_not_created_order(notification, payment, checkout, kind, manager)
- else:
- new_transaction = create_new_transaction(notification, payment, kind)
- if new_transaction.is_success:
- gateway_postprocess(new_transaction, payment)
- if adyen_auto_capture:
- order_info = fetch_order_info(payment.order)
- order_charged(
- order_info,
- None,
- None,
- new_transaction.amount,
- payment,
- manager,
- )
- else:
- order_authorized(
- payment.order,
- None,
- None,
- new_transaction.amount,
- payment,
- manager,
- )
-
- reason = notification.get("reason", "-")
- is_success = True if notification.get("success") == "true" else False
- success_msg = f"Adyen: The payment {transaction_id} request was successful."
- failed_msg = (
- f"Adyen: The payment {transaction_id} request failed. Reason: {reason}."
- )
- create_payment_notification_for_order(payment, success_msg, failed_msg, is_success)
-
-
-def handle_cancellation(
- notification: dict[str, Any],
- _gateway_config: GatewayConfig,
-):
- # https://docs.adyen.com/checkout/cancel#cancellation-notifciation
- transaction_id = notification.get("pspReference")
- payment = get_payment(
- # check_if_active=False as the payment can be still active or already cancelled
- notification.get("merchantReference"),
- transaction_id,
- check_if_active=False,
- )
- if not payment:
- return
- transaction = get_transaction(payment, transaction_id, TransactionKind.CANCEL)
- if transaction and transaction.is_success:
- # it is already cancelled
- return
- new_transaction = create_new_transaction(
- notification, payment, TransactionKind.CANCEL
- )
- gateway_postprocess(new_transaction, payment)
-
- reason = notification.get("reason", "-")
- success_msg = f"Adyen: The cancel {transaction_id} request was successful."
- failed_msg = f"Adyen: The cancel {transaction_id} request failed. Reason: {reason}"
- create_payment_notification_for_order(
- payment, success_msg, failed_msg, new_transaction.is_success
- )
- if payment.order and new_transaction.is_success:
- manager = get_plugins_manager(allow_replica=False)
- cancel_order(payment.order, None, None, manager)
-
-
-def handle_cancel_or_refund(
- notification: dict[str, Any], gateway_config: GatewayConfig
-):
- # https://docs.adyen.com/checkout/cancel-or-refund#cancel-or-refund-notification
- additional_data = notification.get("additionalData")
- if not additional_data:
- return
- action = additional_data.get("modification.action")
- if action == "refund":
- handle_refund(notification, gateway_config)
- elif action == "cancel":
- handle_cancellation(notification, gateway_config)
-
-
-def handle_capture(notification: dict[str, Any], _gateway_config: GatewayConfig):
- # https://docs.adyen.com/checkout/capture#capture-notification
- transaction_id = notification.get("pspReference")
- graphql_payment_id = notification.get("merchantReference")
-
- payment_id = get_payment_id(graphql_payment_id, transaction_id)
- if not payment_id:
- return
- checkout = get_checkout(payment_id)
-
- payment = get_payment(graphql_payment_id, transaction_id, check_if_active=False)
- if not payment:
- return
-
- manager = get_plugins_manager(allow_replica=False)
-
- transaction = get_transaction(payment, transaction_id, TransactionKind.CAPTURE)
-
- if not payment.is_active:
- if not transaction:
- transaction = create_new_transaction(
- notification, payment, TransactionKind.CAPTURE
- )
- transaction = cast(Transaction, transaction)
- try_void_or_refund_inactive_payment(payment, transaction, manager)
- return
-
- if not transaction:
- if not payment.order:
- handle_not_created_order(
- notification, payment, checkout, TransactionKind.CAPTURE, manager
- )
- else:
- new_transaction = create_new_transaction(
- notification, payment, TransactionKind.CAPTURE
- )
- if new_transaction.is_success:
- gateway_postprocess(new_transaction, payment)
- order_info = fetch_order_info(payment.order)
- order_charged(
- order_info, None, None, new_transaction.amount, payment, manager
- )
-
- reason = notification.get("reason", "-")
- is_success = True if notification.get("success") == "true" else False
- success_msg = f"Adyen: The capture {transaction_id} request was successful."
- failed_msg = f"Adyen: The capture {transaction_id} request failed. Reason: {reason}"
- create_payment_notification_for_order(payment, success_msg, failed_msg, is_success)
-
-
-def handle_failed_capture(notification: dict[str, Any], _gateway_config: GatewayConfig):
- # https://docs.adyen.com/checkout/capture#failed-capture
- transaction_id = notification.get("pspReference")
- payment = get_payment(
- notification.get("merchantReference"), transaction_id, check_if_active=False
- )
- if not payment:
- return
-
- transaction = get_transaction(
- payment, transaction_id, TransactionKind.CAPTURE_FAILED
- )
- if transaction and transaction.is_success:
- # it is already failed
- return
- new_transaction = create_new_transaction(
- notification, payment, TransactionKind.CAPTURE_FAILED
- )
- gateway_postprocess(new_transaction, payment)
-
- reason = notification.get("reason", "-")
- msg = (
- f"Adyen: The capture for {transaction_id} failed due to a technical issue. "
- f"Reason: {reason}"
- )
- create_payment_notification_for_order(payment, msg, None, True)
-
-
-def handle_pending(notification: dict[str, Any], gateway_config: GatewayConfig):
- # https://docs.adyen.com/development-resources/webhooks/understand-notifications#
- # event-codes"
- transaction_id = notification.get("pspReference")
- payment = get_payment(
- notification.get("merchantReference"), transaction_id, check_if_active=False
- )
- if not payment:
- return
- transaction = get_transaction(payment, transaction_id, TransactionKind.PENDING)
- if transaction and transaction.is_success:
- # it is already pending
- return
- new_transaction = create_new_transaction(
- notification, payment, TransactionKind.PENDING
- )
- gateway_postprocess(new_transaction, payment)
-
- reason = notification.get("reason", "-")
- msg = f"Adyen: The transaction {transaction_id} is pending. Reason: {reason}"
- create_payment_notification_for_order(
- payment, msg, None, new_transaction.is_success
- )
-
-
-def handle_refund(notification: dict[str, Any], _gateway_config: GatewayConfig):
- # https://docs.adyen.com/checkout/refund#refund-notification
- transaction_id = notification.get("pspReference")
- payment = get_payment(
- notification.get("merchantReference"), transaction_id, check_if_active=False
- )
- if not payment:
- return
-
- transaction = get_transaction(payment, transaction_id, TransactionKind.REFUND)
- if not transaction or not transaction.already_processed:
- if not transaction:
- transaction = create_new_transaction(
- notification, payment, TransactionKind.REFUND
- )
- gateway_postprocess(transaction, payment)
- else:
- # it is already refunded
- return
- transaction = cast(Transaction, transaction)
- reason = notification.get("reason", "-")
- success_msg = f"Adyen: The refund {transaction_id} request was successful."
- failed_msg = f"Adyen: The refund {transaction_id} request failed. Reason: {reason}"
- create_payment_notification_for_order(
- payment, success_msg, failed_msg, transaction.is_success
- )
- if payment.order and transaction.is_success:
- order_refunded(
- payment.order,
- None,
- None,
- transaction.amount,
- payment,
- get_plugins_manager(allow_replica=False),
- )
-
-
-def _get_kind(transaction: Transaction | None) -> str:
- if transaction:
- return transaction.kind
- # To proceed the refund we already need to have the capture status so we will use it
- return TransactionKind.CAPTURE
-
-
-def handle_failed_refund(notification: dict[str, Any], gateway_config: GatewayConfig):
- # https://docs.adyen.com/checkout/refund#failed-refund
- transaction_id = notification.get("pspReference")
- payment = get_payment(
- notification.get("merchantReference"), transaction_id, check_if_active=False
- )
- if not payment:
- return
-
- # take the last status of payment before we tried to perform the refund
- last_transaction = payment.transactions.filter(
- action_required=False,
- is_success=True,
- kind__in=[TransactionKind.AUTH, TransactionKind.CAPTURE],
- ).last()
- last_kind = _get_kind(last_transaction)
-
- refund_transaction = payment.transactions.filter(
- token=transaction_id,
- kind__in=[
- TransactionKind.REFUND_ONGOING,
- TransactionKind.REFUND,
- TransactionKind.REFUND_FAILED,
- ],
- ).last()
-
- reason = notification.get("reason", "-")
- msg = (
- f"Adyen: The refund {transaction_id} failed due to a technical issue. If you"
- f" receive more than two failures on the same refund, contact Adyen Support "
- f"Team. Reason: {reason}"
- )
- create_payment_notification_for_order(payment, msg, None, True)
-
- if not refund_transaction:
- # we don't know anything about refund so we have to skip the notification about
- # failed refund.
- return
- if refund_transaction.kind == TransactionKind.REFUND_FAILED:
- # The failed refund is already saved
- return
-
- if refund_transaction.kind == TransactionKind.REFUND_ONGOING:
- # create new failed transaction which will allows us to discover duplicated
- # notification
- create_new_transaction(notification, payment, TransactionKind.REFUND_FAILED)
-
- # Refund ongoing doesnt do any action on payment.capture_amount so we set
- # 0 to amount. Thanks to it we can create transaction with the same status and
- # no worries that we will capture total in payment two times.
- # (if gateway_postprocess gets transaction with capture it will subtract the
- # amount from transaction
- notification["amount"]["value"] = 0
- new_transaction = create_new_transaction(notification, payment, last_kind)
- gateway_postprocess(new_transaction, payment)
- elif refund_transaction.kind == TransactionKind.REFUND:
- # create new failed transaction which will allows us to discover duplicated
- # notification
- create_new_transaction(notification, payment, TransactionKind.REFUND_FAILED)
- new_transaction = create_new_transaction(
- notification, payment, TransactionKind.CAPTURE
- )
- gateway_postprocess(new_transaction, payment)
-
-
-def handle_reversed_refund(
- notification: dict[str, Any], _gateway_config: GatewayConfig
-):
- # https://docs.adyen.com/checkout/refund#failed-refund
- transaction_id = notification.get("pspReference")
- payment = get_payment(
- notification.get("merchantReference"), transaction_id, check_if_active=False
- )
- if not payment:
- return
- transaction = get_transaction(
- payment, transaction_id, TransactionKind.REFUND_REVERSED
- )
-
- if transaction:
- # it is already refunded
- return
- new_transaction = create_new_transaction(
- notification, payment, TransactionKind.REFUND_REVERSED
- )
- gateway_postprocess(new_transaction, payment)
-
- reason = notification.get("reason", "-")
- msg = (
- f"Adyen: The refunded amount from {transaction_id} has been returned to Adyen, "
- f"and is back in your account. This may happen if the shopper's bank account "
- f"is no longer valid. Reason: {reason}"
- )
- create_payment_notification_for_order(payment, msg, msg, True)
-
-
-def handle_refund_with_data(
- notification: dict[str, Any], gateway_config: GatewayConfig
-):
- # https://docs.adyen.com/checkout/refund#refund-with-data
- handle_refund(notification, gateway_config)
-
-
-def webhook_not_implemented(
- notification: dict[str, Any], gateway_config: GatewayConfig
-):
- adyen_id = notification.get("pspReference")
- success = notification.get("success", True)
- event = notification.get("eventCode")
- transaction_id = notification.get("pspReference")
- payment = get_payment(notification.get("merchantReference"), transaction_id)
- if not payment:
- return
- msg = (
- f"Received not implemented notification from Adyen. Event name: {event}, "
- f"success: {success}, adyen reference: {adyen_id}."
- )
- create_payment_notification_for_order(payment, msg, None, True)
-
-
-def handle_order_opened(notification: dict[str, Any], gateway_config: GatewayConfig):
- # From Adyen's documentation:
- # Sent when the first payment for your payment request is a partial payment, and an
- # order has been created.
- #
- # In this case we just logging here that we received the webhook properly.
- logger.info("First payment request as a partial payment. %s", notification)
-
-
-def get_or_create_adyen_partial_payments(
- notification: dict[str, Any], payment: Payment
-) -> list[Payment] | None:
- """Store basic data about partial payments created by Adyen.
-
- This is a workaround for not supporting partial payments in Saleor. Adyen can
- handle partial payments on their side and send us info about them. We want to
- somehow store some basic information about this but without modifying a whole
- Saleor logic. We're going to change it by introducing partial payments feature on
- Saleor side.
- """
- additional_data = notification.get("additionalData", {})
- new_payments = []
- currency = payment.currency
- payment_total_to_cover = payment.total
- for (
- payment_method_key,
- payment_amount_key,
- psp_reference_key,
- ) in get_adyen_partial_payment_keys(additional_data):
- # payment amount key has structure - "{currency} {amount}", like 'GBP 41.90',
- # for payments with 3d secure, the last payment could not have an amount field,
- # in that case we need to handle it on our side.
- if payment_amount_key in additional_data:
- currency, amount = additional_data[payment_amount_key].split()
- amount = Decimal(amount)
- else:
- amount = quantize_price(max(payment_total_to_cover, Decimal(0)), currency)
-
- new_payment = Payment(**model_to_dict(payment, exclude=["id", "checkout"]))
- new_payment.checkout_id = payment.checkout_id
- new_payment.is_active = False
- new_payment.partial = True
- new_payment.total = Decimal(amount)
- # Increasing captured amount increases a total paid of the order.
- new_payment.captured_amount = 0
- new_payment.currency = currency
- new_payment.payment_method_type = additional_data.get(
- payment_method_key, "givex"
- )
- new_payment.psp_reference = additional_data.get(psp_reference_key, "")
- new_payment.extra_data = json.dumps({"parent_payment_id": payment.id})
- new_payments.append(new_payment)
-
- # For some last partial payments Adyen doesn't send an amount field. We need to
- # figure it out somehow, we calculate the total of amount covered by previous
- # payments.
- payment_total_to_cover -= new_payment.total
-
- already_existing_partial_payments = (
- Payment.objects.filter(
- psp_reference__in=[p.psp_reference for p in new_payments],
- partial=True,
- checkout_id=payment.checkout_id,
- )
- if payment.checkout_id
- else []
- )
- if already_existing_partial_payments:
- return list(already_existing_partial_payments)
-
- if new_payments:
- return Payment.objects.bulk_create(new_payments)
- return None
-
-
-def create_order_event_about_adyen_partial_payments(
- adyen_partial_payments: Iterable[Payment], payment
-):
- msg = "Adyen: "
-
- for payment in adyen_partial_payments:
- payment_method = payment.payment_method_type
- payment_amount = payment.total
- psp_reference = payment.psp_reference
- currency = payment.currency
- msg += (
- f"Partial payment with {payment_method} (PSP: {psp_reference}) "
- f"for {currency} {payment_amount}.\n"
- )
- if adyen_partial_payments:
- payment.refresh_from_db()
- create_payment_notification_for_order(
- payment, msg, failed_msg=None, is_success=True
- )
-
-
-def get_adyen_partial_payment_keys(additiona_data):
- """Get keys that contains adyen partial data.
-
- The data received from Adyen has strange structure. In middle of dict key, there is
- a int number pointing to the given payment method. So we need to convert it and
- match somehow a paymentMethod, paymentAmount and payment psp reference
- """
- index = 1
- while True:
- payment_method_key = f"order-{index}-paymentMethod"
- payment_amount_key = f"order-{index}-paymentAmount"
- psp_reference_key = f"order-{index}-pspReference"
-
- # stop iterating when there is no more an additional payment method fields
- if payment_method_key not in additiona_data:
- return
- yield (payment_method_key, payment_amount_key, psp_reference_key)
- index += 1
-
-
-def refund_partial_payments(payments, config):
- for payment in payments:
- adyen_client = initialize_adyen_client(config)
- merchant_account = config.connection_params["merchant_account"]
- logger.info("Calling refund for partial payment: %s", payment.psp_reference)
- call_refund(
- amount=payment.total,
- currency=payment.currency,
- merchant_account=merchant_account,
- token=payment.psp_reference,
- graphql_payment_id=graphene.Node.to_global_id("Payment", payment.pk),
- adyen_client=adyen_client,
- )
-
-
-def handle_order_closed(notification: dict[str, Any], gateway_config: GatewayConfig):
- # From Adyen's documentation:
- # The success field informs you of the outcome of the shopper's last payment when
- # paying for an order in partial payments.
- #
- # Possible values:
- # true: The full amount has been paid.
- # false: The shopper did not pay the full amount within the sessionValidity.
- # All partial payments that were processed previously are automatically cancelled
- # or refunded.
- is_success = True if notification.get("success") == "true" else False
- psp_reference = notification.get("pspReference")
- logger.info(
- "Partial payment has been finished with result: %s. pspReference: %s",
- is_success,
- psp_reference,
- )
-
- if not is_success:
- logger.info(
- "The shopper did not pay the full amount within the "
- "sessionValidity. All partial payments that were processed "
- "previously are automatically cancelled or refunded by Adyen."
- )
- return
- payment = get_payment(
- notification.get("merchantReference"), psp_reference, check_if_active=False
- )
-
- if not payment:
- # We don't know anything about that payment
- logger.info("There is no payment with pspReference: %s", psp_reference)
- return
-
- if payment.order:
- logger.info("Order already created for payment: %s", payment.pk)
- return
-
- adyen_partial_payments = get_or_create_adyen_partial_payments(notification, payment)
- if not payment.is_active:
- logger.info(
- "Immediately refund an Adyen payments: %s as payment %s is not active."
- )
- refund_partial_payments(adyen_partial_payments, config=gateway_config)
- return
-
- checkout = payment.checkout
-
- adyen_auto_capture = gateway_config.connection_params["adyen_auto_capture"]
- kind = TransactionKind.CAPTURE if adyen_auto_capture else TransactionKind.AUTH
-
- order = None
- try:
- order = handle_not_created_order(
- notification,
- payment,
- checkout,
- kind,
- get_plugins_manager(allow_replica=False),
- )
- except Exception:
- logger.exception("Exception during order creation")
- return
- finally:
- if not order and adyen_partial_payments:
- refund_partial_payments(adyen_partial_payments, config=gateway_config)
- # There is a possibility that user will try once again to pay with partial
- # payments, we update partial objects, as we agree that partial==True points
- # always to valid payments. This is temporary workaround to handle Adyen
- # partial payments in 3.0, and will be properly handled in partial payment
- # feature.
- Payment.objects.filter(
- id__in=[p.id for p in adyen_partial_payments]
- ).update(partial=False)
-
- if adyen_partial_payments:
- create_order_event_about_adyen_partial_payments(adyen_partial_payments, payment)
- else:
- reason = notification.get("reason", "-")
- success_msg = f"Adyen: The payment {psp_reference} request was successful."
- failed_msg = (
- f"Adyen: The payment {psp_reference} request failed. Reason: {reason}."
- )
- create_payment_notification_for_order(
- payment, success_msg, failed_msg, is_success
- )
-
-
-EVENT_MAP = {
- "AUTHORISATION": handle_authorization,
- "AUTHORISATION_ADJUSTMENT": webhook_not_implemented,
- "CANCELLATION": handle_cancellation,
- "CANCEL_OR_REFUND": handle_cancel_or_refund,
- "CAPTURE": handle_capture,
- "CAPTURE_FAILED": handle_failed_capture,
- "HANDLED_EXTERNALLY": webhook_not_implemented,
- "ORDER_OPENED": handle_order_opened,
- "ORDER_CLOSED": handle_order_closed,
- "PENDING": handle_pending,
- "PROCESS_RETRY": webhook_not_implemented,
- "REFUND": handle_refund,
- "REFUND_FAILED": handle_failed_refund,
- "REFUNDED_REVERSED": handle_reversed_refund,
- "REFUND_WITH_DATA": handle_refund_with_data,
- "REPORT_AVAILABLE": webhook_not_implemented,
- "VOID_PENDING_REFUND": webhook_not_implemented,
-}
-
-
-def validate_hmac_signature(
- notification: dict[str, Any], gateway_config: "GatewayConfig"
-) -> bool:
- hmac_signature: str | None = notification.get("additionalData", {}).get(
- "hmacSignature"
- )
- hmac_key: str | None = gateway_config.connection_params.get("webhook_hmac")
- if not hmac_key:
- return not hmac_signature
-
- if not hmac_signature:
- return False
-
- hmac_key = hmac_key.encode()
-
- success = "true" if notification.get("success", "") == "true" else "false"
- if notification.get("success", None) is None:
- success = ""
-
- payload_list = [
- notification.get("pspReference", ""),
- notification.get("originalReference", ""),
- notification.get("merchantAccountCode", ""),
- notification.get("merchantReference", ""),
- str(notification.get("amount", {}).get("value", "")),
- notification.get("amount", {}).get("currency", ""),
- notification.get("eventCode", ""),
- success,
- ]
- payload = ":".join(payload_list)
-
- hmac_key = binascii.a2b_hex(hmac_key)
- hm = hmac.new(hmac_key, payload.encode("utf-8"), hashlib.sha256)
- expected_merchant_sign = base64.b64encode(hm.digest())
- return hmac.compare_digest(hmac_signature, expected_merchant_sign.decode("utf-8"))
-
-
-def validate_auth_user(headers: HttpHeaders, gateway_config: "GatewayConfig") -> bool:
- username = gateway_config.connection_params["webhook_user"]
- password = gateway_config.connection_params["webhook_user_password"]
- auth_header: str | None = headers.get("Authorization")
- if not auth_header:
- if not username:
- return True
- return False
- if not username:
- return False
-
- split_auth = auth_header.split(maxsplit=1)
- prefix = "BASIC"
-
- if len(split_auth) != 2 or split_auth[0].upper() != prefix:
- return False
-
- auth = split_auth[1]
- try:
- decoded_auth = base64.b64decode(auth).decode()
- request_username, request_password = decoded_auth.split(":")
- user_is_correct = request_username == username
- if user_is_correct and check_password(request_password, password):
- return True
- except binascii.Error:
- pass
- return False
-
-
-def validate_merchant_account(
- notification: dict[str, Any], gateway_config: "GatewayConfig"
-):
- merchant_account_code = notification.get("merchantAccountCode")
- return merchant_account_code == gateway_config.connection_params.get(
- "merchant_account"
- )
-
-
-@transaction_with_commit_on_errors()
-def handle_webhook(request: SaleorContext, gateway_config: "GatewayConfig"):
- try:
- json_data = json.loads(request.body)
- except JSONDecodeError:
- logger.warning("Cannot parse request body.")
- return HttpResponse("[accepted]")
- # JSON and HTTP POST notifications always contain a single NotificationRequestItem
- # object.
- notification = json_data.get("notificationItems")[0].get(
- "NotificationRequestItem", {}
- )
-
- if not validate_merchant_account(notification, gateway_config):
- logger.warning("Not supported merchant account.")
- return HttpResponse("[accepted]")
- if not validate_hmac_signature(notification, gateway_config):
- return HttpResponseBadRequest("Invalid or missing hmac signature.")
- if not validate_auth_user(request.headers, gateway_config):
- return HttpResponseBadRequest("Invalid or missing basic auth.")
-
- event_handler = EVENT_MAP.get(notification.get("eventCode", ""))
- if event_handler:
- event_handler(notification, gateway_config)
- return HttpResponse("[accepted]")
- return HttpResponse("[accepted]")
-
-
-class HttpResponseRedirectWithTrustedProtocol(HttpResponseRedirect):
- def __init__(self, redirect_to: str, *args, **kwargs) -> None:
- parsed = urlparse(redirect_to)
- self.allowed_schemes = [parsed.scheme]
- super().__init__(redirect_to, *args, **kwargs)
-
-
-@transaction_with_commit_on_errors()
-def handle_additional_actions(
- request: SaleorContext, payment_details: Callable, channel_slug: str
-):
- """Handle redirect with additional actions.
-
- When a customer uses a payment method with redirect, before customer is redirected
- back to storefront, the request goes through the Saleor. We use the data received
- from Adyen, as a query params or as a post data, to finalize an additional action.
- After that, if payment doesn't require any additional action we create an order.
- In case if action data exists, we don't create an order and we include them in url.
- """
- payment_id = request.GET.get("payment")
- checkout_pk = request.GET.get("checkout")
-
- if not payment_id or not checkout_pk:
- logger.warning(
- "Missing payment_id or checkout id in Adyen's request.",
- extra={"payment_id": payment_id, "checkout_id": checkout_pk},
- )
- return HttpResponseNotFound()
- db_payment_id = get_payment_id(payment_id)
- checkout = get_checkout(db_payment_id)
- payment = get_payment(payment_id, transaction_id=None)
- if not payment:
- logger.warning(
- "Payment doesn't exist or is not active.", extra={"payment_id": payment_id}
- )
- return HttpResponseNotFound(
- "Cannot perform payment. There is no active Adyen payment."
- )
-
- # Adyen for some payment methods can call success notification before we will
- # call an additional_action.
- if not payment.order_id:
- if not checkout or str(checkout.token) != checkout_pk:
- logger.warning(
- "There is no checkout with this payment.",
- extra={"checkout_pk": checkout_pk, "payment_id": payment_id},
- )
- return HttpResponseNotFound(
- "Cannot perform payment. There is no checkout with this payment."
- )
-
- extra_data = json.loads(payment.extra_data)
- data = extra_data[-1] if isinstance(extra_data, list) else extra_data
-
- return_url = payment.return_url
-
- if not return_url:
- logger.warning(
- "Missing return_url for payment.",
- extra={"payment_id": payment_id, "checkout_pk": checkout_pk},
- )
- return HttpResponseNotFound(
- "Cannot perform payment. Lack of data about returnUrl."
- )
-
- try:
- request_data = prepare_api_request_data(request, data)
- except KeyError as e:
- return HttpResponseBadRequest(e.args[0])
- try:
- result = api_call(request_data, payment_details)
- except PaymentError as e:
- return HttpResponseBadRequest(str(e))
- handle_api_response(payment, checkout, result, channel_slug)
- redirect_url = prepare_redirect_url(payment_id, checkout_pk, result, return_url)
- return HttpResponseRedirectWithTrustedProtocol(redirect_url)
-
-
-def prepare_api_request_data(request: SaleorContext, data: dict):
- if "parameters" not in data or "payment_data" not in data:
- raise KeyError(
- "Cannot perform payment. Lack of payment data and parameters information."
- )
-
- params = data["parameters"]
- request_data: QueryDict = QueryDict("")
-
- if all(param in request.GET for param in params):
- request_data = request.GET
- elif all(param in request.POST for param in params):
- request_data = request.POST
-
- if not request_data:
- raise KeyError(
- "Cannot perform payment. Lack of required parameters in request."
- )
-
- api_request_data = {
- "paymentData": data["payment_data"],
- "details": {key: request_data[key] for key in params},
- }
- return api_request_data
-
-
-def prepare_redirect_url(
- payment_id: str, checkout_pk: str, api_response: Adyen.Adyen, return_url: str
-):
- checkout_id = graphene.Node.to_global_id("Checkout", checkout_pk)
-
- params = {
- "checkout": checkout_id,
- "payment": payment_id,
- "resultCode": api_response.message["resultCode"],
- }
-
- # Check if further action is needed.
- if "action" in api_response.message:
- params.update(api_response.message["action"])
-
- return prepare_url(urlencode(params), return_url)
-
-
-def handle_api_response(
- payment: Payment,
- checkout: Checkout | None,
- response: Adyen.Adyen,
- channel_slug: str,
-):
- payment_data = create_payment_information(
- payment=payment,
- payment_token=payment.token,
- )
- payment_brand = response.message.get("additionalData", {}).get("paymentMethod")
- if payment_brand:
- payment.cc_brand = payment_brand
- payment.save(update_fields=["cc_brand"])
-
- error_message = response.message.get("refusalReason")
-
- result_code = response.message["resultCode"].strip().lower()
- is_success = result_code not in FAILED_STATUSES
-
- action_required = False
- if "action" in response.message:
- action_required = True
-
- gateway_response = GatewayResponse(
- is_success=is_success,
- action_required=action_required,
- kind=TransactionKind.ACTION_TO_CONFIRM,
- amount=payment_data.amount,
- currency=payment_data.currency,
- transaction_id=response.message.get("pspReference", ""),
- error=error_message,
- action_required_data=response.message.get("action"),
- psp_reference=response.message.get("pspReference", ""),
- legacy_adyen_plugin_payment_method=response.message.get("paymentMethod", "")
- .strip()
- .lower(),
- legacy_adyen_plugin_result_code=response.message.get("resultCode", "")
- .strip()
- .lower(),
- )
-
- create_transaction(
- payment=payment,
- kind=TransactionKind.ACTION_TO_CONFIRM,
- action_required=action_required,
- payment_information=payment_data,
- gateway_response=gateway_response,
- )
- if is_success and not action_required and not payment.order and checkout:
- manager = get_plugins_manager(allow_replica=False)
-
- confirm_payment_and_set_back_to_confirm(payment, manager, channel_slug)
- payment.refresh_from_db() # refresh charge_status
-
- adyen_partial_payments = get_or_create_adyen_partial_payments(
- response.message, payment
- )
-
- create_order(payment, checkout, manager)
-
- if adyen_partial_payments:
- create_order_event_about_adyen_partial_payments(
- adyen_partial_payments, payment
- )
-
-
-def confirm_payment_and_set_back_to_confirm(payment, manager, channel_slug):
- # The workaround for refund payments when something will crash in
- # `create_order` function before processing a payment.
- # At this moment we have a payment processed on Adyen side but we have to do
- # something more on Saleor side (ACTION_TO_CONFIRM), it's create an order in
- # this case, so before try to create the order we have to confirm the payment
- # and force change the flag to_confirm to True again.
- #
- # This is because we have to handle 2 flows:
- # 1. Having confirmed payment to refund easily when we can't create an order.
- # 2. Do not process payment again when `complete_checkout` logic will execute
- # in `create_order` without errors. We just receive a processed transaction
- # then.
- #
- # This fix is related to SALEOR-4777. PR #8471
- gateway.confirm(payment, manager, channel_slug)
- payment.to_confirm = True
- payment.save(update_fields=["to_confirm"])
diff --git a/saleor/payment/interface.py b/saleor/payment/interface.py
index 292b429ece..efb90ff7fd 100644
--- a/saleor/payment/interface.py
+++ b/saleor/payment/interface.py
@@ -324,11 +324,6 @@ class GatewayResponse:
transaction_already_processed: bool = False
psp_reference: str | None = None
- # Temporary pass Adyen-plugin-specific data to model, so we can drop raw_response
- # After the plugin is gone, this should be removed
- legacy_adyen_plugin_result_code: str | None = None
- legacy_adyen_plugin_payment_method: str | None = None
-
@dataclass
class AddressData:
diff --git a/saleor/payment/migrations/0070_alter_payment_partial_add_db_default.py b/saleor/payment/migrations/0070_alter_payment_partial_add_db_default.py
new file mode 100644
index 0000000000..a1f27cacac
--- /dev/null
+++ b/saleor/payment/migrations/0070_alter_payment_partial_add_db_default.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.11 on 2026-03-11 12:07
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("payment", "0069_transactionitem_gc_fields"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="payment",
+ name="partial",
+ field=models.BooleanField(db_default=False, default=False),
+ ),
+ ]
diff --git a/saleor/payment/migrations/0071_remove_legacy_adyen_plugin_fields_from_orm.py b/saleor/payment/migrations/0071_remove_legacy_adyen_plugin_fields_from_orm.py
new file mode 100644
index 0000000000..53f7dc7678
--- /dev/null
+++ b/saleor/payment/migrations/0071_remove_legacy_adyen_plugin_fields_from_orm.py
@@ -0,0 +1,31 @@
+# Generated by Django 5.2.11 on 2026-03-11 12:08
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ (
+ "payment",
+ "0070_alter_payment_partial_add_db_default",
+ ),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.RemoveField(
+ model_name="payment",
+ name="partial",
+ ),
+ migrations.RemoveField(
+ model_name="transaction",
+ name="legacy_adyen_plugin_payment_method",
+ ),
+ migrations.RemoveField(
+ model_name="transaction",
+ name="legacy_adyen_plugin_result_code",
+ ),
+ ],
+ )
+ ]
diff --git a/saleor/payment/model_helpers.py b/saleor/payment/model_helpers.py
index e0d3e655d6..988f1a80f4 100644
--- a/saleor/payment/model_helpers.py
+++ b/saleor/payment/model_helpers.py
@@ -10,11 +10,7 @@ if TYPE_CHECKING:
def get_last_payment(payments: Iterable[Payment]):
- # Skipping a partial payment is a temporary workaround for storing a basic data
- # about partial payment from Adyen plugin. This is something that will removed in
- # 3.1 by introducing a partial payments feature
- valid_payments = [payment for payment in payments if not payment.partial]
- return max(valid_payments, default=None, key=attrgetter("pk"))
+ return max(payments, default=None, key=attrgetter("pk"))
def get_total_authorized(payments: Iterable[Payment], fallback_currency: str):
diff --git a/saleor/payment/models.py b/saleor/payment/models.py
index b3f2e10569..c78acd8de1 100644
--- a/saleor/payment/models.py
+++ b/saleor/payment/models.py
@@ -282,7 +282,6 @@ class Payment(ModelWithMetadata):
gateway = models.CharField(max_length=255)
is_active = models.BooleanField(default=True)
to_confirm = models.BooleanField(default=False)
- partial = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
charge_status = models.CharField(
@@ -485,18 +484,6 @@ class Transaction(models.Model):
gateway_response = JSONField(encoder=DjangoJSONEncoder)
already_processed = models.BooleanField(default=False)
- """
- Legacy fields that allow Adyen plugin to work until it's removed.
-
- Previously Adyen plugin was using gateway_response which holds entire response for every Payment plugin.
- Adyen plugin is the only plugin using this field, it has access to result_code and payment_method.
-
- To remove gateway_response we introduce two legacy fields that Adyen can write to and gateway_response can be removed.
- Once plugin is removed, these fields should be removed from the model.
- """
- legacy_adyen_plugin_result_code = models.TextField(null=True)
- legacy_adyen_plugin_payment_method = models.TextField(null=True)
-
class Meta:
ordering = ("pk",)
indexes = [
diff --git a/saleor/payment/tests/fixtures/gateway_response.py b/saleor/payment/tests/fixtures/gateway_response.py
index b250ba5ee8..bdfbea6ff2 100644
--- a/saleor/payment/tests/fixtures/gateway_response.py
+++ b/saleor/payment/tests/fixtures/gateway_response.py
@@ -14,7 +14,7 @@ def action_required_gateway_response():
action_required_data={
"paymentData": "test",
"paymentMethodType": "scheme",
- "url": "https://test.adyen.com/hpp/3d/validate.shtml",
+ "url": "https://test.example.com/3d/validate",
"data": {
"MD": "md-test-data",
"PaReq": "PaReq-test-data",
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index dbc0c66436..17359a9c5a 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -415,7 +415,6 @@ def create_payment(
"gateway": gateway,
"total": total,
"return_url": return_url,
- "partial": False,
"psp_reference": external_reference or "",
"store_payment_method": store_payment_method,
"metadata": {} if metadata is None else metadata,
@@ -505,8 +504,6 @@ def create_transaction(
customer_id=gateway_response.customer_id,
gateway_response=gateway_response.raw_response or {},
action_required_data=gateway_response.action_required_data or {},
- legacy_adyen_plugin_result_code=gateway_response.legacy_adyen_plugin_result_code,
- legacy_adyen_plugin_payment_method=gateway_response.legacy_adyen_plugin_payment_method,
)
return txn
diff --git a/saleor/settings.py b/saleor/settings.py
index e165b4d436..3b0f251f66 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -891,7 +891,6 @@ BUILTIN_PLUGINS = [
"saleor.payment.gateways.stripe.plugin.StripeGatewayPlugin",
"saleor.payment.gateways.braintree.plugin.DeprecatedBraintreeGatewayPlugin",
"saleor.payment.gateways.razorpay.plugin.DeprecatedRazorpayGatewayPlugin",
- "saleor.payment.gateways.adyen.plugin.AdyenGatewayPlugin",
"saleor.payment.gateways.authorize_net.plugin.AuthorizeNetGatewayPlugin",
"saleor.payment.gateways.np_atobarai.plugin.NPAtobaraiGatewayPlugin",
"saleor.plugins.user_email.plugin.UserEmailPlugin",
diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.py
index 2cbdce9b7c..e9f76c43b7 100644
--- a/saleor/webhook/tests/test_webhook_payloads.py
+++ b/saleor/webhook/tests/test_webhook_payloads.py
@@ -185,7 +185,6 @@ def test_generate_order_payload(
"type": "Payment",
"gateway": payment.gateway,
"payment_method_type": payment.payment_method_type,
- "partial": False,
"cc_brand": payment.cc_brand,
"is_active": payment.is_active,
"created": parse_django_datetime(payment.created_at),
diff --git a/uv.lock b/uv.lock
index b78cc7605c..374039ccc0 100644
--- a/uv.lock
+++ b/uv.lock
@@ -8,12 +8,6 @@ supported-markers = [
"platform_python_implementation != 'PyPy'",
]
-[[package]]
-name = "adyen"
-version = "4.0.0"
-source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/12/eb/6833b24e8c6f55b855ded1ec131712bef62982a2461e6f184ddd9438bf3e/Adyen-4.0.0.tar.gz", hash = "sha256:f44007fd542d7634bee69f29572442bf9102043141a7d5822ac98539ac5e4d5b", size = 12656, upload-time = "2020-11-26T11:42:44.023Z" }
-
[[package]]
name = "amqp"
version = "5.3.1"
@@ -2526,7 +2520,6 @@ name = "saleor"
version = "3.23.0a0"
source = { virtual = "." }
dependencies = [
- { name = "adyen", marker = "platform_python_implementation != 'PyPy'" },
{ name = "asgiref", marker = "platform_python_implementation != 'PyPy'" },
{ name = "authlib", marker = "platform_python_implementation != 'PyPy'" },
{ name = "authorizenet", marker = "platform_python_implementation != 'PyPy'" },
@@ -2640,7 +2633,6 @@ dev = [
[package.metadata]
requires-dist = [
- { name = "adyen", specifier = ">=4.0.0,<5" },
{ name = "asgiref", specifier = ">=3.7.2,<4" },
{ name = "authlib", specifier = ">=1.6.9,<2" },
{ name = "authorizenet", specifier = ">=1.1.5,<2" },