Skip to content

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

Fix failing saleor autocapture. Improve the handler for authorization (#6348)

Maciej Korycinski03be7057c1f1
diff --git a/saleor/payment/gateways/adyen/plugin.py b/saleor/payment/gateways/adyen/plugin.py
index f8e60aaef2..13784e0ef5 100644
--- a/saleor/payment/gateways/adyen/plugin.py
+++ b/saleor/payment/gateways/adyen/plugin.py
@@ -334,20 +334,25 @@ class AdyenGatewayPlugin(BasePlugin):
result = api_call(additional_data, self.adyen.checkout.payments_details)
result_code = result.message["resultCode"].strip().lower()
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:
+ elif is_success and config.auto_capture and not action_required:
# 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
+ 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" in result.message,
+ action_required=action_required,
action_required_data=action,
kind=kind,
amount=payment_information.amount,
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 c7a41ee0ec..4ef9266013 100644
--- a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py
+++ b/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py
@@ -272,9 +272,14 @@ def test_handle_authorization_with_adyen_auto_capture_and_payment_charged(
assert external_events.count() == 1
-def test_handle_cancel(notification, adyen_plugin, payment_adyen_for_order):
[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,
diff --git a/saleor/payment/gateways/adyen/utils.py b/saleor/payment/gateways/adyen/utils.py
index dc0265c19f..86b0751ae6 100644
--- a/saleor/payment/gateways/adyen/utils.py
+++ b/saleor/payment/gateways/adyen/utils.py
@@ -68,8 +68,9 @@ def request_data_for_payment(
channel = payment_data.get("channel", "web")
origin_url = payment_data.get("originUrl")
- if "browserInfo" in payment_data:
- extra_request_params["browserInfo"] = payment_data["browserInfo"]
+ browser_info = payment_data.get("browserInfo")
+ if browser_info:
+ extra_request_params["browserInfo"] = browser_info
if "billingAddress" in payment_data:
extra_request_params["billingAddress"] = payment_data["billingAddress"]
if "shopperIP" in payment_data:
diff --git a/saleor/payment/gateways/adyen/webhooks.py b/saleor/payment/gateways/adyen/webhooks.py
index 9b6d0086e9..f0ffe1aa10 100644
--- a/saleor/payment/gateways/adyen/webhooks.py
+++ b/saleor/payment/gateways/adyen/webhooks.py
@@ -47,7 +47,9 @@ logger = logging.getLogger(__name__)
def get_payment(
- payment_id: Optional[str], transaction_id: Optional[str] = None
+ payment_id: Optional[str],
+ transaction_id: Optional[str] = None,
+ check_if_active=True,
) -> Optional[Payment]:
transaction_id = transaction_id or ""
if payment_id is None or not payment_id.strip():
@@ -62,15 +64,20 @@ def get_payment(
transaction_id,
)
return None
- payment = (
+ payments = (
Payment.objects.prefetch_related("order", "checkout")
.select_for_update(of=("self",))
- .filter(id=db_payment_id, is_active=True, gateway="mirumee.payments.adyen")
- .first()
+ .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 was not found. Reference %s", payment_id, transaction_id
+ "Payment for %s (%s) was not found. Reference %s",
+ payment_id,
+ db_payment_id,
+ transaction_id,
)
return payment
@@ -155,7 +162,7 @@ def create_order(payment, checkout):
return order
-def handle_not_created_order(notification, payment, checkout):
+def handle_not_created_order(notification, payment, checkout, kind):
"""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
@@ -166,14 +173,18 @@ def handle_not_created_order(notification, payment, checkout):
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(
+ action_required=False, is_success=True, kind=kind
+ ).last()
+ if not transaction:
+ # 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.
+ transaction = create_new_transaction(
+ notification, payment, TransactionKind.ACTION_TO_CONFIRM
+ )
# Only when we confirm that notification is success we will create the order
- if action_transaction.is_success and checkout: # type: ignore
+ if transaction.is_success and checkout: # type: ignore
order = create_order(payment, checkout)
return order
return None
@@ -187,8 +198,12 @@ def handle_authorization(notification: Dict[str, Any], gateway_config: GatewayCo
return
checkout = get_checkout(payment)
+ adyen_auto_capture = gateway_config.connection_params["adyen_auto_capture"]
+ kind = TransactionKind.AUTH
+ if adyen_auto_capture:
+ kind = TransactionKind.CAPTURE
if not payment.order:
- handle_not_created_order(notification, payment, checkout)
+ handle_not_created_order(notification, payment, checkout, kind)
else:
adyen_auto_capture = gateway_config.connection_params["adyen_auto_capture"]
kind = TransactionKind.AUTH
@@ -200,13 +215,16 @@ def handle_authorization(notification: Dict[str, Any], gateway_config: GatewayCo
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)
+ if not transaction:
+ new_transaction = create_new_transaction(notification, payment, kind)
+ if new_transaction.is_success:
+ 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."
@@ -219,7 +237,12 @@ def handle_authorization(notification: Dict[str, Any], gateway_config: GatewayCo
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(notification.get("merchantReference"), transaction_id)
+ 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)
@@ -264,7 +287,9 @@ def handle_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig)
checkout = get_checkout(payment)
if not payment.order:
- handle_not_created_order(notification, payment, checkout)
+ handle_not_created_order(
+ notification, payment, checkout, TransactionKind.CAPTURE
+ )
else:
capture_transaction = payment.transactions.filter(
action_required=False, is_success=True, kind=TransactionKind.CAPTURE,
@@ -645,9 +670,7 @@ def handle_additional_actions(
result = api_call(request_data, payment_details)
except PaymentError as e:
return HttpResponseBadRequest(str(e))
-
handle_api_response(payment, result)
-
redirect_url = prepare_redirect_url(payment_id, checkout_pk, result, return_url)
return redirect(redirect_url)
@@ -739,6 +762,5 @@ def handle_api_response(
payment_information=payment_data,
gateway_response=gateway_response,
)
-
- if is_success and not action_required:
+ if is_success and not action_required and not payment.order:
create_order(payment, checkout)