Skip to content

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

Clean up the webhook logic

Maciej Korycinskid0214559f572
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index 61713a0d04..5a35bfc3e4 100644
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@ -17,7 +17,7 @@ from ....order.actions import (
)
from ....order.error_codes import OrderErrorCode
from ....order.utils import get_valid_shipping_methods_for_order
-from ....payment import CustomPaymentChoices, PaymentError, gateway
+from ....payment import CustomPaymentChoices, PaymentError, TransactionKind, gateway
from ...account.types import AddressInput
from ...core.mutations import BaseMutation
from ...core.scalars import UUID, Decimal
@@ -122,7 +122,7 @@ def clean_refund_payment(payment):
def try_payment_action(order, user, payment, func, *args, **kwargs):
try:
- func(*args, **kwargs)
+ return func(*args, **kwargs)
except (PaymentError, ValueError) as e:
message = str(e)
events.payment_failed_event(
@@ -131,7 +131,6 @@ def try_payment_action(order, user, payment, func, *args, **kwargs):
raise ValidationError(
{"payment": ValidationError(message, code=OrderErrorCode.PAYMENT_ERROR)}
)
- return True
class OrderUpdateInput(graphene.InputObjectType):
@@ -388,10 +387,13 @@ class OrderCapture(BaseMutation):
payment = order.get_last_payment()
clean_order_capture(payment)
- try_payment_action(
+ transaction = try_payment_action(
order, info.context.user, payment, gateway.capture, payment, amount
)
- order_captured(order, info.context.user, amount, payment)
+ # Confirm that we changed the status to capture. Some payment can receive
+ # asynchronous webhook with update status
+ if transaction.kind == TransactionKind.CAPTURE:
+ order_captured(order, info.context.user, amount, payment)
if order.is_fully_paid():
handle_fully_paid_order(order)
return OrderCapture(order=order)
@@ -415,8 +417,13 @@ class OrderVoid(BaseMutation):
payment = order.get_last_payment()
clean_void_payment(payment)
- try_payment_action(order, info.context.user, payment, gateway.void, payment)
- order_voided(order, info.context.user, payment)
+ transaction = try_payment_action(
+ order, info.context.user, payment, gateway.void, payment
+ )
+ # Confirm that we changed the status to void. Some payment can receive
+ # asynchronous webhook with update status
+ if transaction.kind == TransactionKind.VOID:
+ order_voided(order, info.context.user, payment)
return OrderVoid(order=order)
@@ -449,11 +456,14 @@ class OrderRefund(BaseMutation):
payment = order.get_last_payment()
clean_refund_payment(payment)
- try_payment_action(
+ transaction = try_payment_action(
order, info.context.user, payment, gateway.refund, payment, amount
)
- order_refunded(order, info.context.user, amount, payment)
+ # Confirm that we changed the status to refund. Some payment can receive
+ # asynchronous webhook with update status
+ if transaction.kind == TransactionKind.REFUND:
+ order_refunded(order, info.context.user, amount, payment)
return OrderRefund(order=order)
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index c6b8965477..fb025f0c6e 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -1,6 +1,6 @@
import logging
from decimal import Decimal
-from typing import TYPE_CHECKING, Dict, List
+from typing import TYPE_CHECKING, Dict, List, Optional
from django.db import transaction
@@ -69,7 +69,7 @@ def handle_fully_paid_order(order: "Order", user: "User" = None):
@transaction.atomic
-def cancel_order(order: "Order", user: "User"):
+def cancel_order(order: "Order", user: Optional["User"]):
"""Cancel order.
Release allocation of unfulfilled order items.
@@ -86,7 +86,9 @@ def cancel_order(order: "Order", user: "User"):
manager.order_updated(order)
-def order_refunded(order: "Order", user: "User", amount: "Decimal", payment: "Payment"):
+def order_refunded(
+ order: "Order", user: Optional["User"], amount: "Decimal", payment: "Payment"
+):
events.payment_refunded_event(
order=order, user=user, amount=amount, payment=payment
)
@@ -129,7 +131,7 @@ def order_shipping_updated(order: "Order"):
def order_authorized(
- order: "Order", user: "User", amount: "Decimal", payment: "Payment"
+ order: "Order", user: Optional["User"], amount: "Decimal", payment: "Payment"
):
events.payment_authorized_event(
order=order, user=user, amount=amount, payment=payment
@@ -137,7 +139,9 @@ def order_authorized(
get_plugins_manager().order_updated(order)
-def order_captured(order: "Order", user: "User", amount: "Decimal", payment: "Payment"):
+def order_captured(
+ order: "Order", user: Optional["User"], amount: "Decimal", payment: "Payment"
+):
events.payment_captured_event(
order=order, user=user, amount=amount, payment=payment
)
diff --git a/saleor/payment/gateways/adyen/plugin.py b/saleor/payment/gateways/adyen/plugin.py
index f28c8ede45..11ab5c1682 100644
--- a/saleor/payment/gateways/adyen/plugin.py
+++ b/saleor/payment/gateways/adyen/plugin.py
@@ -20,6 +20,7 @@ from .utils import (
api_call,
request_data_for_gateway_config,
request_data_for_payment,
+ request_for_payment_capture,
request_for_payment_refund,
)
from .webhooks import handle_webhook
@@ -254,7 +255,7 @@ class AdyenGatewayPlugin(BasePlugin):
):
super()._update_config_items(configuration_to_update, current_config)
for item in current_config:
- if item.get("name") == "Notification password":
+ if item.get("name") == "Notification password" and item["value"]:
item["value"] = make_password(item["value"])
@require_active_plugin
@@ -293,7 +294,7 @@ class AdyenGatewayPlugin(BasePlugin):
_type, payment_id = from_global_id(payment_information.payment_id)
transaction = (
Transaction.objects.filter(
- payment__id=payment_id, kind=TransactionKind.CAPTURE
+ payment__id=payment_id, kind=TransactionKind.AUTH
)
.exclude(token__isnull=True, token__exact="")
.last()
@@ -320,12 +321,40 @@ class AdyenGatewayPlugin(BasePlugin):
raw_response=result.message,
)
+ @require_active_plugin
def capture_payment(
self, payment_information: "PaymentData", previous_value
) -> "GatewayResponse":
- pass
+ _type, payment_id = from_global_id(payment_information.payment_id)
+ transaction = (
+ Transaction.objects.filter(
+ payment__id=payment_id, kind=TransactionKind.AUTH
+ )
+ .exclude(token__isnull=True, token__exact="")
+ .last()
+ )
+ if not transaction:
+ raise PaymentError("Cannot find a payment reference to capture.")
+
+ request = request_for_payment_capture(
+ payment_information=payment_information,
+ merchant_account=self.config.connection_params["merchant_account"],
+ token=transaction.token,
+ )
+ result = api_call(request, self.adyen.payment.capture)
+ 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="",
+ raw_response=result.message,
+ )
def void_payment(
self, payment_information: "PaymentData", previous_value
) -> "GatewayResponse":
+
pass
diff --git a/saleor/payment/gateways/adyen/utils.py b/saleor/payment/gateways/adyen/utils.py
index 3ad74e702e..69ae64655f 100644
--- a/saleor/payment/gateways/adyen/utils.py
+++ b/saleor/payment/gateways/adyen/utils.py
@@ -118,3 +118,19 @@ def request_for_payment_refund(
"originalReference": token,
"reference": payment_information.payment_id,
}
+
+
+def request_for_payment_capture(
+ payment_information: "PaymentData", merchant_account, token
+) -> Dict[str, Any]:
+ return {
+ "merchantAccount": merchant_account,
+ "modificationAmount": {
+ "value": get_price_amount(
+ payment_information.amount, payment_information.currency
+ ),
+ "currency": payment_information.currency,
+ },
+ "originalReference": token,
+ "reference": payment_information.payment_id,
+ }
diff --git a/saleor/payment/gateways/adyen/webhooks.py b/saleor/payment/gateways/adyen/webhooks.py
index 8328e7080c..76e0f8c036 100644
--- a/saleor/payment/gateways/adyen/webhooks.py
+++ b/saleor/payment/gateways/adyen/webhooks.py
@@ -11,6 +11,13 @@ from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotFou
from django.http.request import HttpHeaders
from graphql_relay import from_global_id
+from ....order.actions import (
+ cancel_order,
+ handle_fully_paid_order,
+ order_authorized,
+ order_captured,
+ order_refunded,
+)
from ....order.events import payment_gateway_notification_event
from ....payment.models import Payment, Transaction
from ... import TransactionKind
@@ -28,7 +35,7 @@ def get_payment(payment_id: str) -> Payment:
def get_transaction(
payment: "Payment", transaction_id: str, kind: TransactionKind,
) -> Transaction:
- transaction = payment.transactions.filter(kind=kind, token=transaction_id)
+ transaction = payment.transactions.filter(kind=kind, token=transaction_id).first()
return transaction
@@ -96,6 +103,8 @@ def handle_authorization(notification: Dict[str, Any], gateway_config: GatewayCo
create_payment_notification_for_order(
payment, success_msg, failed_msg, transaction.is_success
)
+ if payment.order:
+ order_authorized(payment.order, None, transaction.amount, payment)
def handle_cancellation(notification: Dict[str, Any], _gateway_config: GatewayConfig):
@@ -116,8 +125,10 @@ def handle_cancellation(notification: Dict[str, Any], _gateway_config: GatewayCo
success_msg = f"Adyen: The cancel {transaction_id} request was successful."
failed_msg = f"Adyen: The camcel {transaction_id} request failed. Reason: {reason}"
create_payment_notification_for_order(
- payment, success_msg, failed_msg, transaction.is_success
+ payment, success_msg, failed_msg, new_transaction.is_success
)
+ if payment.order:
+ cancel_order(payment.order, None)
def handle_cancel_or_refund(
@@ -132,6 +143,7 @@ def handle_cancel_or_refund(
def handle_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig):
+ # FIXME execute order_fully_paid event
payment = get_payment(notification.get("merchantReference"))
if not payment:
return
@@ -144,14 +156,19 @@ def handle_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig)
new_transaction = create_new_transaction(
notification, payment, TransactionKind.CAPTURE
)
+
gateway_postprocess(new_transaction, payment)
+ if payment.order:
+ handle_fully_paid_order(payment.order)
reason = notification.get("reason", "-")
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, transaction.is_success
+ payment, success_msg, failed_msg, new_transaction.is_success
)
+ if payment.order:
+ order_captured(payment.orderm, None, transaction.amount, payment)
def handle_failed_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig):
@@ -199,7 +216,9 @@ def handle_pending(notification: Dict[str, Any], gateway_config: GatewayConfig):
reason = notification.get("reason", "-")
msg = f"Adyen: The transaction {transaction_id} is pending. Reason: {reason}"
- create_payment_notification_for_order(payment, msg, None, transaction.is_success)
+ create_payment_notification_for_order(
+ payment, msg, None, new_transaction.is_success
+ )
def handle_refund(notification: Dict[str, Any], _gateway_config: GatewayConfig):
@@ -220,8 +239,10 @@ def handle_refund(notification: Dict[str, Any], _gateway_config: GatewayConfig):
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
+ payment, success_msg, failed_msg, new_transaction.is_success
)
+ if payment.order:
+ order_refunded(payment.order, None, transaction.amount, payment)
def handle_failed_refund(notification: Dict[str, Any], _gateway_config: GatewayConfig):
@@ -244,7 +265,7 @@ def handle_failed_refund(notification: Dict[str, Any], _gateway_config: GatewayC
f" receive more than two failures on the same refund, contact Adyen Support "
f"Team. Reason: {reason}"
)
- create_payment_notification_for_order(payment, msg, msg, transaction.is_success)
+ create_payment_notification_for_order(payment, msg, msg, new_transaction.is_success)
def handle_reversed_refund(
@@ -272,7 +293,7 @@ def handle_reversed_refund(
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, transaction.is_success)
+ create_payment_notification_for_order(payment, msg, msg, True)
def handle_refund_with_data(
@@ -296,8 +317,10 @@ def handle_refund_with_data(
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
+ payment, success_msg, failed_msg, new_transaction.is_success
)
+ if payment.order:
+ order_refunded(payment.order, None, transaction.amount, payment)
def webhook_not_implemented(