Skip to content

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

Adyen add void, rebuild confirm, lock payment changes (#5985)

Maciej Korycinskiad463728907a
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index df06670695..9f5bc2451d 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -205,6 +205,7 @@ class PaymentCapture(BaseMutation):
)
try:
gateway.capture(payment, amount)
+ payment.refresh_from_db()
except PaymentError as e:
raise ValidationError(str(e), code=PaymentErrorCode.PAYMENT_ERROR)
return PaymentCapture(payment=payment)
@@ -224,6 +225,7 @@ class PaymentRefund(PaymentCapture):
)
try:
gateway.refund(payment, amount=amount)
+ payment.refresh_from_db()
except PaymentError as e:
raise ValidationError(str(e), code=PaymentErrorCode.PAYMENT_ERROR)
return PaymentRefund(payment=payment)
@@ -248,6 +250,7 @@ class PaymentVoid(BaseMutation):
)
try:
gateway.void(payment)
+ payment.refresh_from_db()
except PaymentError as e:
raise ValidationError(str(e), code=PaymentErrorCode.PAYMENT_ERROR)
return PaymentVoid(payment=payment)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 0bb77c3556..1dbe3ace45 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -5028,6 +5028,7 @@ enum TransactionError {
enum TransactionKind {
AUTH
PENDING
+ ACTION_TO_CONFIRM
REFUND
REFUND_ONGOING
CAPTURE
diff --git a/saleor/order/events.py b/saleor/order/events.py
index de666b81f5..b588ad4f2a 100644
--- a/saleor/order/events.py
+++ b/saleor/order/events.py
@@ -261,14 +261,12 @@ def payment_failed_event(
def external_notification_event(
- *, order: Order, user: UserType, message: Optional[str], payment: Payment
+ *, order: Order, user: UserType, message: Optional[str], parameters: Optional[dict]
) -> OrderEvent:
if not _user_is_valid(user):
user = None
- parameters = {"message": message}
-
- if payment:
- parameters.update({"service": payment.gateway, "id": payment.token})
+ parameters = parameters or {}
+ parameters["message"] = message
return OrderEvent.objects.create(
order=order,
diff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.py
index db8a8a25e4..faf1733352 100644
--- a/saleor/payment/__init__.py
+++ b/saleor/payment/__init__.py
@@ -60,6 +60,7 @@ class TransactionKind:
AUTH = "auth"
CAPTURE = "capture"
CAPTURE_FAILED = "capture_failed"
+ ACTION_TO_CONFIRM = "action_to_confirm"
VOID = "void"
PENDING = "pending"
REFUND = "refund"
@@ -74,6 +75,7 @@ class TransactionKind:
CHOICES = [
(AUTH, "Authorization"),
(PENDING, "Pending"),
+ (ACTION_TO_CONFIRM, "Action to confirm"),
(REFUND, "Refund"),
(REFUND_ONGOING, "Refund in progress"),
(CAPTURE, "Capture"),
diff --git a/saleor/payment/gateway.py b/saleor/payment/gateway.py
index 19705c86dd..1c8b654b23 100644
--- a/saleor/payment/gateway.py
+++ b/saleor/payment/gateway.py
@@ -2,6 +2,8 @@ import logging
from decimal import Decimal
from typing import TYPE_CHECKING, Callable, List, Optional
+from django.db import transaction
+
from ..payment.interface import TokenConfig
from ..plugins.manager import get_plugins_manager
from . import GatewayError, PaymentError, TransactionKind
@@ -10,8 +12,8 @@ from .utils import (
clean_authorize,
clean_capture,
create_payment_information,
- create_transaction,
gateway_postprocess,
+ get_already_processed_transaction_or_create_new_transaction,
update_payment_method_details,
validate_gateway_response,
)
@@ -54,9 +56,21 @@ def require_active_payment(fn: Callable) -> Callable:
return wrapped
-@payment_postprocess
+def with_locked_payment(fn: Callable) -> Callable:
+ """Lock payment to protect from asynchronous modification."""
+
+ def wrapped(payment: Payment, *args, **kwargs):
+ with transaction.atomic():
+ payment = Payment.objects.select_for_update().get(id=payment.id)
+ return fn(payment, *args, **kwargs)
+
+ return wrapped
+
+
@raise_payment_error
@require_active_payment
+@with_locked_payment
+@payment_postprocess
def process_payment(
payment: Payment,
token: str,
@@ -70,13 +84,14 @@ def process_payment(
store_source=store_source,
additional_data=additional_data,
)
+
response, error = _fetch_gateway_response(
plugin_manager.process_payment, payment.gateway, payment_data
)
action_required = response is not None and response.action_required
if response and response.payment_method_info:
update_payment_method_details(payment, response)
- return create_transaction(
+ return get_already_processed_transaction_or_create_new_transaction(
payment=payment,
kind=TransactionKind.CAPTURE,
action_required=action_required,
@@ -86,9 +101,10 @@ def process_payment(
)
-@payment_postprocess
@raise_payment_error
@require_active_payment
+@with_locked_payment
+@payment_postprocess
def authorize(payment: Payment, token: str, store_source: bool = False) -> Transaction:
plugin_manager = get_plugins_manager()
clean_authorize(payment)
@@ -100,7 +116,7 @@ def authorize(payment: Payment, token: str, store_source: bool = False) -> Trans
)
if response and response.payment_method_info:
update_payment_method_details(payment, response)
- return create_transaction(
+ return get_already_processed_transaction_or_create_new_transaction(
payment=payment,
kind=TransactionKind.AUTH,
payment_information=payment_data,
@@ -112,6 +128,8 @@ def authorize(payment: Payment, token: str, store_source: bool = False) -> Trans
@payment_postprocess
@raise_payment_error
@require_active_payment
+@with_locked_payment
+@payment_postprocess
def capture(
payment: Payment, amount: Decimal = None, store_source: bool = False
) -> Transaction:
@@ -128,7 +146,7 @@ def capture(
)
if response and response.payment_method_info:
update_payment_method_details(payment, response)
- return create_transaction(
+ return get_already_processed_transaction_or_create_new_transaction(
payment=payment,
kind=TransactionKind.CAPTURE,
payment_information=payment_data,
@@ -137,9 +155,10 @@ def capture(
)
-@payment_postprocess
@raise_payment_error
@require_active_payment
+@with_locked_payment
+@payment_postprocess
def refund(payment: Payment, amount: Decimal = None) -> Transaction:
plugin_manager = get_plugins_manager()
if amount is None:
@@ -154,7 +173,7 @@ def refund(payment: Payment, amount: Decimal = None) -> Transaction:
response, error = _fetch_gateway_response(
plugin_manager.refund_payment, payment.gateway, payment_data
)
- return create_transaction(
+ return get_already_processed_transaction_or_create_new_transaction(
payment=payment,
kind=TransactionKind.REFUND,
payment_information=payment_data,
@@ -163,9 +182,10 @@ def refund(payment: Payment, amount: Decimal = None) -> Transaction:
)
-@payment_postprocess
@raise_payment_error
@require_active_payment
+@with_locked_payment
+@payment_postprocess
def void(payment: Payment) -> Transaction:
plugin_manager = get_plugins_manager()
token = _get_past_transaction_token(payment, TransactionKind.AUTH)
@@ -173,7 +193,7 @@ def void(payment: Payment) -> Transaction:
response, error = _fetch_gateway_response(
plugin_manager.void_payment, payment.gateway, payment_data
)
- return create_transaction(
+ return get_already_processed_transaction_or_create_new_transaction(
payment=payment,
kind=TransactionKind.VOID,
payment_information=payment_data,
@@ -182,19 +202,20 @@ def void(payment: Payment) -> Transaction:
)
-@payment_postprocess
@raise_payment_error
@require_active_payment
+@with_locked_payment
+@payment_postprocess
def confirm(payment: Payment, additional_data: Optional[dict] = None) -> Transaction:
plugin_manager = get_plugins_manager()
- token = _get_past_transaction_token(payment, TransactionKind.CAPTURE)
+ token = _get_past_transaction_token(payment, TransactionKind.ACTION_TO_CONFIRM)
payment_data = create_payment_information(
payment=payment, payment_token=token, additional_data=additional_data
)
response, error = _fetch_gateway_response(
plugin_manager.confirm_payment, payment.gateway, payment_data
)
- return create_transaction(
+ return get_already_processed_transaction_or_create_new_transaction(
payment=payment,
kind=TransactionKind.CONFIRM,
payment_information=payment_data,
@@ -236,8 +257,8 @@ def _fetch_gateway_response(fn, *args, **kwargs):
def _get_past_transaction_token(
payment: Payment, kind: str # for kind use "TransactionKind"
-):
- txn = payment.transactions.filter(kind=kind, is_success=True).first()
+) -> Optional[str]:
+ txn = payment.transactions.filter(kind=kind, is_success=True).last()
if txn is None:
raise PaymentError(f"Cannot find successful {kind} transaction.")
return txn.token
diff --git a/saleor/payment/gateways/adyen/plugin.py b/saleor/payment/gateways/adyen/plugin.py
index a6188e0f56..2e9eee08e6 100644
--- a/saleor/payment/gateways/adyen/plugin.py
+++ b/saleor/payment/gateways/adyen/plugin.py
@@ -24,6 +24,7 @@ from .utils import (
call_capture,
request_data_for_gateway_config,
request_data_for_payment,
+ request_for_payment_cancel,
request_for_payment_refund,
update_payment_with_action_required_data,
)
@@ -199,10 +200,7 @@ class AdyenGatewayPlugin(BasePlugin):
return handle_webhook(request, config)
elif path.startswith(ADDITIONAL_ACTION_PATH):
return handle_additional_actions(
- request,
- self.adyen.checkout.payments_details,
- config.connection_params["adyen_auto_capture"],
- config.auto_capture,
+ request, self.adyen.checkout.payments_details,
)
return HttpResponseNotFound()
@@ -276,8 +274,14 @@ class AdyenGatewayPlugin(BasePlugin):
elif adyen_auto_capture:
kind = TransactionKind.CAPTURE
+ 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
- if self.config.auto_capture and result_code == AUTH_STATUS:
+ elif self.config.auto_capture and result_code == AUTH_STATUS:
kind = TransactionKind.CAPTURE
result = call_capture(
payment_information=payment_information,
@@ -285,14 +289,6 @@ class AdyenGatewayPlugin(BasePlugin):
token=result.message.get("pspReference"),
adyen_client=self.adyen,
)
-
- 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", []),
- )
-
return GatewayResponse(
is_success=is_success,
action_required="action" in result.message,
@@ -323,11 +319,38 @@ class AdyenGatewayPlugin(BasePlugin):
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:
+ 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:
+ response = self.capture_payment(
+ payment_information, amount=payment_information.amount
+ )
+ is_success = response.is_success
+
+ 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.get("pspReference", ""),
+ error=result.message.get("refusalReason"),
+ raw_response=result.message,
+ )
+
@require_active_plugin
def confirm_payment(
self, payment_information: "PaymentData", previous_value
) -> "GatewayResponse":
-
+ 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()
@@ -336,48 +359,62 @@ class AdyenGatewayPlugin(BasePlugin):
transaction = (
payment.transactions.filter(
- payment__id=payment_information.payment_id,
- kind__in=[TransactionKind.AUTH, TransactionKind.CAPTURE],
+ kind=TransactionKind.ACTION_TO_CONFIRM,
is_success=True,
+ action_required=False,
)
.exclude(token__isnull=True, token__exact="")
.last()
)
- if transaction:
- # We already have the Auth/Capture transaction which means that payment was
- # confirmed asynchronous
- return GatewayResponse(
- is_success=transaction.is_success,
- action_required=False,
- kind=TransactionKind.CONFIRM,
- amount=transaction.amount,
- currency=transaction.currency,
- transaction_id=transaction.token,
- error=None,
- raw_response={},
+
+ 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)
+
+ # 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
+ if not transaction_already_processed and config.auto_capture:
+ response = self.capture_payment(
+ payment_information, amount=transaction.amount
)
- additional_data = payment_information.data
- if not additional_data:
- raise PaymentError("Unable to finish the payment.")
+ is_success = response.is_success
+
+ token = transaction.token
+ if transaction_already_processed:
+ token = transaction_already_processed.token
- result = api_call(additional_data, self.adyen.checkout.payments)
- is_success = result.message["resultCode"].strip().lower() not in FAILED_STATUSES
return GatewayResponse(
is_success=is_success,
- action_required="action" in result.message,
- kind=TransactionKind.CONFIRM,
- amount=payment_information.amount,
- currency=payment_information.currency,
- transaction_id=result.get("pspReference", ""),
- error=result.message.get("refusalReason"),
- raw_response=result.message,
+ action_required=False,
+ kind=kind,
+ amount=payment_information.amount, # type: ignore
+ currency=payment_information.currency, # type: ignore
+ transaction_id=token, # type: ignore
+ error=None,
+ raw_response={},
+ transaction_already_processed=bool(transaction_already_processed),
)
@require_active_plugin
def refund_payment(
self, payment_information: "PaymentData", previous_value
) -> "GatewayResponse":
-
# we take Auth kind because it contains the transaction id that we need
transaction = (
Transaction.objects.filter(
@@ -442,3 +479,25 @@ class AdyenGatewayPlugin(BasePlugin):
error="",
raw_response=result.message,
)
+
+ @require_active_plugin
+ def void_payment(
+ self, payment_information: "PaymentData", previous_value
+ ) -> "GatewayResponse":
+ request = request_for_payment_cancel(
+ payment_information=payment_information,
+ merchant_account=self.config.connection_params["merchant_account"],
+ token=payment_information.token, # type: ignore
+ )
+ 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="",
+ raw_response=result.message,
+ )
diff --git a/saleor/payment/gateways/adyen/tests/cassettes/test_void_payment.yaml b/saleor/payment/gateways/adyen/tests/cassettes/test_void_payment.yaml
new file mode 100644
index 0000000000..8fad615154
--- /dev/null
+++ b/saleor/payment/gateways/adyen/tests/cassettes/test_void_payment.yaml
@@ -0,0 +1,46 @@
+interactions:
+- request:
+ body: '{"merchantAccount": "SaleorECOM", "originalReference": "883597146907178J",
+ "reference": "UGF5bWVudDoz", "applicationInfo": {"adyenLibrary": {"name": "adyen-python-api-library",
+ "version": "3.0.0"}}}'
+ headers:
+ Accept:
+ - '*/*'
+ Accept-Encoding:
+ - gzip, deflate
+ Connection:
+ - keep-alive
+ Content-Length:
+ - '198'
+ Content-Type:
+ - application/json
+ User-Agent:
+ - adyen-python-api-library/3.0.0
+ x-api-key:
+ - test_key
+ method: POST
+ uri: https://pal-test.adyen.com/pal/servlet/Payment/v49/cancel
+ response:
+ body:
+ string: '{"pspReference":"853597151490739D","response":"[cancel-received]"}'
+ headers:
+ Connection:
+ - Keep-Alive
+ Content-Type:
+ - application/json;charset=utf-8
+ Date:
+ - Tue, 11 Aug 2020 13:11:30 GMT
+ Keep-Alive:
+ - timeout=15, max=100
+ Server:
+ - Apache
+ Set-Cookie:
+ - JSESSIONID=9AD68D1916B666D0038F370BB8343FC0.test4e; Path=/pal; Secure; HttpOnly
+ Transfer-Encoding:
+ - chunked
+ pspReference:
+ - 853597151490739D
+ status:
+ code: 200
+ message: '200'
+version: 1
diff --git a/saleor/payment/gateways/adyen/tests/test_plugin.py b/saleor/payment/gateways/adyen/tests/test_plugin.py
index 93112b42fd..1b86909952 100644
--- a/saleor/payment/gateways/adyen/tests/test_plugin.py
+++ b/saleor/payment/gateways/adyen/tests/test_plugin.py
@@ -211,7 +211,7 @@ def test_process_payment_additional_action_checkout_does_not_exists(
def test_confirm_payment(payment_adyen_for_order, adyen_plugin):
payment_info = create_payment_information(payment_adyen_for_order,)
gateway_response = GatewayResponse(
- kind=TransactionKind.AUTH,
+ kind=TransactionKind.ACTION_TO_CONFIRM,
action_required=False,
transaction_id="882595494831959A",
is_success=True,
@@ -221,7 +221,42 @@ def test_confirm_payment(payment_adyen_for_order, adyen_plugin):
raw_response={},
)
- auth_transaction = create_transaction(
+ 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_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="",
+ raw_response={},
+ )
+ 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,
@@ -231,8 +266,39 @@ def test_confirm_payment(payment_adyen_for_order, 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.CONFIRM
+ assert response.kind == TransactionKind.AUTH
+ assert response.amount == action_transaction.amount
+ assert response.currency == action_transaction.currency
+ assert payment_adyen_for_order.transactions.count() == 2
+
+
+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="",
+ raw_response={},
+ )
+
+ 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
@@ -278,6 +344,36 @@ def test_refund_payment(payment_adyen_for_order, order_with_lines, adyen_plugin)
assert response.transaction_id == "882595499620961A" # ID returned by Adyen
+def test_void_payment(payment_adyen_for_order, order_with_lines, adyen_plugin):
+ payment_info = create_payment_information(payment_adyen_for_order,)
+ gateway_response = GatewayResponse(
+ kind=TransactionKind.AUTH,
+ action_required=False,
+ transaction_id="883597146907178J",
+ is_success=True,
+ amount=payment_info.amount,
+ currency=payment_info.currency,
+ error="",
+ raw_response={},
+ )
+ 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("1234")
+ assert response.currency == order_with_lines.currency
+ assert response.transaction_id == "853597151490739D" # ID returned by Adyen
+
+
@pytest.mark.vcr
def test_capture_payment(payment_adyen_for_order, order_with_lines, adyen_plugin):
payment_info = create_payment_information(
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 28821f53f7..4f8e2692b8 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
@@ -6,7 +6,6 @@ from urllib.parse import quote_plus
import graphene
from ..... import PaymentError, TransactionKind
-from .....models import Transaction
from ...webhooks import handle_additional_actions
@@ -35,9 +34,7 @@ def test_handle_additional_actions_post(api_call_mock, payment_adyen_for_checkou
api_call_mock.return_value.message = message
# when
- response = handle_additional_actions(
- request_mock, payment_details_mock, False, False
- )
+ response = handle_additional_actions(request_mock, payment_details_mock)
# then
payment_adyen_for_checkout.refresh_from_db()
@@ -49,7 +46,7 @@ def test_handle_additional_actions_post(api_call_mock, payment_adyen_for_checkou
payment_adyen_for_checkout.transactions.all().count() == transaction_count + 1
)
transaction = payment_adyen_for_checkout.transactions.last()
- assert transaction.kind == "auth"
+ assert transaction.kind == TransactionKind.ACTION_TO_CONFIRM
@mock.patch("saleor.payment.gateways.adyen.webhooks.api_call")
@@ -80,53 +77,7 @@ def test_handle_additional_actions_get(api_call_mock, payment_adyen_for_checkout
api_call_mock.return_value.message = message
# when
- response = handle_additional_actions(
- request_mock, payment_details_mock, False, False
- )
-
- # 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
- assert (
- payment_adyen_for_checkout.transactions.all().count() == transaction_count + 1
- )
- transaction = payment_adyen_for_checkout.transactions.last()
- assert transaction.kind == "auth"
-
-
[email protected]("saleor.payment.gateways.adyen.webhooks.api_call")
-def test_handle_additional_actions_adyen_auto_capture(
- 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(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": 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, True, False
- )
+ response = handle_additional_actions(request_mock, payment_details_mock)
# then
payment_adyen_for_checkout.refresh_from_db()
@@ -138,65 +89,7 @@ def test_handle_additional_actions_adyen_auto_capture(
payment_adyen_for_checkout.transactions.all().count() == transaction_count + 1
)
transaction = payment_adyen_for_checkout.transactions.last()
- assert transaction.kind == "capture"
-
-
[email protected]("saleor.payment.gateways.adyen.webhooks.capture")
[email protected]("saleor.payment.gateways.adyen.webhooks.api_call")
-def test_handle_additional_actions_auto_capture(
- api_call_mock, capture_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(update_fields=["extra_data"])
-
- payment_adyen_for_checkout.transactions.create(
- amount=payment_adyen_for_checkout.total,
- kind=TransactionKind.AUTH,
- gateway_response={},
- is_success=True,
- )
-
- 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": checkout.pk}
- request_mock.POST = {"payload": "test"}
-
- payment_details_mock = mock.Mock()
- message = {
- "resultCode": "Test",
- }
- api_call_mock.return_value.message = message
-
- capture_mock.return_value = Transaction.objects.create(
- payment=payment_adyen_for_checkout,
- action_required=False,
- kind=TransactionKind.CAPTURE,
- gateway_response={},
- is_success=True,
- )
-
- # when
- response = handle_additional_actions(
- request_mock, payment_details_mock, False, True
- )
-
- # 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
- assert (
- payment_adyen_for_checkout.transactions.all().count() == transaction_count + 2
- )
+ assert transaction.kind == TransactionKind.ACTION_TO_CONFIRM
def test_handle_additional_actions_more_action_required(payment_adyen_for_checkout):
@@ -228,9 +121,7 @@ def test_handle_additional_actions_more_action_required(payment_adyen_for_checko
payment_details_mock.return_value.message = message
# when
- response = handle_additional_actions(
- request_mock, payment_details_mock, False, False
- )
+ response = handle_additional_actions(request_mock, payment_details_mock)
# then
assert response.status_code == 302
@@ -242,6 +133,10 @@ def test_handle_additional_actions_more_action_required(payment_adyen_for_checko
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
+
def test_handle_additional_actions_payment_does_not_exist(payment_adyen_for_checkout):
# given
@@ -266,9 +161,7 @@ def test_handle_additional_actions_payment_does_not_exist(payment_adyen_for_chec
payment_adyen_for_checkout.delete()
# when
- response = handle_additional_actions(
- request_mock, payment_details_mock, False, False
- )
+ response = handle_additional_actions(request_mock, payment_details_mock)
# then
assert response.status_code == 404
@@ -302,9 +195,7 @@ def test_handle_additional_actions_payment_lack_of_return_url(
}
# when
- response = handle_additional_actions(
- request_mock, payment_details_mock, False, False
- )
+ response = handle_additional_actions(request_mock, payment_details_mock)
# then
assert response.status_code == 404
@@ -332,9 +223,7 @@ def test_handle_additional_actions_no_payment_id_in_get(payment_adyen_for_checko
payment_details_mock.return_value.message = message
# when
- response = handle_additional_actions(
- request_mock, payment_details_mock, False, False
- )
+ response = handle_additional_actions(request_mock, payment_details_mock)
# then
assert response.status_code == 404
@@ -362,9 +251,7 @@ def test_handle_additional_actions_checkout_not_related_to_payment(
payment_details_mock.return_value.message = message
# when
- response = handle_additional_actions(
- request_mock, payment_details_mock, False, False
- )
+ response = handle_additional_actions(request_mock, payment_details_mock)
# then
assert response.status_code == 404
@@ -397,9 +284,7 @@ def test_handle_additional_actions_payment_does_not_have_checkout(
payment_details_mock.return_value.message = message
# when
- response = handle_additional_actions(
- request_mock, payment_details_mock, False, False
- )
+ response = handle_additional_actions(request_mock, payment_details_mock)
# then
assert response.status_code == 404
@@ -438,9 +323,7 @@ def test_handle_additional_actions_api_call_error(
payment_details_mock.return_value.message = message
# when
- response = handle_additional_actions(
- request_mock, payment_details_mock, False, False
- )
+ response = handle_additional_actions(request_mock, payment_details_mock)
# then
assert response.status_code == 400
@@ -469,9 +352,7 @@ def test_handle_additional_actions_payment_not_active(payment_adyen_for_checkout
payment_details_mock.return_value.message = message
# when
- response = handle_additional_actions(
- request_mock, payment_details_mock, False, False
- )
+ response = handle_additional_actions(request_mock, payment_details_mock)
# then
assert response.status_code == 404
@@ -505,9 +386,7 @@ def test_handle_additional_actions_payment_with_no_adyen_gateway(
payment_details_mock.return_value.message = message
# when
- response = handle_additional_actions(
- request_mock, payment_details_mock, False, False
- )
+ response = handle_additional_actions(request_mock, payment_details_mock)
# then
assert response.status_code == 404
@@ -541,9 +420,7 @@ def test_handle_additional_actions_lack_of_parameter_in_request(
api_call_mock.return_value.message = message
# when
- response = handle_additional_actions(
- request_mock, payment_details_mock, False, False
- )
+ response = handle_additional_actions(request_mock, payment_details_mock)
# then
payment_adyen_for_checkout.refresh_from_db()
diff --git a/saleor/payment/gateways/adyen/utils.py b/saleor/payment/gateways/adyen/utils.py
index b71e898005..d9c7bbf7c3 100644
--- a/saleor/payment/gateways/adyen/utils.py
+++ b/saleor/payment/gateways/adyen/utils.py
@@ -256,3 +256,13 @@ def call_capture(
token=token,
)
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,
+ }
diff --git a/saleor/payment/gateways/adyen/webhooks.py b/saleor/payment/gateways/adyen/webhooks.py
index 690aeaa161..630335607f 100644
--- a/saleor/payment/gateways/adyen/webhooks.py
+++ b/saleor/payment/gateways/adyen/webhooks.py
@@ -40,15 +40,23 @@ from .utils import FAILED_STATUSES, api_call, from_adyen_price
def get_payment(payment_id: Optional[str]) -> Optional[Payment]:
if not payment_id:
return None
- _type, payment_id = from_global_id(payment_id)
- payment = Payment.objects.prefetch_related("order").filter(id=payment_id).first()
+ try:
+ _type, db_payment_id = from_global_id(payment_id)
+ except UnicodeDecodeError:
+ return None
+ payment = (
+ Payment.objects.prefetch_related("order")
+ .select_related()
+ .filter(id=db_payment_id)
+ .first()
+ )
return payment
def get_transaction(
payment: "Payment", transaction_id: Optional[str], kind: str,
) -> Optional[Transaction]:
- transaction = payment.transactions.filter(kind=kind, token=transaction_id).first()
+ transaction = payment.transactions.filter(kind=kind, token=transaction_id).last()
return transaction
@@ -86,7 +94,10 @@ def create_payment_notification_for_order(
msg = success_msg if is_success else failed_msg
external_notification_event(
- order=payment.order, user=None, message=msg, payment=payment
+ order=payment.order,
+ user=None,
+ message=msg,
+ parameters={"service": payment.gateway, "id": payment.token},
)
@@ -108,10 +119,13 @@ def handle_authorization(notification: Dict[str, Any], gateway_config: GatewayCo
transaction_id = notification.get("pspReference")
transaction = payment.transactions.filter(
- token=transaction_id, kind__in=[TransactionKind.AUTH, TransactionKind.CAPTURE]
- ).first()
+ token=transaction_id,
+ action_required=False,
+ is_success=True,
+ kind__in=[TransactionKind.AUTH, TransactionKind.CAPTURE],
+ ).last()
- if transaction and transaction.is_success:
+ if transaction:
# We already have this transaction
return
@@ -504,14 +518,11 @@ def handle_webhook(request: WSGIRequest, gateway_config: "GatewayConfig"):
if event_handler:
event_handler(notification, gateway_config)
return HttpResponse("[accepted]")
- return HttpResponseNotFound()
+ return HttpResponse("[accepted]")
def handle_additional_actions(
- request: WSGIRequest,
- payment_details: Callable,
- adyen_auto_capture: bool,
- auto_capture: bool,
+ request: WSGIRequest, payment_details: Callable,
):
payment_id = request.GET.get("payment")
checkout_pk = request.GET.get("checkout")
@@ -552,7 +563,7 @@ def handle_additional_actions(
except PaymentError as e:
return HttpResponseBadRequest(str(e))
- handle_api_response(payment, result, adyen_auto_capture, auto_capture)
+ handle_api_response(payment, result)
redirect_url = prepare_redirect_url(payment_id, checkout_pk, result, return_url)
return redirect(redirect_url)
@@ -605,15 +616,8 @@ def prepare_redirect_url(
def handle_api_response(
- payment: Payment,
- response: Adyen.Adyen,
- adyen_auto_capture: bool,
- auto_capture: bool,
+ payment: Payment, response: Adyen.Adyen,
):
- kind = TransactionKind.AUTH
- if adyen_auto_capture:
- kind = TransactionKind.CAPTURE
-
payment_data = create_payment_information(
payment=payment, payment_token=payment.token,
)
@@ -623,13 +627,14 @@ def handle_api_response(
result_code = response.message["resultCode"].strip().lower()
is_success = result_code not in FAILED_STATUSES
- # action_required is True as we want to call gateway.confirm from the
- # checkoutComplete mutation
+ action_required = False
+ if "action" in response.message:
+ action_required = True
gateway_response = GatewayResponse(
is_success=is_success,
- action_required=True,
- kind=kind,
+ action_required=action_required,
+ kind=TransactionKind.ACTION_TO_CONFIRM,
amount=payment_data.amount,
currency=payment_data.currency,
transaction_id=response.message.get("pspReference", ""),
@@ -638,15 +643,10 @@ def handle_api_response(
action_required_data=response.message.get("action"),
)
- transaction = create_transaction(
+ create_transaction(
payment=payment,
- kind=kind,
- action_required=True,
+ kind=TransactionKind.ACTION_TO_CONFIRM,
+ action_required=action_required,
payment_information=payment_data,
gateway_response=gateway_response,
)
-
- if auto_capture:
- transaction = capture(payment, amount=transaction.amount)
-
- gateway_postprocess(transaction, payment)
diff --git a/saleor/payment/gateways/dummy/tests/test_dummy.py b/saleor/payment/gateways/dummy/tests/test_dummy.py
index dab6f8f503..9882d255c5 100644
--- a/saleor/payment/gateways/dummy/tests/test_dummy.py
+++ b/saleor/payment/gateways/dummy/tests/test_dummy.py
@@ -166,6 +166,8 @@ def test_refund_success(
payment.captured_amount = initial_captured_amount
payment.save()
txn = gateway.refund(payment=payment, amount=Decimal(refund_amount))
+
+ payment.refresh_from_db()
assert txn.kind == TransactionKind.REFUND
assert txn.is_success
assert txn.payment == payment
diff --git a/saleor/payment/gateways/dummy_credit_card/tests/test_dummy_credit_card.py b/saleor/payment/gateways/dummy_credit_card/tests/test_dummy_credit_card.py
index 22aeb0bd63..e3f32954f1 100644
--- a/saleor/payment/gateways/dummy_credit_card/tests/test_dummy_credit_card.py
+++ b/saleor/payment/gateways/dummy_credit_card/tests/test_dummy_credit_card.py
@@ -170,6 +170,7 @@ def test_void_method_error(dummy_payment_data, dummy_gateway_config, monkeypatch
)
def test_capture_success(amount, charge_status, token, payment_txn_preauth):
payment_txn_preauth.gateway = "mirumee.payments.dummy_credit_card"
+ payment_txn_preauth.save()
transaction = payment_txn_preauth.transactions.last()
transaction.token = token
transaction.save()
@@ -264,6 +265,8 @@ def test_refund_success(
payment.captured_amount = initial_captured_amount
payment.save()
txn = gateway.refund(payment=payment, amount=Decimal(refund_amount))
+
+ payment.refresh_from_db()
assert txn.kind == TransactionKind.REFUND
assert txn.is_success
assert txn.payment == payment
diff --git a/saleor/payment/interface.py b/saleor/payment/interface.py
index 1334dea563..31bd7212a3 100644
--- a/saleor/payment/interface.py
+++ b/saleor/payment/interface.py
@@ -37,6 +37,9 @@ class GatewayResponse:
payment_method_info: Optional[PaymentMethodInfo] = None
raw_response: Optional[Dict[str, str]] = None
action_required_data: Optional[JSONType] = None
+ # Some gateway can process transaction asynchronously. This value define if we
+ # should create new transaction based on this response
+ transaction_already_processed: bool = False
@dataclass
diff --git a/saleor/payment/migrations/0019_auto_20200812_1028.py b/saleor/payment/migrations/0019_auto_20200812_1028.py
new file mode 100644
index 0000000000..43dfbd986d
--- /dev/null
+++ b/saleor/payment/migrations/0019_auto_20200812_1028.py
@@ -0,0 +1,36 @@
+# Generated by Django 3.1 on 2020-08-12 10:28
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("payment", "0018_auto_20200810_1310"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="transaction",
+ name="already_processed",
+ field=models.BooleanField(default=False),
+ ),
+ migrations.AlterField(
+ model_name="transaction",
+ name="kind",
+ field=models.CharField(
+ choices=[
+ ("auth", "Authorization"),
+ ("pending", "Pending"),
+ ("action_to_confirm", "Action to confirm"),
+ ("refund", "Refund"),
+ ("refund_ongoing", "Refund in progress"),
+ ("capture", "Capture"),
+ ("void", "Void"),
+ ("confirm", "Confirm"),
+ ("cancel", "Cancel"),
+ ],
+ max_length=25,
+ ),
+ ),
+ ]
diff --git a/saleor/payment/models.py b/saleor/payment/models.py
index 4b6b66af77..3a17f6a628 100644
--- a/saleor/payment/models.py
+++ b/saleor/payment/models.py
@@ -125,7 +125,9 @@ class Payment(models.Model):
authorized_txns = [
txn
for txn in transactions
- if txn.kind == TransactionKind.AUTH and txn.is_success
+ if txn.kind == TransactionKind.AUTH
+ and txn.is_success
+ and not txn.action_required
]
# Calculate authorized amount from all succeeded auth transactions
@@ -147,7 +149,9 @@ class Payment(models.Model):
def is_authorized(self):
return any(
[
- txn.kind == TransactionKind.AUTH and txn.is_success
+ txn.kind == TransactionKind.AUTH
+ and txn.is_success
+ and not txn.action_required
for txn in self.transactions.all()
]
)
@@ -214,6 +218,7 @@ class Transaction(models.Model):
)
customer_id = models.CharField(max_length=256, null=True)
gateway_response = JSONField(encoder=DjangoJSONEncoder)
+ already_processed = models.BooleanField(default=False)
class Meta:
ordering = ("pk",)
diff --git a/saleor/payment/tests/test_payment.py b/saleor/payment/tests/test_payment.py
index 772d1f909f..624ad17509 100644
--- a/saleor/payment/tests/test_payment.py
+++ b/saleor/payment/tests/test_payment.py
@@ -264,11 +264,13 @@ def test_gateway_charge_errors(payment_dummy, transaction_token, settings):
assert exc.value.message == "Amount should be a positive number."
payment.charge_status = ChargeStatus.FULLY_REFUNDED
+ payment.save()
with pytest.raises(PaymentError) as exc:
gateway.capture(payment, Decimal("10"))
assert exc.value.message == "This payment cannot be captured."
payment.charge_status = ChargeStatus.NOT_CHARGED
+ payment.save()
with pytest.raises(PaymentError) as exc:
gateway.capture(payment, Decimal("1000000"))
assert exc.value.message == ("Unable to charge more than un-captured amount.")
@@ -285,6 +287,7 @@ def test_gateway_refund_errors(payment_txn_captured):
assert exc.value.message == "Amount should be a positive number."
payment.charge_status = ChargeStatus.NOT_CHARGED
+ payment.save()
with pytest.raises(PaymentError) as exc:
gateway.refund(payment, Decimal("1"))
assert exc.value.message == "This payment cannot be refunded."
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index ddeafa0a2d..c3cbb7c0bf 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -132,6 +132,20 @@ def create_payment(
return payment
+def get_already_processed_transaction(
+ payment: "Payment", gateway_response: GatewayResponse
+):
+ transaction = payment.transactions.filter(
+ is_success=gateway_response.is_success,
+ action_required=gateway_response.action_required,
+ token=gateway_response.transaction_id,
+ kind=gateway_response.kind,
+ amount=gateway_response.amount,
+ currency=gateway_response.currency,
+ ).last()
+ return transaction
+
+
def create_transaction(
payment: Payment,
kind: str,
@@ -171,6 +185,28 @@ def create_transaction(
return txn
+def get_already_processed_transaction_or_create_new_transaction(
+ payment: Payment,
+ kind: str,
+ payment_information: PaymentData,
+ action_required: bool = False,
+ gateway_response: GatewayResponse = None,
+ error_msg=None,
+) -> Transaction:
+ if gateway_response and gateway_response.transaction_already_processed:
+ transaction = get_already_processed_transaction(payment, gateway_response)
+ if transaction:
+ return transaction
+ return create_transaction(
+ payment,
+ kind,
+ payment_information,
+ action_required,
+ gateway_response,
+ error_msg,
+ )
+
+
def clean_capture(payment: Payment, amount: Decimal):
"""Check if payment can be captured."""
if amount <= 0:
@@ -212,12 +248,12 @@ def validate_gateway_response(response: GatewayResponse):
def gateway_postprocess(transaction, payment):
if not transaction.is_success:
return
-
if transaction.action_required:
payment.to_confirm = True
payment.save(update_fields=["to_confirm"])
return
-
+ if transaction.already_processed:
+ return
changed_fields = []
# to_confirm is defined by the transaction.action_required. Payment doesn't
# require confirmation when we got action_required == False
@@ -229,7 +265,6 @@ def gateway_postprocess(transaction, payment):
if transaction_kind in {
TransactionKind.CAPTURE,
- TransactionKind.CONFIRM,
TransactionKind.REFUND_REVERSED,
}:
payment.captured_amount += transaction.amount
@@ -271,6 +306,8 @@ def gateway_postprocess(transaction, payment):
changed_fields += ["charge_status", "captured_amount", "modified"]
if changed_fields:
payment.save(update_fields=changed_fields)
+ transaction.already_processed = True
+ transaction.save(update_fields=["already_processed"])
def fetch_customer_id(user: User, gateway: str):
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index cd23986adf..fdc921cf04 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -1526,7 +1526,7 @@ def payment_txn_to_confirm(order_with_lines, payment_dummy):
payment.transactions.create(
amount=payment.total,
- kind=TransactionKind.CAPTURE,
+ kind=TransactionKind.ACTION_TO_CONFIRM,
gateway_response={},
is_success=True,
action_required=True,