Skip to content

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

Cleanup the webhooks logic. Creae order after additional actions are done

Maciej Korycinski0f28c07ad794
diff --git a/saleor/order/models.py b/saleor/order/models.py
index 14904fae21..e97184c840 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -242,7 +242,9 @@ class Order(ModelWithMetadata):
def is_pre_authorized(self):
return (
self.payments.filter(
- is_active=True, transactions__kind=TransactionKind.AUTH
+ is_active=True,
+ transactions__kind=TransactionKind.AUTH,
+ transactions__action_required=False,
)
.filter(transactions__is_success=True)
.exists()
@@ -251,7 +253,9 @@ class Order(ModelWithMetadata):
def is_captured(self):
return (
self.payments.filter(
- is_active=True, transactions__kind=TransactionKind.CAPTURE
+ is_active=True,
+ transactions__kind=TransactionKind.CAPTURE,
+ transactions__action_required=False,
)
.filter(transactions__is_success=True)
.exists()
diff --git a/saleor/payment/gateways/adyen/plugin.py b/saleor/payment/gateways/adyen/plugin.py
index 319426cabc..70146027f5 100644
--- a/saleor/payment/gateways/adyen/plugin.py
+++ b/saleor/payment/gateways/adyen/plugin.py
@@ -334,10 +334,14 @@ class AdyenGatewayPlugin(BasePlugin):
raise PaymentError("Unable to finish the payment.")
result = api_call(additional_data, self.adyen.checkout.payments)
- is_success = result.message["resultCode"].strip().lower() not in FAILED_STATUSES
- # For enabled auto_capture on Saleor side we need to proceed an additional
- # action
- if is_success and config.auto_capture:
+ result_code = result.message["resultCode"].strip().lower()
+ is_success = result_code not in FAILED_STATUSES
+
+ if result_code in PENDING_STATUSES:
+ kind = TransactionKind.PENDING
+ elif is_success and config.auto_capture:
+ # For enabled auto_capture on Saleor side we need to proceed an additional
+ # action
response = self.capture_payment(payment_information, None)
is_success = response.is_success
@@ -383,6 +387,10 @@ class AdyenGatewayPlugin(BasePlugin):
# standard flow for confirming an additional action
return self._process_additional_action(payment_information, kind)
+ result_code = transaction.gateway_response.get("resultCode", "").strip().lower()
+ if result_code and result_code in PENDING_STATUSES:
+ kind = TransactionKind.PENDING
+
# We already have the ACTION_TO_CONFIRM transaction, it means that
# payment was processed asynchronous and no additional action is required
@@ -395,7 +403,11 @@ class AdyenGatewayPlugin(BasePlugin):
currency=payment_information.currency,
).first()
is_success = True
- if not transaction_already_processed and config.auto_capture:
+ 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
diff --git a/saleor/payment/gateways/adyen/tests/test_plugin.py b/saleor/payment/gateways/adyen/tests/test_plugin.py
index 3ac6ebc81b..2fc4ec9582 100644
--- a/saleor/payment/gateways/adyen/tests/test_plugin.py
+++ b/saleor/payment/gateways/adyen/tests/test_plugin.py
@@ -238,6 +238,34 @@ def test_confirm_payment(payment_adyen_for_order, adyen_plugin):
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="",
+ raw_response={"pspReference": "882595494831959A", "resultCode": "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(
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
index 4f8e2692b8..8e143c0c5a 100644
--- a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_additional_actions.py
+++ b/saleor/payment/gateways/adyen/tests/webhooks/test_handle_additional_actions.py
@@ -10,12 +10,16 @@ from ...webhooks import handle_additional_actions
@mock.patch("saleor.payment.gateways.adyen.webhooks.api_call")
-def test_handle_additional_actions_post(api_call_mock, payment_adyen_for_checkout):
+def test_handle_additional_actions_post(
+ api_call_mock, payment_adyen_for_checkout, adyen_plugin
+):
# given
+ adyen_plugin()
+ 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=["extra_data"])
+ payment_adyen_for_checkout.save(update_fields=["to_confirm", "extra_data"])
transaction_count = payment_adyen_for_checkout.transactions.all().count()
@@ -29,6 +33,7 @@ def test_handle_additional_actions_post(api_call_mock, payment_adyen_for_checkou
payment_details_mock = mock.Mock()
message = {
+ "pspReference": "11111",
"resultCode": "Test",
}
api_call_mock.return_value.message = message
@@ -42,20 +47,26 @@ def test_handle_additional_actions_post(api_call_mock, payment_adyen_for_checkou
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_checkout.transactions.all().count() == transaction_count + 1
- )
- transaction = payment_adyen_for_checkout.transactions.last()
- assert transaction.kind == TransactionKind.ACTION_TO_CONFIRM
+ 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
@mock.patch("saleor.payment.gateways.adyen.webhooks.api_call")
-def test_handle_additional_actions_get(api_call_mock, payment_adyen_for_checkout):
+def test_handle_additional_actions_get(
+ api_call_mock, payment_adyen_for_checkout, adyen_plugin
+):
# given
+ adyen_plugin()
+ 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=["extra_data"])
+ payment_adyen_for_checkout.save(update_fields=["to_confirm", "extra_data"])
transaction_count = payment_adyen_for_checkout.transactions.all().count()
@@ -72,6 +83,7 @@ def test_handle_additional_actions_get(api_call_mock, payment_adyen_for_checkout
payment_details_mock = mock.Mock()
message = {
+ "pspReference": "11111",
"resultCode": "Test",
}
api_call_mock.return_value.message = message
@@ -85,11 +97,12 @@ def test_handle_additional_actions_get(api_call_mock, payment_adyen_for_checkout
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_checkout.transactions.all().count() == transaction_count + 1
- )
- transaction = payment_adyen_for_checkout.transactions.last()
- assert transaction.kind == TransactionKind.ACTION_TO_CONFIRM
+ 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
def test_handle_additional_actions_more_action_required(payment_adyen_for_checkout):
@@ -136,6 +149,8 @@ def test_handle_additional_actions_more_action_required(payment_adyen_for_checko
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):
@@ -166,8 +181,7 @@ def test_handle_additional_actions_payment_does_not_exist(payment_adyen_for_chec
# then
assert response.status_code == 404
assert response.content.decode() == (
- "Cannot perform payment. "
- "There is no active adyen payment with specified checkout."
+ "Cannot perform payment.There is no active adyen payment."
)
@@ -256,8 +270,7 @@ def test_handle_additional_actions_checkout_not_related_to_payment(
# then
assert response.status_code == 404
assert response.content.decode() == (
- "Cannot perform payment. "
- "There is no active adyen payment with specified checkout."
+ "Cannot perform payment.There is no checkout with this payment."
)
@@ -289,8 +302,7 @@ def test_handle_additional_actions_payment_does_not_have_checkout(
# then
assert response.status_code == 404
assert response.content.decode() == (
- "Cannot perform payment. "
- "There is no active adyen payment with specified checkout."
+ "Cannot perform payment.There is no checkout with this payment."
)
@@ -357,8 +369,7 @@ def test_handle_additional_actions_payment_not_active(payment_adyen_for_checkout
# then
assert response.status_code == 404
assert response.content.decode() == (
- "Cannot perform payment. "
- "There is no active adyen payment with specified checkout."
+ "Cannot perform payment.There is no active adyen payment."
)
@@ -391,8 +402,7 @@ def test_handle_additional_actions_payment_with_no_adyen_gateway(
# then
assert response.status_code == 404
assert response.content.decode() == (
- "Cannot perform payment. "
- "There is no active adyen payment with specified checkout."
+ "Cannot perform payment.There is no active adyen payment."
)
diff --git a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py b/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py
index 2aaac52a6c..e7f0b61bd2 100644
--- a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py
+++ b/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py
@@ -5,7 +5,7 @@ import graphene
import pytest
from ......checkout import calculations
-from ......order import OrderStatus
+from ......order import OrderEvents, OrderStatus
from ..... import ChargeStatus, TransactionKind
from ...utils import to_adyen_price
from ...webhooks import (
@@ -35,10 +35,91 @@ def test_handle_authorization_for_order(
config = adyen_plugin().config
handle_authorization(notification, config)
- assert payment.transactions.count() == 1
- transaction = payment.transactions.get()
+ assert payment.transactions.count() == 2
+ transaction = payment.transactions.last()
assert transaction.is_success is True
assert transaction.kind == TransactionKind.AUTH
+ assert (
+ payment.order.events.filter(
+ type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
+ ).count()
+ == 1
+ )
+
+
+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=to_adyen_price(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
+ assert (
+ payment.order.events.filter(
+ type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
+ ).count()
+ == 1
+ )
+
+ second_notification = notification(
+ merchant_reference=payment_id,
+ value=to_adyen_price(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
+ assert (
+ payment.order.events.filter(
+ type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
+ ).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=to_adyen_price(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
+ assert (
+ payment.order.events.filter(
+ type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
+ ).count()
+ == 1
+ )
def test_handle_authorization_for_checkout(
@@ -78,6 +159,12 @@ def test_handle_authorization_for_checkout(
assert payment.checkout is None
assert payment.order
assert payment.order.checkout_token == checkout_token
+ assert (
+ payment.order.events.filter(
+ type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
+ ).count()
+ == 1
+ )
def test_handle_authorization_with_adyen_auto_capture(
@@ -108,9 +195,16 @@ def test_handle_authorization_with_adyen_auto_capture(
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
+ assert (
+ payment.order.events.filter(
+ type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
+ ).count()
+ == 1
+ )
@pytest.mark.vcr
@@ -136,6 +230,12 @@ def test_handle_authorization_with_auto_capture(
transaction = payment.transactions.filter(kind=TransactionKind.CAPTURE).get()
assert transaction.is_success is True
assert payment.charge_status == ChargeStatus.FULLY_CHARGED
+ assert (
+ payment.order.events.filter(
+ type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
+ ).count()
+ == 1
+ )
def test_handle_authorization_with_adyen_auto_capture_and_payment_charged(
@@ -153,8 +253,15 @@ def test_handle_authorization_with_adyen_auto_capture_and_payment_charged(
config.connection_params["adyen_auto_capture"] = True
handle_authorization(notification, config)
- # payment already has a charge status no need to handle auth action
- assert payment.transactions.count() == 1
+ payment.refresh_from_db()
+ assert payment.transactions.count() == 2
+ assert payment.transactions.filter(kind=TransactionKind.CAPTURE).exists()
+ assert (
+ payment.order.events.filter(
+ type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
+ ).count()
+ == 1
+ )
def test_handle_cancel(notification, adyen_plugin, payment_adyen_for_order):
@@ -175,9 +282,15 @@ def test_handle_cancel(notification, adyen_plugin, payment_adyen_for_order):
assert transaction.is_success is True
assert payment.order.status == OrderStatus.CANCELED
+ assert (
+ payment.order.events.filter(
+ type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
+ ).count()
+ == 1
+ )
-def test_handle_cancel_already_canceleld(
+def test_handle_cancel_already_canceled(
notification, adyen_plugin, payment_adyen_for_order
):
payment = payment_adyen_for_order
@@ -210,6 +323,12 @@ def test_handle_capture_for_order(notification, adyen_plugin, payment_adyen_for_
transaction = payment.transactions.filter(kind=TransactionKind.CAPTURE).get()
assert transaction.is_success is True
assert payment.charge_status == ChargeStatus.FULLY_CHARGED
+ assert (
+ payment.order.events.filter(
+ type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
+ ).count()
+ == 1
+ )
def test_handle_capture_for_checkout(
@@ -249,6 +368,12 @@ def test_handle_capture_for_checkout(
assert payment.checkout is None
assert payment.order
assert payment.order.checkout_token == checkout_token
+ assert (
+ payment.order.events.filter(
+ type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
+ ).count()
+ == 1
+ )
def test_handle_capture_with_payment_already_charged(
@@ -268,7 +393,14 @@ def test_handle_capture_with_payment_already_charged(
handle_capture(notification, config)
# Payment is already captured so no need to save capture transaction
- assert payment.transactions.count() == 1
+ payment.refresh_from_db()
+ assert payment.transactions.count() == 2
+ assert (
+ payment.order.events.filter(
+ type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
+ ).count()
+ == 1
+ )
@pytest.mark.parametrize(
@@ -295,6 +427,12 @@ def test_handle_failed_capture(
assert transaction.is_success is True
payment.refresh_from_db()
assert payment.charge_status == ChargeStatus.NOT_CHARGED
+ assert (
+ payment.order.events.filter(
+ type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
+ ).count()
+ == 1
+ )
def test_handle_failed_capture_partial_charge(
@@ -318,6 +456,12 @@ def test_handle_failed_capture_partial_charge(
assert transaction.is_success is True
payment.refresh_from_db()
assert payment.charge_status == ChargeStatus.PARTIALLY_CHARGED
+ assert (
+ payment.order.events.filter(
+ type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
+ ).count()
+ == 1
+ )
def test_handle_pending(notification, adyen_plugin, payment_adyen_for_order):
@@ -336,6 +480,12 @@ def test_handle_pending(notification, adyen_plugin, payment_adyen_for_order):
assert transaction.is_success is True
payment.refresh_from_db()
assert payment.charge_status == ChargeStatus.PENDING
+ assert (
+ payment.order.events.filter(
+ type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
+ ).count()
+ == 1
+ )
def test_handle_pending_with_adyen_auto_capture(
@@ -358,6 +508,12 @@ def test_handle_pending_with_adyen_auto_capture(
assert payment.transactions.filter(kind=TransactionKind.PENDING).first()
payment.refresh_from_db()
assert payment.charge_status == ChargeStatus.PENDING
+ assert (
+ payment.order.events.filter(
+ type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
+ ).count()
+ == 1
+ )
def test_handle_pending_already_pending(
@@ -405,6 +561,12 @@ def test_handle_refund(
mock_order_refunded.assert_called_once_with(
payment.order, None, transaction.amount, payment
)
+ assert (
+ payment.order.events.filter(
+ type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
+ ).count()
+ == 1
+ )
@mock.patch("saleor.payment.gateways.adyen.webhooks.order_refunded")
@@ -446,6 +608,12 @@ def test_handle_failed_refund_missing_transaction(
handle_failed_refund(notification, config)
assert payment.transactions.count() == 1
+ assert (
+ payment.order.events.filter(
+ type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
+ ).count()
+ == 1
+ )
def test_handle_failed_refund_with_transaction_refund_ongoing(
@@ -469,6 +637,12 @@ def test_handle_failed_refund_with_transaction_refund_ongoing(
) # ACTION_TO_CONFIRM, REFUND_ONGOING, REFUND_FAILED, FULLY_CHARGED
assert payment.charge_status == ChargeStatus.FULLY_CHARGED
assert payment.total == payment.captured_amount
+ assert (
+ payment.order.events.filter(
+ type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
+ ).count()
+ == 1
+ )
def test_handle_failed_refund_with_transaction_refund(
@@ -491,6 +665,12 @@ def test_handle_failed_refund_with_transaction_refund(
assert payment.transactions.count() == 4 # REFUND, REFUND_FAILED, FULLY_CHARGED
assert payment.charge_status == ChargeStatus.FULLY_CHARGED
assert payment.total == payment.captured_amount
+ assert (
+ payment.order.events.filter(
+ type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
+ ).count()
+ == 1
+ )
def test_handle_reversed_refund(notification, adyen_plugin, payment_adyen_for_order):
@@ -510,6 +690,12 @@ def test_handle_reversed_refund(notification, adyen_plugin, payment_adyen_for_or
assert payment.transactions.filter(kind=TransactionKind.REFUND_REVERSED).exists()
assert payment.charge_status == ChargeStatus.FULLY_CHARGED
assert payment.total == payment.captured_amount
+ assert (
+ payment.order.events.filter(
+ type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
+ ).count()
+ == 1
+ )
def test_handle_reversed_refund_already_processed(
@@ -528,7 +714,6 @@ def test_handle_reversed_refund_already_processed(
create_new_transaction(notification, payment, TransactionKind.REFUND_REVERSED)
handle_reversed_refund(notification, config)
- payment.refresh_from_db()
assert payment.transactions.filter(kind=TransactionKind.REFUND_REVERSED).exists()
@@ -546,7 +731,12 @@ def test_webhook_not_implemented(notification, adyen_plugin, payment_adyen_for_o
webhook_not_implemented(notification, config)
- assert payment.order.events.count() == 1
+ assert (
+ payment.order.events.filter(
+ type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
+ ).count()
+ == 1
+ )
@mock.patch("saleor.payment.gateways.adyen.webhooks.handle_refund")
diff --git a/saleor/payment/gateways/adyen/webhooks.py b/saleor/payment/gateways/adyen/webhooks.py
index e09826fe6e..842f661f88 100644
--- a/saleor/payment/gateways/adyen/webhooks.py
+++ b/saleor/payment/gateways/adyen/webhooks.py
@@ -11,7 +11,7 @@ import Adyen
import graphene
from django.contrib.auth.hashers import check_password
from django.contrib.auth.models import AnonymousUser
-from django.core.exceptions import ObjectDoesNotExist, ValidationError
+from django.core.exceptions import ValidationError
from django.core.handlers.wsgi import WSGIRequest
from django.http import (
HttpResponse,
@@ -28,7 +28,12 @@ from ....checkout.models import Checkout
from ....core.transactions import transaction_with_commit_on_errors
from ....core.utils.url import prepare_url
from ....discount.utils import fetch_active_discounts
-from ....order.actions import cancel_order, order_captured, order_refunded
+from ....order.actions import (
+ cancel_order,
+ order_authorized,
+ order_captured,
+ order_refunded,
+)
from ....order.events import external_notification_event
from ....payment.models import Payment, Transaction
from ... import ChargeStatus, PaymentError, TransactionKind
@@ -41,7 +46,7 @@ logger = logging.getLogger(__name__)
def get_payment(
- payment_id: Optional[str], transaction_id: Optional[str]
+ payment_id: Optional[str], transaction_id: Optional[str] = None
) -> Optional[Payment]:
transaction_id = transaction_id or ""
if not payment_id:
@@ -59,7 +64,7 @@ def get_payment(
payment = (
Payment.objects.prefetch_related("order", "checkout")
.select_for_update(of=("self",))
- .filter(id=db_payment_id)
+ .filter(id=db_payment_id, is_active=True, gateway="mirumee.payments.adyen")
.first()
)
if not payment:
@@ -130,68 +135,84 @@ def create_payment_notification_for_order(
)
-@transaction_with_commit_on_errors()
-def handle_authorization(notification: Dict[str, Any], _gateway_config: GatewayConfig):
- transaction_id = notification.get("pspReference")
- payment = get_payment(notification.get("merchantReference"), transaction_id)
- if not payment:
- # We don't know anything about that payment
- return
- checkout = get_checkout(payment)
- if payment.order and payment.charge_status in {
- ChargeStatus.FULLY_CHARGED,
+def create_order(payment, checkout):
+ try:
+ discounts = fetch_active_discounts()
+ order, _, _ = complete_checkout(
+ checkout=checkout,
+ payment_data={},
+ store_source=False,
+ discounts=discounts,
+ user=checkout.user or AnonymousUser(),
+ )
+ except ValidationError:
+ payment_refund_or_void(payment)
+ return None
+ payment.order = order
+ return order
+
+
+def handle_not_created_order(notification, payment, checkout):
+ """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
+ # If the payment is not Auth/Capture, it means that user didn't return to the
+ # storefront and we need to finalize the checkout asynchronously.
+ action_transaction = create_new_transaction(
+ notification, payment, TransactionKind.ACTION_TO_CONFIRM
+ )
- transaction = payment.transactions.filter(
- token=transaction_id,
- action_required=False,
- is_success=True,
- kind__in=[TransactionKind.AUTH, TransactionKind.CAPTURE],
- ).last()
+ # Only when we confirm that notification is success we will create the order
+ if action_transaction.is_success and checkout: # type: ignore
+ order = create_order(payment, checkout)
+ return order
+ return None
- if transaction and payment.order:
- # We already have this transaction and order is created
- return
- action_transaction = payment.transactions.filter(
- token=transaction_id,
- action_required=False,
- is_success=True,
- kind=TransactionKind.ACTION_TO_CONFIRM,
- ).last()
+def handle_authorization(notification: Dict[str, Any], gateway_config: GatewayConfig):
+ transaction_id = notification.get("pspReference")
+ payment = get_payment(notification.get("merchantReference"), transaction_id)
+ if not payment:
+ # We don't know anything about that payment
+ return
+ checkout = get_checkout(payment)
if not payment.order:
- # If the payment is not Auth/Capture, it means that user didn't return to the
- # storefront and we need to finalize the checkout asynchronously.
- if not action_transaction:
- action_transaction = create_new_transaction(
- notification, payment, TransactionKind.ACTION_TO_CONFIRM
- )
-
- if action_transaction.is_success and checkout: # type: ignore
- try:
- discounts = fetch_active_discounts()
- order, _, _ = complete_checkout(
- checkout=checkout,
- payment_data={},
- store_source=False,
- discounts=discounts,
- user=checkout.user or AnonymousUser(),
- )
- except ValidationError:
- payment_refund_or_void(payment)
- return
-
+ handle_not_created_order(notification, payment, checkout)
+ else:
+ adyen_auto_capture = gateway_config.connection_params["adyen_auto_capture"]
+ kind = TransactionKind.AUTH
+ if adyen_auto_capture:
+ kind = TransactionKind.CAPTURE
+ transaction = payment.transactions.filter(
+ token=transaction_id,
+ action_required=False,
+ is_success=True,
+ kind__in=[TransactionKind.AUTH, TransactionKind.CAPTURE],
+ ).last()
+ new_transaction = create_new_transaction(notification, payment, kind)
+ if new_transaction.is_success and not transaction:
+ gateway_postprocess(new_transaction, payment)
+ if adyen_auto_capture:
+ order_captured(payment.order, None, new_transaction.amount, payment)
+ else:
+ order_authorized(payment.order, None, new_transaction.amount, payment)
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}"
+ failed_msg = (
+ f"Adyen: The payment {transaction_id} request failed. Reason: {reason}."
+ )
create_payment_notification_for_order(payment, success_msg, failed_msg, is_success)
-@transaction_with_commit_on_errors()
def handle_cancellation(notification: Dict[str, Any], _gateway_config: GatewayConfig):
# https://docs.adyen.com/checkout/cancel#cancellation-notifciation
transaction_id = notification.get("pspReference")
@@ -213,7 +234,7 @@ def handle_cancellation(notification: Dict[str, Any], _gateway_config: GatewayCo
create_payment_notification_for_order(
payment, success_msg, failed_msg, new_transaction.is_success
)
- if payment.order:
+ if payment.order and new_transaction.is_success:
cancel_order(payment.order, None)
@@ -231,7 +252,6 @@ def handle_cancel_or_refund(
handle_cancellation(notification, gateway_config)
-@transaction_with_commit_on_errors()
def handle_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig):
# https://docs.adyen.com/checkout/capture#capture-notification
transaction_id = notification.get("pspReference")
@@ -240,54 +260,18 @@ def handle_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig)
return
checkout = get_checkout(payment)
- if payment.charge_status == ChargeStatus.FULLY_CHARGED:
- # the payment has already status captured.
- return
-
- capture_transaction = payment.transactions.filter(
- token=transaction_id,
- action_required=False,
- is_success=True,
- kind=TransactionKind.CAPTURE,
- ).last()
-
- if capture_transaction:
- # We already have this transaction
- return
-
if not payment.order:
- action_transaction = payment.transactions.filter(
- token=transaction_id,
- action_required=False,
- is_success=True,
- kind=TransactionKind.ACTION_TO_CONFIRM,
- ).last()
- # If the payment is not Auth/Capture, it means that user didn't return to the
- # storefront and we need to finalize the checkout asynchronously.
- if not action_transaction:
- action_transaction = create_new_transaction(
- notification, payment, TransactionKind.ACTION_TO_CONFIRM
- )
-
- if action_transaction.is_success and checkout: # type: ignore
- try:
- discounts = fetch_active_discounts()
- order, _, _ = complete_checkout(
- checkout=checkout,
- payment_data={},
- store_source=False,
- discounts=discounts,
- user=checkout.user or AnonymousUser(),
- )
- except ValidationError:
- payment_refund_or_void(payment)
- return
+ handle_not_created_order(notification, payment, checkout)
else:
+ capture_transaction = payment.transactions.filter(
+ action_required=False, is_success=True, kind=TransactionKind.CAPTURE,
+ ).last()
new_transaction = create_new_transaction(
notification, payment, TransactionKind.CAPTURE
)
- gateway_postprocess(new_transaction, payment)
- order_captured(payment.order, None, new_transaction.amount, payment)
+ if new_transaction.is_success and not capture_transaction:
+ gateway_postprocess(new_transaction, payment)
+ order_captured(payment.order, None, new_transaction.amount, payment)
reason = notification.get("reason", "-")
is_success = True if notification.get("success") == "true" else False
@@ -296,7 +280,6 @@ def handle_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig)
create_payment_notification_for_order(payment, success_msg, failed_msg, is_success)
-@transaction_with_commit_on_errors()
def handle_failed_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig):
# https://docs.adyen.com/checkout/capture#failed-capture
transaction_id = notification.get("pspReference")
@@ -323,7 +306,6 @@ def handle_failed_capture(notification: Dict[str, Any], _gateway_config: Gateway
create_payment_notification_for_order(payment, msg, None, True)
-@transaction_with_commit_on_errors()
def handle_pending(notification: Dict[str, Any], gateway_config: GatewayConfig):
# https://docs.adyen.com/development-resources/webhooks/understand-notifications#
# event-codes"
@@ -347,7 +329,6 @@ def handle_pending(notification: Dict[str, Any], gateway_config: GatewayConfig):
)
-@transaction_with_commit_on_errors()
def handle_refund(notification: Dict[str, Any], _gateway_config: GatewayConfig):
# https://docs.adyen.com/checkout/refund#refund-notification
transaction_id = notification.get("pspReference")
@@ -380,7 +361,6 @@ def _get_kind(transaction: Optional[Transaction]) -> str:
return TransactionKind.CAPTURE
-@transaction_with_commit_on_errors()
def handle_failed_refund(notification: Dict[str, Any], gateway_config: GatewayConfig):
# https://docs.adyen.com/checkout/refund#failed-refund
transaction_id = notification.get("pspReference")
@@ -444,7 +424,6 @@ def handle_failed_refund(notification: Dict[str, Any], gateway_config: GatewayCo
gateway_postprocess(new_transaction, payment)
-@transaction_with_commit_on_errors()
def handle_reversed_refund(
notification: Dict[str, Any], _gateway_config: GatewayConfig
):
@@ -481,7 +460,6 @@ def handle_refund_with_data(
handle_refund(notification, gateway_config)
-@transaction_with_commit_on_errors()
def webhook_not_implemented(
notification: Dict[str, Any], gateway_config: GatewayConfig
):
@@ -589,6 +567,7 @@ def validate_auth_user(headers: HttpHeaders, gateway_config: "GatewayConfig") ->
return False
+@transaction_with_commit_on_errors()
def handle_webhook(request: WSGIRequest, gateway_config: "GatewayConfig"):
json_data = json.loads(request.body)
# JSON and HTTP POST notifications always contain a single NotificationRequestItem
@@ -609,6 +588,7 @@ def handle_webhook(request: WSGIRequest, gateway_config: "GatewayConfig"):
return HttpResponse("[accepted]")
+@transaction_with_commit_on_errors()
def handle_additional_actions(
request: WSGIRequest, payment_details: Callable,
):
@@ -618,19 +598,16 @@ def handle_additional_actions(
if not payment_id or not checkout_pk:
return HttpResponseNotFound()
- _type, payment_pk = from_global_id(payment_id)
- try:
- payment = Payment.objects.get(
- pk=payment_pk,
- checkout__pk=checkout_pk,
- is_active=True,
- gateway="mirumee.payments.adyen",
+ payment = get_payment(payment_id, transaction_id=None)
+ if not payment:
+ return HttpResponseNotFound(
+ "Cannot perform payment.There is no active adyen payment."
)
- except ObjectDoesNotExist:
+ if not payment.checkout or str(payment.checkout.token) != checkout_pk:
return HttpResponseNotFound(
- "Cannot perform payment. "
- "There is no active adyen payment with specified checkout."
+ "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
@@ -706,6 +683,7 @@ def prepare_redirect_url(
def handle_api_response(
payment: Payment, response: Adyen.Adyen,
):
+ checkout = get_checkout(payment)
payment_data = create_payment_information(
payment=payment, payment_token=payment.token,
)
@@ -738,3 +716,6 @@ def handle_api_response(
payment_information=payment_data,
gateway_response=gateway_response,
)
+
+ if is_success and not action_required:
+ create_order(payment, checkout)