Skip to content

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

Add auto capture flags for Adyen and Saleor (#5956)

Maciej Korycinski4946aa7d4818
diff --git a/saleor/payment/gateway.py b/saleor/payment/gateway.py
index 8b67679a39..c0ffb1150b 100644
--- a/saleor/payment/gateway.py
+++ b/saleor/payment/gateway.py
@@ -122,7 +122,7 @@ def capture(
response, error = _fetch_gateway_response(
plugin_manager.capture_payment, payment.gateway, payment_data
)
- if response.card_info:
+ if response and response.card_info:
update_card_details(payment, response)
return create_transaction(
payment=payment,
diff --git a/saleor/payment/gateways/adyen/plugin.py b/saleor/payment/gateways/adyen/plugin.py
index e6f081d9c1..77d18984b0 100644
--- a/saleor/payment/gateways/adyen/plugin.py
+++ b/saleor/payment/gateways/adyen/plugin.py
@@ -15,9 +15,9 @@ from ...models import Transaction
from ..utils import get_supported_currencies
from .utils import (
api_call,
+ call_capture,
request_data_for_gateway_config,
request_data_for_payment,
- request_for_payment_capture,
request_for_payment_refund,
)
from .webhooks import handle_webhook
@@ -35,7 +35,10 @@ def require_active_plugin(fn):
return wrapped
+# https://docs.adyen.com/checkout/payment-result-codes
FAILED_STATUSES = ["refused", "error", "cancelled"]
+PENDING_STATUSES = ["pending", "received"]
+AUTH_STATUS = "authorised"
class AdyenGatewayPlugin(BasePlugin):
@@ -50,6 +53,7 @@ class AdyenGatewayPlugin(BasePlugin):
{"name": "Origin Url", "value": ""},
{"name": "Live", "value": ""},
{"name": "Automatically mark payment as a capture", "value": True},
+ {"name": "Automatic payment capture", "value": False},
{"name": "HMAC secret key", "value": ""},
{"name": "Notification user", "value": ""},
{"name": "Notification password", "value": ""},
@@ -116,17 +120,17 @@ class AdyenGatewayPlugin(BasePlugin):
"Automatically mark payment as a capture": {
"type": ConfigurationTypeField.BOOLEAN,
"help_text": (
- "Saleor by default doesn't receive notification which payment has "
- "status capture, all sucess payment can be marked as a capture by "
- "default."
- "A payment that is automatically captured does not trigger a "
- "separate CAPTURE notification. If you are using delayed automatic "
- "capture (by having a Capture Delay of a fixed number of days), you "
- "can optionally receive CAPTURE notifications. To enable this "
- "functionality, contact with Adyen Support Team."
+ "All authorized payments will be marked as paid. This should be enabled"
+ " when Adyen uses automatically auto-capture. Saleor doesn't support "
+ "delayed automatically capture."
),
"label": "Automatically mark payment as a capture",
},
+ "Automatic payment capture": {
+ "type": ConfigurationTypeField.BOOLEAN,
+ "help_text": "Determines if Saleor should automaticaly capture payments.",
+ "label": "Automatic payment capture",
+ },
"HMAC secret key": {
"type": ConfigurationTypeField.SECRET,
"help_text": (
@@ -166,7 +170,7 @@ class AdyenGatewayPlugin(BasePlugin):
configuration = {item["name"]: item["value"] for item in self.configuration}
self.config = GatewayConfig(
gateway_name=GATEWAY_NAME,
- auto_capture=configuration["Automatically mark payment as a capture"],
+ auto_capture=configuration["Automatic payment capture"],
supported_currencies=configuration["Supported currencies"],
connection_params={
"api_key": configuration["API key"],
@@ -178,6 +182,9 @@ class AdyenGatewayPlugin(BasePlugin):
"webhook_hmac": configuration["HMAC secret key"],
"webhook_user": configuration["Notification user"],
"webhook_user_password": configuration["Notification password"],
+ "adyen_auto_capture": configuration[
+ "Automatically mark payment as a capture"
+ ],
},
)
api_key = self.config.connection_params["api_key"]
@@ -232,13 +239,26 @@ class AdyenGatewayPlugin(BasePlugin):
merchant_account=self.config.connection_params["merchant_account"],
origin_url=self.config.connection_params["origin_url"],
)
-
result = api_call(request_data, self.adyen.checkout.payments)
- is_success = result.message["resultCode"].strip().lower() not in FAILED_STATUSES
- if self.config.auto_capture:
+ result_code = result.message["resultCode"].strip().lower()
+ is_success = result_code not in FAILED_STATUSES
+ adyen_auto_capture = self.config.connection_params["adyen_auto_capture"]
+ kind = TransactionKind.AUTH
+ if adyen_auto_capture:
kind = TransactionKind.CAPTURE
- else:
- kind = TransactionKind.AUTH
+ elif result_code in PENDING_STATUSES:
+ kind = TransactionKind.PENDING
+
+ # If auto capture is enabled, let's make a capture the auth payment
+ if self.config.auto_capture and result_code == AUTH_STATUS:
+ 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,
+ )
+
return GatewayResponse(
is_success=is_success,
action_required="action" in result.message,
@@ -294,6 +314,7 @@ class AdyenGatewayPlugin(BasePlugin):
) -> "GatewayResponse":
_type, payment_id = from_global_id(payment_information.payment_id)
+ # we take Auth kind because it contains the transaction id that we need
transaction = (
Transaction.objects.filter(
payment__id=payment_id, kind=TransactionKind.AUTH
@@ -338,12 +359,12 @@ class AdyenGatewayPlugin(BasePlugin):
if not transaction:
raise PaymentError("Cannot find a payment reference to capture.")
- request = request_for_payment_capture(
+ result = call_capture(
payment_information=payment_information,
merchant_account=self.config.connection_params["merchant_account"],
token=transaction.token,
+ adyen_client=self.adyen,
)
- result = api_call(request, self.adyen.payment.capture)
return GatewayResponse(
is_success=True,
action_required=False,
diff --git a/saleor/payment/gateways/adyen/tests/cassettes/test_handle_authorization_with_auto_capture.yaml b/saleor/payment/gateways/adyen/tests/cassettes/test_handle_authorization_with_auto_capture.yaml
new file mode 100644
index 0000000000..4115fe24b5
--- /dev/null
+++ b/saleor/payment/gateways/adyen/tests/cassettes/test_handle_authorization_with_auto_capture.yaml
@@ -0,0 +1,47 @@
+interactions:
+- request:
+ body: '{"merchantAccount": "SaleorECOM", "modificationAmount": {"value": "123400",
+ "currency": "USD"}, "originalReference": "853596537720508F", "reference": "UGF5bWVudDoxMA==",
+ "applicationInfo": {"adyenLibrary": {"name": "adyen-python-api-library", "version":
+ "3.0.0"}}}'
+ headers:
+ Accept:
+ - '*/*'
+ Accept-Encoding:
+ - gzip, deflate
+ Connection:
+ - keep-alive
+ Content-Length:
+ - '264'
+ 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/capture
+ response:
+ body:
+ string: '{"pspReference":"853596621736884E","response":"[capture-received]"}'
+ headers:
+ Connection:
+ - Keep-Alive
+ Content-Type:
+ - application/json;charset=utf-8
+ Date:
+ - Wed, 05 Aug 2020 10:02:16 GMT
+ Keep-Alive:
+ - timeout=15, max=100
+ Server:
+ - Apache
+ Set-Cookie:
+ - JSESSIONID=DE99DF461A79A101442FF0B7820C68D1.test4e; Path=/pal; Secure; HttpOnly
+ Transfer-Encoding:
+ - chunked
+ pspReference:
+ - 853596621736884E
+ status:
+ code: 200
+ message: '200'
+version: 1
diff --git a/saleor/payment/gateways/adyen/tests/cassettes/test_process_payment_with_adyen_auto_capture.yaml b/saleor/payment/gateways/adyen/tests/cassettes/test_process_payment_with_adyen_auto_capture.yaml
new file mode 100644
index 0000000000..fcead20271
--- /dev/null
+++ b/saleor/payment/gateways/adyen/tests/cassettes/test_process_payment_with_adyen_auto_capture.yaml
@@ -0,0 +1,48 @@
+interactions:
+- request:
+ body: '{"amount": {"value": "123400", "currency": "USD"}, "reference": "UGF5bWVudDo3",
+ "paymentMethod": {"paymentdata": ""}, "returnUrl": "http://127.0.0.1:3000/",
+ "merchantAccount": "SaleorECOM", "applicationInfo": {"adyenLibrary": {"name":
+ "adyen-python-api-library", "version": "3.0.0"}}}'
+ headers:
+ Accept:
+ - '*/*'
+ Accept-Encoding:
+ - gzip, deflate
+ Connection:
+ - keep-alive
+ Content-Length:
+ - '4444'
+ Content-Type:
+ - application/json
+ User-Agent:
+ - adyen-python-api-library/3.0.0
+ x-api-key:
+ - test_key
+ method: POST
+ uri: https://checkout-test.adyen.com/v49/payments
+ response:
+ body:
+ string: '{"pspReference":"882595494831959A","resultCode":"Authorised","merchantReference":"UGF5bWVudDoz"}'
+ headers:
+ Connection:
+ - Keep-Alive
+ Content-Type:
+ - application/json;charset=UTF-8
+ Date:
+ - Thu, 23 Jul 2020 09:00:31 GMT
+ Keep-Alive:
+ - timeout=15, max=100
+ Server:
+ - Apache
+ Set-Cookie:
+ - JSESSIONID=16B2B5BA678472CFD5D8FEE7C6EB1227.test103e; Path=/checkout; Secure;
+ HttpOnly
+ Transfer-Encoding:
+ - chunked
+ pspReference:
+ - 881595494831497D
+ status:
+ code: 200
+ message: '200'
+version: 1
diff --git a/saleor/payment/gateways/adyen/tests/cassettes/test_process_payment_with_auto_capture.yaml b/saleor/payment/gateways/adyen/tests/cassettes/test_process_payment_with_auto_capture.yaml
index fcead20271..297fa2489c 100644
--- a/saleor/payment/gateways/adyen/tests/cassettes/test_process_payment_with_auto_capture.yaml
+++ b/saleor/payment/gateways/adyen/tests/cassettes/test_process_payment_with_auto_capture.yaml
@@ -1,9 +1,17 @@
interactions:
- request:
- body: '{"amount": {"value": "123400", "currency": "USD"}, "reference": "UGF5bWVudDo3",
- "paymentMethod": {"paymentdata": ""}, "returnUrl": "http://127.0.0.1:3000/",
- "merchantAccount": "SaleorECOM", "applicationInfo": {"adyenLibrary": {"name":
- "adyen-python-api-library", "version": "3.0.0"}}}'
+ body: '{"amount": {"value": "123400", "currency": "USD"}, "reference": "UGF5bWVudDoxNw==",
+ "paymentMethod": {"type": "scheme", "holderName": "John Doe", "encryptedCardNumber":
+ "adyenjs_0_1_25$I4hADbyBrUvNV2Zv+lQcRZdBtj0pYYjRHweEJ7NgT+Lk91H77GhomGxuSuyQKE71qyOdloMBI/dB9AhYLzM3WkkpOdO903XHQfceMHrbfrMw7yYOcLg99bSYx3E0kgr1jgG0bNSnwG6SHW7bZO+ZC+FJ96juHFwjLIIsWVtZ0SCvhXdMdsvQwIGAQ6ry+J7AdVaAcLRWYQRwVl05CaXOTqoSIiwWgrj9nucbQfKVGaoi/eldsFzbs0Ou72ap9piKo0+1wtj4SMjJUPX8WO37uWZUgH2RjKRDCVAZgc7V2DbaZKmU5o9LHyFxEnjn37zTxf+XiEQWxYpfMFJc0+66WA==$rdYYJn4cYOlzPDauDrb5WW7x6RQzzyJrk8RuipaqxsUeGbmkJRh+JKogznXcLoRDltUcFITY2+hsYlfmCMq0Xii8mpBUJfHNJSwz/23/DPykr5uYPDWJctrsxn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9tZmeUxYAZxr4LKH/ELUoRZjaF5W/bO5XBawRLsh+JfaE="},
+ "returnUrl": "http://127.0.0.1:3000/", "merchantAccount": "SaleorECOM", "browserInfo":
+ {"acceptHeader": "*/*", "colorDepth": 24, "language": "en-gb", "javaEnabled":
+ true, "screenHeight": 1440, "screenWidth": 2560, "userAgent": "Mozilla/5.0 (Macintosh;
+ Intel Mac OS X 10_15_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1
+ Safari/605.1.15", "timeZoneOffset": -120}, "applicationInfo": {"adyenLibrary":
+ {"name": "adyen-python-api-library", "version": "3.0.0"}}}'
headers:
Accept:
- '*/*'
@@ -12,36 +20,81 @@ interactions:
Connection:
- keep-alive
Content-Length:
- - '4444'
+ - '4433'
Content-Type:
- application/json
User-Agent:
- adyen-python-api-library/3.0.0
x-api-key:
- - test_key
+ - test_key
method: POST
uri: https://checkout-test.adyen.com/v49/payments
response:
body:
- string: '{"pspReference":"882595494831959A","resultCode":"Authorised","merchantReference":"UGF5bWVudDoz"}'
+ string: '{"pspReference":"883596624248178D","resultCode":"Authorised","merchantReference":"UGF5bWVudDoxNw=="}'
headers:
Connection:
- Keep-Alive
Content-Type:
- application/json;charset=UTF-8
Date:
- - Thu, 23 Jul 2020 09:00:31 GMT
+ - Wed, 05 Aug 2020 10:44:08 GMT
Keep-Alive:
- timeout=15, max=100
Server:
- Apache
Set-Cookie:
- - JSESSIONID=16B2B5BA678472CFD5D8FEE7C6EB1227.test103e; Path=/checkout; Secure;
+ - JSESSIONID=7C62498C2A031656D45B70E9A2F50F69.test3e; Path=/checkout; Secure;
HttpOnly
Transfer-Encoding:
- chunked
pspReference:
- - 881595494831497D
+ - 851596624248090H
+ status:
+ code: 200
+ message: '200'
+- request:
+ body: '{"merchantAccount": "SaleorECOM", "modificationAmount": {"value": "123400",
+ "currency": "USD"}, "originalReference": "883596624248178D", "reference": "UGF5bWVudDoxNw==",
+ "applicationInfo": {"adyenLibrary": {"name": "adyen-python-api-library", "version":
+ "3.0.0"}}}'
+ headers:
+ Accept:
+ - '*/*'
+ Accept-Encoding:
+ - gzip, deflate
+ Connection:
+ - keep-alive
+ Content-Length:
+ - '264'
+ Content-Type:
+ - application/json
+ User-Agent:
+ - adyen-python-api-library/3.0.0
+ x-api-key:
+ - AQEhhmfuXNWTK0Qc+iSDk2g9qPaBhkT1nbWV8YkFf5Sl/5+mEMFdWw2+5HzctViMSCJMYAc=-4yzUVXf8vxvefP8rRR8UOK/fHR34XP+tZmVZZFWntAs=-?[Cv%4@EEx:C5b6f
+ method: POST
+ uri: https://pal-test.adyen.com/pal/servlet/Payment/v49/capture
+ response:
+ body:
+ string: '{"pspReference":"853596624248395G","response":"[capture-received]"}'
+ headers:
+ Connection:
+ - Keep-Alive
+ Content-Type:
+ - application/json;charset=utf-8
+ Date:
+ - Wed, 05 Aug 2020 10:44:08 GMT
+ Keep-Alive:
+ - timeout=15, max=100
+ Server:
+ - Apache
+ Set-Cookie:
+ - JSESSIONID=109BFB126438537FBB7852C4C592655E.test3e; Path=/pal; Secure; HttpOnly
+ Transfer-Encoding:
+ - chunked
+ pspReference:
+ - 853596624248395G
status:
code: 200
message: '200'
diff --git a/saleor/payment/gateways/adyen/tests/conftest.py b/saleor/payment/gateways/adyen/tests/conftest.py
index 780df4a863..3f821704d6 100644
--- a/saleor/payment/gateways/adyen/tests/conftest.py
+++ b/saleor/payment/gateways/adyen/tests/conftest.py
@@ -15,6 +15,7 @@ def adyen_plugin(settings):
return_url=None,
origin_key=None,
origin_url=None,
+ adyen_auto_capture=None,
auto_capture=None,
):
api_key = api_key or "test_key"
@@ -22,6 +23,7 @@ def adyen_plugin(settings):
return_url = return_url or "http://127.0.0.1:3000/"
origin_key = origin_key or "test_origin_key"
origin_url = origin_url or "http://127.0.0.1:3000"
+ adyen_auto_capture = adyen_auto_capture or False
auto_capture = auto_capture or False
settings.PLUGINS = ["saleor.payment.gateways.adyen.plugin.AdyenGatewayPlugin"]
manager = get_plugins_manager()
@@ -37,8 +39,9 @@ def adyen_plugin(settings):
{"name": "Origin Url", "value": origin_url},
{
"name": "Automatically mark payment as a capture",
- "value": auto_capture,
+ "value": adyen_auto_capture,
},
+ {"name": "Automatic payment capture", "value": auto_capture},
{"name": "Supported currencies", "value": "USD"},
],
},
diff --git a/saleor/payment/gateways/adyen/tests/test_plugin.py b/saleor/payment/gateways/adyen/tests/test_plugin.py
index 80f6fccc31..eec849bd0f 100644
--- a/saleor/payment/gateways/adyen/tests/test_plugin.py
+++ b/saleor/payment/gateways/adyen/tests/test_plugin.py
@@ -28,7 +28,7 @@ def test_get_payment_gateway_for_checkout(
}
assert config[1]["field"] == "config"
config = json.loads(config[1]["value"])
- assert isinstance(config, list)
+ assert isinstance(config, dict)
@pytest.mark.vcr
@@ -48,6 +48,25 @@ def test_process_payment(payment_adyen_for_checkout, checkout_with_items, adyen_
assert response.error is None
+def test_process_payment_with_adyen_auto_capture(
+ payment_adyen_for_checkout, checkout_with_items, adyen_plugin
+):
+ payment_info = create_payment_information(
+ payment_adyen_for_checkout,
+ additional_data={"paymentMethod": {"paymentdata": ""}},
+ )
+ adyen_plugin = adyen_plugin(adyen_auto_capture=True)
+ response = adyen_plugin.process_payment(payment_info, None)
+ assert response.is_success is True
+ assert response.action_required is False
+ assert response.kind == TransactionKind.CAPTURE
+ assert response.amount == Decimal("1234")
+ assert response.currency == checkout_with_items.currency
+ assert response.transaction_id == "882595494831959A" # ID returned by Adyen
+ assert response.error is None
+
+
@pytest.mark.vcr
def test_process_payment_with_auto_capture(
payment_adyen_for_checkout, checkout_with_items, adyen_plugin
@@ -63,7 +82,7 @@ def test_process_payment_with_auto_capture(
assert response.kind == TransactionKind.CAPTURE
assert response.amount == Decimal("1234")
assert response.currency == checkout_with_items.currency
- assert response.transaction_id == "882595494831959A" # ID returned by Adyen
+ assert response.transaction_id == "853596624248395G" # ID returned by Adyen
assert response.error is None
diff --git a/saleor/payment/gateways/adyen/tests/test_webhook.py b/saleor/payment/gateways/adyen/tests/test_webhook.py
index d75f1b76af..61bb1262f4 100644
--- a/saleor/payment/gateways/adyen/tests/test_webhook.py
+++ b/saleor/payment/gateways/adyen/tests/test_webhook.py
@@ -71,7 +71,7 @@ def test_handle_authorization(notification, adyen_plugin, payment_adyen_for_orde
assert transaction.kind == TransactionKind.AUTH
-def test_handle_authorization_with_autocapture(
+def test_handle_authorization_with_adyen_auto_capture(
notification, adyen_plugin, payment_adyen_for_order
):
payment = payment_adyen_for_order
@@ -81,24 +81,50 @@ def test_handle_authorization_with_autocapture(
value=get_price_amount(payment.total, payment.currency),
)
config = adyen_plugin().config
+ config.connection_params["adyen_auto_capture"] = True
+ handle_authorization(notification, config)
+
+ assert payment.transactions.count() == 1
+ assert payment.transactions.get().kind == TransactionKind.CAPTURE
+
+
+def test_handle_authorization_with_auto_capture(
+ notification, adyen_plugin, payment_adyen_for_order
+):
+ payment = payment_adyen_for_order
+ payment_id = graphene.Node.to_global_id("Payment", payment.pk)
+ notification = notification(
+ psp_reference="853596537720508F",
+ merchant_reference=payment_id,
+ value=get_price_amount(payment.total, payment.currency),
+ )
+ config = adyen_plugin().config
config.auto_capture = True
+ config.connection_params["adyen_auto_capture"] = False
+
handle_authorization(notification, config)
- assert payment.transactions.count() == 0
+ payment.refresh_from_db()
+ assert payment.transactions.count() == 2
+ assert payment.transactions.first().kind == TransactionKind.AUTH
+ assert payment.transactions.last().kind == TransactionKind.CAPTURE
+ assert payment.charge_status == ChargeStatus.FULLY_CHARGED
-def test_handle_authorization_with_autocapture_and_payment_charged(
+def test_handle_authorization_with_adyen_auto_capture_and_payment_charged(
notification, adyen_plugin, payment_adyen_for_order
):
payment = payment_adyen_for_order
payment.charge_status = ChargeStatus.FULLY_CHARGED
+ payment.save()
payment_id = graphene.Node.to_global_id("Payment", payment.pk)
notification = notification(
merchant_reference=payment_id,
value=get_price_amount(payment.total, payment.currency),
)
config = adyen_plugin().config
- config.auto_capture = True
+ config.connection_params["adyen_auto_capture"] = True
handle_authorization(notification, config)
# payment already has a charge status no need to handle auth action
@@ -259,7 +285,7 @@ def test_handle_pending(notification, adyen_plugin, payment_adyen_for_order):
assert payment.charge_status == ChargeStatus.PENDING
-def test_handle_pending_with_autocapture(
+def test_handle_pending_with_adyen_auto_capture(
notification, adyen_plugin, payment_adyen_for_order
):
payment = payment_adyen_for_order
@@ -269,15 +295,16 @@ def test_handle_pending_with_autocapture(
value=get_price_amount(payment.total, payment.currency),
)
config = adyen_plugin().config
- config.auto_capture = True
+ config.connection_params["adyen_auto_capture"] = True
handle_pending(notification, config)
# in case of autocapture we don't want to store the pending status as all payments
# by default get capture status.
- assert payment.transactions.count() == 0
+ assert payment.transactions.count() == 1
+ assert payment.transactions.get().kind == TransactionKind.PENDING
payment.refresh_from_db()
- assert payment.charge_status != ChargeStatus.PENDING
+ assert payment.charge_status == ChargeStatus.PENDING
def test_handle_pending_already_pending(
diff --git a/saleor/payment/gateways/adyen/utils.py b/saleor/payment/gateways/adyen/utils.py
index 4a54f45b37..fb77d8e18a 100644
--- a/saleor/payment/gateways/adyen/utils.py
+++ b/saleor/payment/gateways/adyen/utils.py
@@ -170,7 +170,7 @@ def request_for_payment_refund(
def request_for_payment_capture(
- payment_information: "PaymentData", merchant_account, token
+ payment_information: "PaymentData", merchant_account: str, token: str
) -> Dict[str, Any]:
return {
"merchantAccount": merchant_account,
@@ -183,3 +183,17 @@ def request_for_payment_capture(
"originalReference": token,
"reference": payment_information.payment_id,
}
+
+
+def call_capture(
+ payment_information: "PaymentData",
+ merchant_account: str,
+ token: str,
+ adyen_client: Adyen.Adyen,
+):
+ request = request_for_payment_capture(
+ payment_information=payment_information,
+ merchant_account=merchant_account,
+ token=token,
+ )
+ return api_call(request, adyen_client.payment.capture)
diff --git a/saleor/payment/gateways/adyen/webhooks.py b/saleor/payment/gateways/adyen/webhooks.py
index db7d81f39b..4f6246b351 100644
--- a/saleor/payment/gateways/adyen/webhooks.py
+++ b/saleor/payment/gateways/adyen/webhooks.py
@@ -20,6 +20,7 @@ from ....order.actions import (
from ....order.events import external_notification_event
from ....payment.models import Payment, Transaction
from ... import ChargeStatus, TransactionKind
+from ...gateway import capture
from ...interface import GatewayConfig, GatewayResponse
from ...utils import create_transaction, gateway_postprocess
from .utils import convert_adyen_price_format
@@ -90,18 +91,22 @@ def handle_authorization(notification: Dict[str, Any], gateway_config: GatewayCo
ChargeStatus.PARTIALLY_CHARGED,
}:
return
- mark_capture = gateway_config.auto_capture
- if mark_capture:
- # If we mark order as a capture by default we don't need to handle auth actions
- return
+
+ kind = TransactionKind.AUTH
+ adyen_auto_capture = gateway_config.connection_params["adyen_auto_capture"]
+ if adyen_auto_capture:
+ kind = TransactionKind.CAPTURE
transaction_id = notification.get("pspReference")
- transaction = get_transaction(payment, transaction_id, TransactionKind.AUTH)
- if transaction:
- # We already marked it as Auth
+ transaction = payment.transactions.filter(
+ token=transaction_id, kind__in=[TransactionKind.AUTH, TransactionKind.CAPTURE]
+ ).first()
+
+ if transaction and transaction.is_success:
+ # We already have this transaction
return
- transaction = create_new_transaction(notification, payment, TransactionKind.AUTH)
+ transaction = create_new_transaction(notification, payment, kind)
reason = notification.get("reason", "-")
success_msg = f"Adyen: The payment {transaction_id} request was successful."
@@ -109,8 +114,17 @@ 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:
+ if not payment.order:
+ return
+
+ # If saleor has enabled auto capture we need to proceed the capture action.
+ if gateway_config.auto_capture:
+ capture(payment, amount=transaction.amount)
+
+ if kind == TransactionKind.AUTH:
order_authorized(payment.order, None, transaction.amount, payment)
+ elif kind == TransactionKind.CAPTURE:
+ order_captured(payment.order, None, transaction.amount, payment)
def handle_cancellation(notification: Dict[str, Any], _gateway_config: GatewayConfig):
@@ -207,10 +221,6 @@ def handle_failed_capture(notification: Dict[str, Any], _gateway_config: Gateway
def handle_pending(notification: Dict[str, Any], gateway_config: GatewayConfig):
# https://docs.adyen.com/development-resources/webhooks/understand-notifications#
# event-codes"
- mark_capture = gateway_config.auto_capture
- if mark_capture:
- # If we mark order as a capture by default we don't need to handle this action
- return
payment = get_payment(notification.get("merchantReference"))
if not payment:
return