Skip to content

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

Add tests for webhooks, fix not working parts of code

Maciej Korycinskiad99950b0e97
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index 5a35bfc3e4..67cee5f284 100644
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@ -394,8 +394,6 @@ class OrderCapture(BaseMutation):
# 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)
diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index 78c36b4ac2..b879b778e0 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -1587,9 +1587,9 @@ def test_order_capture(
}
assert event_order_fully_paid.type == order_events.OrderEvents.ORDER_FULLY_PAID
- assert event_order_fully_paid.user is None
+ assert event_order_fully_paid.user == staff_user
- assert event_email_sent.user is None
+ assert event_email_sent.user == staff_user
assert event_email_sent.parameters == {
"email": order.user_email,
"email_type": order_events.OrderEventsEmails.PAYMENT,
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index fb025f0c6e..7aa83f0e8c 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -43,11 +43,9 @@ def order_created(order: "Order", user: "User", from_draft: bool = False):
order_authorized(
order=order, user=user, amount=payment.total, payment=payment
)
- if order.is_fully_paid():
- handle_fully_paid_order(order=order, user=user)
-def handle_fully_paid_order(order: "Order", user: "User" = None):
+def handle_fully_paid_order(order: "Order", user: Optional["User"] = None):
events.order_fully_paid_event(order=order, user=user)
if order.get_customer_email():
@@ -146,6 +144,8 @@ def order_captured(
order=order, user=user, amount=amount, payment=payment
)
get_plugins_manager().order_updated(order)
+ if order.is_fully_paid():
+ handle_fully_paid_order(order, user)
def fulfillment_tracking_updated(
diff --git a/saleor/order/events.py b/saleor/order/events.py
index 34e1ce370d..9e24af6834 100644
--- a/saleor/order/events.py
+++ b/saleor/order/events.py
@@ -268,7 +268,7 @@ def payment_gateway_notification_event(
parameters = {"message": message}
if payment:
- parameters.update({"gateway": payment.gateway, "payment_id": payment.token})
+ parameters.update({"plugin": payment.gateway, "payment_id": payment.token})
return OrderEvent.objects.create(
order=order,
diff --git a/saleor/payment/gateways/adyen/plugin.py b/saleor/payment/gateways/adyen/plugin.py
index bc3394a7f1..aad329b400 100644
--- a/saleor/payment/gateways/adyen/plugin.py
+++ b/saleor/payment/gateways/adyen/plugin.py
@@ -98,7 +98,7 @@ class AdyenGatewayPlugin(BasePlugin):
"Live": {
"type": ConfigurationTypeField.STRING,
"help_text": (
- "Live it blank when you want to use test env. To communicate with the"
+ "Leave it blank when you want to use test env. To communicate with the"
" Adyen API you should submit HTTP POST requests to corresponding "
"endpoints. These endpoints differ for test and live accounts, and also"
" depend on the data format (SOAP, JSON, or FORM) you use to submit "
@@ -362,9 +362,3 @@ class AdyenGatewayPlugin(BasePlugin):
error="",
raw_response=result.message,
)
-
- def void_payment(
- self, payment_information: "PaymentData", previous_value
- ) -> "GatewayResponse":
-
- pass
diff --git a/saleor/payment/gateways/adyen/tests/cassettes/test_confirm_payment.yaml b/saleor/payment/gateways/adyen/tests/cassettes/test_confirm_payment.yaml
deleted file mode 100644
index bf5b88b316..0000000000
--- a/saleor/payment/gateways/adyen/tests/cassettes/test_confirm_payment.yaml
+++ /dev/null
@@ -1,55 +0,0 @@
-interactions:
-- request:
- body: '{"paymentMethod": {"riskData": {"clientData": "eyJ2ZXJzaW9uIjoiMS4wLjAiLCJkZXZpY2VGaW5nZXJwcmludCI6InJ5RUdYOGVacEowMDMwMDAwMDAwMDAwMDAwS1piSVFqNmt6czAwODkxNDY3NzZjVkI5NGlLekJHdmFtOUVxNm9WUTVTMTZHb2g1TWswMDRpdmJTdVlkRzBSMDAwMDBZVnhFcjAwMDAwY3J1OXNBeFRSNWlaQ3FuSTRsc2s6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2op1ZPO3gBklnAqKR9rGeCpkNvBgEUDIiuVTxNRzQD1UtKvWMX4RQeI0/vGKraNQCDbGQS1g+N4JUnzEnMmSUAq5GPKsoFijEP/UfXR2/Qh4g/AoyCwfmneDFG+YuqKa4LI563yRgODIKVZk+tYrzVGOw4Ass4R0kaHztcx7vk0haNur5MWsS0WzciuMhYfBu33qwW9i0P4yePxHEJdFlGCn+uxUFjmQj39Rch5xUUo6tkHP7b72Gn5xH3g==$uJDSyZJ8HNdG9q8REYbAVEHlnGuN/RRTQ6DGB3svlqheRY6tdqWnMS5g5nDJMT3VU+nEdvEpso21NhOiHGMhBTMd8UzMUYJqUbWwp/295Khvjpo5NNtwrmdQ74M2s5f19/Pn+6zwmC6HG+WFH7ZNTClLX8CqXa4iCEudho6IDg+Yf5RxCBO5Cvn30K2g6c16zMwNnNo/y7F8ejr8f2W+zvLtCPhLmb+8umvj8I65VHR+fr+aJ85w8WRSONOmFhdQTLbsUTnmuQHEksBTYfVK6kwTg661IfTgjaSdCmhs0gs0qBnSeVgTtizyO7rvKM6pfR5f78PVZPQWpOGhxGRqhu3TAc+4XZDSwh8B8Y0ofn98rucJpL3MgE+QHTn0AkBg9gtjmWWs0bNEFXBWDoAGfcs/ATCCfF74bgr2KstwOO3PBm7C4Y6ssPFsYqOomJGIZeCL+OAcEA+eeCDW/xjUEpPdiEZiIA3cAA=="},
- "browserInfo": {"acceptHeader": "*/*", "colorDepth": 24, "language": "en-GB",
- "javaEnabled": false, "screenHeight": 1440, "screenWidth": 2560, "userAgent":
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML,
- like Gecko) Chrome/84.0.4147.89 Safari/537.36", "timeZoneOffset": -120}}, "merchantAccount":
- null, "applicationInfo": {"adyenLibrary": {"name": "adyen-python-api-library",
- "version": "3.0.0"}}}'
- headers:
- Accept:
- - '*/*'
- Accept-Encoding:
- - gzip, deflate
- Connection:
- - keep-alive
- Content-Length:
- - '5800'
- 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: '{"status":422,"errorCode":"130","message":"Reference Missing","errorType":"validation"}'
- headers:
- Connection:
- - Keep-Alive
- Content-Type:
- - application/json;charset=UTF-8
- Date:
- - Thu, 23 Jul 2020 09:54:31 GMT
- Keep-Alive:
- - timeout=15, max=100
- Server:
- - Apache
- Set-Cookie:
- - JSESSIONID=53EB8B6F4EA1F082EF436F5327AD007C.test103e; Path=/checkout; Secure;
- HttpOnly
- Transfer-Encoding:
- - chunked
- pspReference:
- - 881595498071188J
- status:
- code: 422
- message: '422'
-version: 1
diff --git a/saleor/payment/gateways/adyen/tests/conftest.py b/saleor/payment/gateways/adyen/tests/conftest.py
new file mode 100644
index 0000000000..780df4a863
--- /dev/null
+++ b/saleor/payment/gateways/adyen/tests/conftest.py
@@ -0,0 +1,74 @@
+from decimal import Decimal
+
+import pytest
+
+from .....plugins.manager import get_plugins_manager
+from ....utils import create_payment
+from ..plugin import AdyenGatewayPlugin
+
+
+def adyen_plugin(settings):
+ def fun(
+ api_key=None,
+ merchant_account=None,
+ return_url=None,
+ origin_key=None,
+ origin_url=None,
+ auto_capture=None,
+ ):
+ api_key = api_key or "test_key"
+ merchant_account = merchant_account or "SaleorECOM"
+ 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"
+ auto_capture = auto_capture or False
+ settings.PLUGINS = ["saleor.payment.gateways.adyen.plugin.AdyenGatewayPlugin"]
+ manager = get_plugins_manager()
+ manager.save_plugin_configuration(
+ AdyenGatewayPlugin.PLUGIN_ID,
+ {
+ "active": True,
+ "configuration": [
+ {"name": "API key", "value": api_key},
+ {"name": "Merchant Account", "value": merchant_account},
+ {"name": "Return Url", "value": return_url},
+ {"name": "Origin Key", "value": origin_key},
+ {"name": "Origin Url", "value": origin_url},
+ {
+ "name": "Automatically mark payment as a capture",
+ "value": auto_capture,
+ },
+ {"name": "Supported currencies", "value": "USD"},
+ ],
+ },
+ )
+
+ manager = get_plugins_manager()
+ return manager.plugins[0]
+
+ return fun
+
+
+def payment_adyen_for_checkout(checkout_with_items, address):
+ checkout_with_items.billing_address = address
+ checkout_with_items.save()
+ payment = create_payment(
+ gateway=AdyenGatewayPlugin.PLUGIN_ID,
+ payment_token="",
+ total=Decimal("1234"),
+ currency=checkout_with_items.currency,
+ email=checkout_with_items.email,
+ customer_ip_address="",
+ checkout=checkout_with_items,
+ )
+ return payment
+
+
+def payment_adyen_for_order(payment_adyen_for_checkout, order_with_lines):
+ payment_adyen_for_checkout.checkout = None
+ payment_adyen_for_checkout.order = order_with_lines
+ payment_adyen_for_checkout.save()
+ return payment_adyen_for_checkout
diff --git a/saleor/payment/gateways/adyen/tests/test_plugin.py b/saleor/payment/gateways/adyen/tests/test_plugin.py
index e57f013090..72f8d1719c 100644
--- a/saleor/payment/gateways/adyen/tests/test_plugin.py
+++ b/saleor/payment/gateways/adyen/tests/test_plugin.py
@@ -1,74 +1,11 @@
import json
from decimal import Decimal
-# settings.PLUGINS = ["saleor.plugins.avatax.plugin.AvataxPlugin"]
-# manager = get_plugins_manager()
-# manager.save_plugin_configuration(
-# AvataxPlugin.PLUGIN_ID,
-# {
-# "configuration": [
-# {"name": "Username or account", "value": "test"},
-# {"name": "Password or license", "value": "test"},
-# ],
-# },
-# )
-# manager.save_plugin_configuration(AvataxPlugin.PLUGIN_ID, {"active": True})
-# plugin_configuration = PluginConfiguration.objects.get(
-# identifier=AvataxPlugin.PLUGIN_ID
-# )
-# assert plugin_configuration.active
import pytest
-from .....plugins.manager import get_plugins_manager
from .... import TransactionKind
from ....interface import GatewayResponse
-from ....utils import create_payment, create_payment_information, create_transaction
-from ..plugin import AdyenGatewayPlugin
-
-
-def adyen_plugin(settings):
- def fun(
- api_key=None,
- merchant_account=None,
- return_url=None,
- origin_key=None,
- origin_url=None,
- auto_capture=None,
- ):
- api_key = api_key or "test_key"
- merchant_account = merchant_account or "SaleorECOM" # "test_merchant"
- return_url = return_url or "http://127.0.0.1:3000/" # "test_return_url"
- origin_key = (
- origin_key or "test_origin_key"
- ) # "pub.v2.8015947108133280.aHR0cDovLzEyNy4wLjAuMTozMDAw.F13B5vHDsUw4vWEkRTUMUfICGgkS_Vdu4EbpiqZY6OU"
- origin_url = origin_url or "http://127.0.0.1:3000" # "test_origin_url"
- auto_capture = auto_capture or False
- settings.PLUGINS = ["saleor.payment.gateways.adyen.plugin.AdyenGatewayPlugin"]
- manager = get_plugins_manager()
- manager.save_plugin_configuration(
- AdyenGatewayPlugin.PLUGIN_ID,
- {
- "active": True,
- "configuration": [
- {"name": "API key", "value": api_key},
- {"name": "Merchant Account", "value": merchant_account},
- {"name": "Return Url", "value": return_url},
- {"name": "Origin Key", "value": origin_key},
- {"name": "Origin Url", "value": origin_url},
- {
- "name": "Automatically mark payment as a capture",
- "value": auto_capture,
- },
- {"name": "Supported currencies", "value": "USD"},
- ],
- },
- )
-
- manager = get_plugins_manager()
- return manager.plugins[0]
-
- return fun
+from ....utils import create_payment_information, create_transaction
@pytest.mark.vcr
@@ -94,30 +31,6 @@ def test_get_payment_gateway_for_checkout(
assert isinstance(config, list)
-def payment_adyen_for_checkout(checkout_with_items, address):
- checkout_with_items.billing_address = address
- checkout_with_items.save()
- payment = create_payment(
- gateway=AdyenGatewayPlugin.PLUGIN_ID,
- payment_token="",
- total=Decimal("1234"),
- currency=checkout_with_items.currency,
- email=checkout_with_items.email,
- customer_ip_address="",
- checkout=checkout_with_items,
- )
- return payment
-
-
-def payment_adyen_for_order(payment_adyen_for_checkout, order_with_lines):
- payment_adyen_for_checkout.checkout = None
- payment_adyen_for_checkout.order = order_with_lines
- payment_adyen_for_checkout.save()
- return payment_adyen_for_checkout
-
-
@pytest.mark.vcr
def test_process_payment(payment_adyen_for_checkout, checkout_with_items, adyen_plugin):
payment_info = create_payment_information(
diff --git a/saleor/payment/gateways/adyen/tests/test_webhook.py b/saleor/payment/gateways/adyen/tests/test_webhook.py
new file mode 100644
index 0000000000..d75f1b76af
--- /dev/null
+++ b/saleor/payment/gateways/adyen/tests/test_webhook.py
@@ -0,0 +1,603 @@
+from decimal import Decimal
+from unittest import mock
+
+import graphene
+import pytest
+from django.contrib.auth.hashers import make_password
+
+from saleor.order import OrderStatus
+from saleor.payment import ChargeStatus, TransactionKind
+
+from ..utils import get_price_amount
+from ..webhooks import (
+ create_new_transaction,
+ handle_authorization,
+ handle_cancel_or_refund,
+ handle_cancellation,
+ handle_capture,
+ handle_failed_capture,
+ handle_failed_refund,
+ handle_pending,
+ handle_refund,
+ handle_reversed_refund,
+ validate_auth_user,
+ validate_hmac_signature,
+ webhook_not_implemented,
+)
+
+
+def notification():
+ def fun(
+ event_code=None,
+ success=None,
+ psp_reference=None,
+ merchant_reference=None,
+ value=None,
+ ):
+ event_code = event_code or "AUTHORISATION"
+ success = success or "true"
+ psp_reference = psp_reference or "852595499936560C"
+ merchant_reference = merchant_reference or "UGF5bWVudDoxNw=="
+ value = value or 1130
+
+ return {
+ "additionalData": {},
+ "eventCode": event_code,
+ "success": success,
+ "eventDate": "2019-06-28T18:03:50+01:00",
+ "merchantAccountCode": "SaleorECOM",
+ "pspReference": psp_reference,
+ "merchantReference": merchant_reference,
+ "amount": {"value": value, "currency": "USD"},
+ }
+
+ return fun
+
+
+def test_handle_authorization(notification, adyen_plugin, payment_adyen_for_order):
+ payment = payment_adyen_for_order
+ 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
+ handle_authorization(notification, config)
+
+ assert payment.transactions.count() == 1
+ transaction = payment.transactions.get()
+ assert transaction.is_success is True
+ assert transaction.kind == TransactionKind.AUTH
+
+
+def test_handle_authorization_with_autocapture(
+ notification, adyen_plugin, payment_adyen_for_order
+):
+ payment = payment_adyen_for_order
+ 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
+ handle_authorization(notification, config)
+
+ assert payment.transactions.count() == 0
+
+
+def test_handle_authorization_with_autocapture_and_payment_charged(
+ notification, adyen_plugin, payment_adyen_for_order
+):
+ payment = payment_adyen_for_order
+ payment.charge_status = ChargeStatus.FULLY_CHARGED
+ 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
+ handle_authorization(notification, config)
+
+ # payment already has a charge status no need to handle auth action
+ assert payment.transactions.count() == 0
+
+
+def test_handle_cancel(notification, adyen_plugin, payment_adyen_for_order):
+ payment = payment_adyen_for_order
+ payment.charge_status = ChargeStatus.FULLY_CHARGED
+ 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
+
+ handle_cancellation(notification, config)
+
+ payment.order.refresh_from_db()
+ assert payment.transactions.count() == 1
+ transaction = payment.transactions.get()
+ assert transaction.is_success is True
+ assert transaction.kind == TransactionKind.CANCEL
+
+ assert payment.order.status == OrderStatus.CANCELED
+
+
+def test_handle_cancel_already_canceleld(
+ notification, adyen_plugin, payment_adyen_for_order
+):
+ payment = payment_adyen_for_order
+ payment.charge_status = ChargeStatus.FULLY_CHARGED
+ 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
+ create_new_transaction(notification, payment, TransactionKind.CANCEL)
+
+ handle_cancellation(notification, config)
+
+ assert payment.transactions.count() == 1
+
+
[email protected]("saleor.payment.gateways.adyen.webhooks.order_captured")
+def test_handle_capture(
+ mocked_captured, notification, adyen_plugin, payment_adyen_for_order
+):
+ payment = payment_adyen_for_order
+ 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
+
+ handle_capture(notification, config)
+
+ assert payment.transactions.count() == 1
+ transaction = payment.transactions.get()
+ assert transaction.is_success is True
+ assert transaction.kind == TransactionKind.CAPTURE
+ payment.refresh_from_db()
+ assert payment.charge_status == ChargeStatus.FULLY_CHARGED
+ mocked_captured.assert_called_once_with(
+ payment.order, None, transaction.amount, payment
+ )
+
+
+def test_handle_capture_with_payment_already_charged(
+ notification, adyen_plugin, payment_adyen_for_order
+):
+ payment = payment_adyen_for_order
+ payment.charge_status = ChargeStatus.FULLY_CHARGED
+ payment.captured_amount = payment.total
+ 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
+
+ handle_capture(notification, config)
+
+ # Payment is already captured so no need to save capture transaction
+ assert payment.transactions.count() == 0
+
+
+ "charge_status", [ChargeStatus.NOT_CHARGED, ChargeStatus.FULLY_CHARGED]
+)
+def test_handle_failed_capture(
+ charge_status, notification, adyen_plugin, payment_adyen_for_order
+):
+ payment = payment_adyen_for_order
+ payment.charge_status = charge_status
+ payment.captured_amount = payment.total
+ 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
+
+ handle_failed_capture(notification, config)
+
+ assert payment.transactions.count() == 1
+ transaction = payment.transactions.get()
+ assert transaction.is_success is True
+ assert transaction.kind == TransactionKind.CAPTURE_FAILED
+ payment.refresh_from_db()
+ assert payment.charge_status == ChargeStatus.NOT_CHARGED
+
+
+def test_handle_failed_capture_partial_charge(
+ notification, adyen_plugin, payment_adyen_for_order
+):
+ payment = payment_adyen_for_order
+ payment.charge_status = ChargeStatus.FULLY_CHARGED
+ payment.captured_amount += payment.total * 2
+ 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
+
+ handle_failed_capture(notification, config)
+
+ assert payment.transactions.count() == 1
+ transaction = payment.transactions.get()
+ assert transaction.is_success is True
+ assert transaction.kind == TransactionKind.CAPTURE_FAILED
+ payment.refresh_from_db()
+ assert payment.charge_status == ChargeStatus.PARTIALLY_CHARGED
+
+
+def test_handle_pending(notification, adyen_plugin, payment_adyen_for_order):
+ payment = payment_adyen_for_order
+ 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
+
+ handle_pending(notification, config)
+
+ assert payment.transactions.count() == 1
+ transaction = payment.transactions.get()
+ assert transaction.is_success is True
+ assert transaction.kind == TransactionKind.PENDING
+ payment.refresh_from_db()
+ assert payment.charge_status == ChargeStatus.PENDING
+
+
+def test_handle_pending_with_autocapture(
+ notification, adyen_plugin, payment_adyen_for_order
+):
+ payment = payment_adyen_for_order
+ 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
+
+ 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
+ payment.refresh_from_db()
+ assert payment.charge_status != ChargeStatus.PENDING
+
+
+def test_handle_pending_already_pending(
+ notification, adyen_plugin, payment_adyen_for_order
+):
+ payment = payment_adyen_for_order
+ payment.charge_status = ChargeStatus.PENDING
+ 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
+ create_new_transaction(notification, payment, TransactionKind.PENDING)
+
+ handle_pending(notification, config)
+
+ assert payment.transactions.count() == 1
+
+
[email protected]("saleor.payment.gateways.adyen.webhooks.order_refunded")
+def test_handle_refund(
+ mock_order_refunded, notification, adyen_plugin, payment_adyen_for_order
+):
+ payment = payment_adyen_for_order
+ payment.charge_status = ChargeStatus.FULLY_CHARGED
+ payment.captured_amount = payment.total
+ 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
+
+ handle_refund(notification, config)
+
+ assert payment.transactions.count() == 1
+ transaction = payment.transactions.get()
+ assert transaction.is_success is True
+ assert transaction.kind == TransactionKind.REFUND
+ payment.refresh_from_db()
+ assert payment.charge_status == ChargeStatus.FULLY_REFUNDED
+ assert payment.captured_amount == Decimal("0.00")
+
+ mock_order_refunded.assert_called_once_with(
+ payment.order, None, transaction.amount, payment
+ )
+
+
[email protected]("saleor.payment.gateways.adyen.webhooks.order_refunded")
+def test_handle_refund_already_refunded(
+ mock_order_refunded, notification, adyen_plugin, payment_adyen_for_order
+):
+ payment = payment_adyen_for_order
+ payment.charge_status = ChargeStatus.FULLY_REFUNDED
+ payment.captured_amount = Decimal("0.00")
+ 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),
+ )
+ create_new_transaction(notification, payment, TransactionKind.REFUND)
+ config = adyen_plugin().config
+
+ handle_refund(notification, config)
+
+ assert payment.transactions.count() == 1
+ assert not mock_order_refunded.called
+
+
+def test_handle_failed_refund_missing_transaction(
+ notification, adyen_plugin, payment_adyen_for_order
+):
+ payment = payment_adyen_for_order
+ payment.charge_status = ChargeStatus.FULLY_CHARGED
+ payment.captured_amount = payment.total
+ 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
+
+ handle_failed_refund(notification, config)
+
+ assert payment.transactions.count() == 0
+
+
+def test_handle_failed_refund_with_transaction_refund_ongoing(
+ notification, adyen_plugin, payment_adyen_for_order
+):
+ payment = payment_adyen_for_order
+ payment.charge_status = ChargeStatus.FULLY_CHARGED
+ payment.captured_amount = payment.total
+ 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
+ create_new_transaction(notification, payment, TransactionKind.REFUND_ONGOING)
+ handle_failed_refund(notification, config)
+
+ assert (
+ payment.transactions.count() == 3
+ ) # REFUND_ONGOING, REFUND_FAILED, FULLY_CHARGED
+ assert payment.charge_status == ChargeStatus.FULLY_CHARGED
+ assert payment.total == payment.captured_amount
+
+
+def test_handle_failed_refund_with_transaction_refund(
+ notification, adyen_plugin, payment_adyen_for_order
+):
+ payment = payment_adyen_for_order
+ payment.charge_status = ChargeStatus.FULLY_REFUNDED
+ payment.captured_amount = Decimal("0.0")
+ 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
+ create_new_transaction(notification, payment, TransactionKind.REFUND)
+ handle_failed_refund(notification, config)
+
+ payment.refresh_from_db()
+ assert payment.transactions.count() == 3 # REFUND, REFUND_FAILED, FULLY_CHARGED
+ assert payment.charge_status == ChargeStatus.FULLY_CHARGED
+ assert payment.total == payment.captured_amount
+
+
+def test_handle_reversed_refund(notification, adyen_plugin, payment_adyen_for_order):
+ payment = payment_adyen_for_order
+ payment.charge_status = ChargeStatus.FULLY_REFUNDED
+ payment.captured_amount = Decimal("0.0")
+ 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
+ handle_reversed_refund(notification, config)
+
+ payment.refresh_from_db()
+ assert payment.transactions.count() == 1 # REFUND_REVERSED
+ assert payment.charge_status == ChargeStatus.FULLY_CHARGED
+ assert payment.total == payment.captured_amount
+
+
+def test_handle_reversed_refund_already_processed(
+ notification, adyen_plugin, payment_adyen_for_order
+):
+ payment = payment_adyen_for_order
+ payment.charge_status = ChargeStatus.FULLY_CHARGED
+ payment.captured_amount = payment.total
+ 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
+ create_new_transaction(notification, payment, TransactionKind.REFUND_REVERSED)
+ handle_reversed_refund(notification, config)
+
+ payment.refresh_from_db()
+ assert payment.transactions.count() == 1
+
+
+def test_webhook_not_implemented(notification, adyen_plugin, payment_adyen_for_order):
+ payment = payment_adyen_for_order
+ payment.charge_status = ChargeStatus.FULLY_CHARGED
+ payment.captured_amount = payment.total
+ 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
+
+ webhook_not_implemented(notification, config)
+
+ assert payment.order.events.count() == 1
+
+
[email protected]("saleor.payment.gateways.adyen.webhooks.handle_refund")
+def test_handle_cancel_or_refund_action_refund(
+ mock_handle_refund, notification, adyen_plugin, payment_adyen_for_order
+):
+
+ payment = payment_adyen_for_order
+ payment_id = graphene.Node.to_global_id("Payment", payment.pk)
+ config = adyen_plugin().config
+ notification = notification(
+ merchant_reference=payment_id,
+ value=get_price_amount(payment.total, payment.currency),
+ )
+ notification["additionalData"]["modification.action"] = "refund"
+
+ handle_cancel_or_refund(notification, config)
+
+ mock_handle_refund.assert_called_once_with(notification, config)
+
+
[email protected]("saleor.payment.gateways.adyen.webhooks.handle_cancellation")
+def test_handle_cancel_or_refund_action_cancel(
+ mock_handle_cancellation, notification, adyen_plugin, payment_adyen_for_order
+):
+ payment = payment_adyen_for_order
+ payment_id = graphene.Node.to_global_id("Payment", payment.pk)
+ config = adyen_plugin().config
+ notification = notification(
+ merchant_reference=payment_id,
+ value=get_price_amount(payment.total, payment.currency),
+ )
+ notification["additionalData"]["modification.action"] = "cancel"
+
+ handle_cancel_or_refund(notification, config)
+
+ mock_handle_cancellation.assert_called_once_with(notification, config)
+
+
+def notification_with_hmac_signature():
+ return {
+ "additionalData": {
+ "expiryDate": "12/2012",
+ " NAME1 ": "VALUE1",
+ "cardSummary": "7777",
+ "totalFraudScore": "10",
+ "hmacSignature": "D4bKVtjx5AlBL2eeQZIh1p7G1Lh6vWjzwkDlzC+PoMo=",
+ "NAME2": " VALUE2 ",
+ "fraudCheck-6-ShopperIpUsage": "10",
+ },
+ "amount": {"currency": "GBP", "value": 20150},
+ "eventCode": "AUTHORISATION",
+ "eventDate": "2020-07-24T12:40:22+02:00",
+ "merchantAccountCode": "SaleorPOS",
+ "merchantReference": "8313842560770001",
+ "paymentMethod": "visa",
+ "pspReference": "test_AUTHORISATION_4",
+ "reason": "REFUSED",
+ "success": "false",
+ }
+
+
+def test_validate_hmac_signature(adyen_plugin, notification_with_hmac_signature):
+ hmac_key = "8E60EDDCA27F96095AD5882EF0AA3B05844864710EC089B7967F796AC44AE76E"
+ plugin = adyen_plugin()
+ config = plugin.config
+ config.connection_params["webhook_hmac"] = hmac_key
+ assert validate_hmac_signature(notification_with_hmac_signature, config) is True
+
+
+def test_validate_hmac_signature_missing_key_in_saleor(
+ adyen_plugin, notification_with_hmac_signature
+):
+ plugin = adyen_plugin()
+ config = plugin.config
+ assert validate_hmac_signature(notification_with_hmac_signature, config) is False
+
+
+def test_validate_hmac_signature_missing_key_in_notification(
+ adyen_plugin, notification
+):
+ hmac_key = "8E60EDDCA27F96095AD5882EF0AA3B05844864710EC089B7967F796AC44AE76E"
+ plugin = adyen_plugin()
+ config = plugin.config
+ config.connection_params["webhook_hmac"] = hmac_key
+ assert validate_hmac_signature(notification(), config) is False
+
+
+def test_validate_hmac_signature_without_keys(adyen_plugin, notification):
+ plugin = adyen_plugin()
+ config = plugin.config
+ assert validate_hmac_signature(notification(), config) is True
+
+
+def test_validate_auth_user(adyen_plugin):
+ plugin = adyen_plugin()
+ config = plugin.config
+ config.connection_params["webhook_user"] = "[email protected]"
+ password = make_password("admin")
+ config.connection_params["webhook_user_password"] = password
+ is_valid = validate_auth_user(
+ headers={"Authorization": "Basic YWRtaW5AZXhhbXBsZS5jb206YWRtaW4="},
+ gateway_config=config,
+ )
+ assert is_valid is True
+
+
+def validate_auth_user_when_header_is_missing(adyen_plugin):
+ plugin = adyen_plugin()
+ config = plugin.config
+ config.connection_params["webhook_user"] = "[email protected]"
+ password = make_password("admin")
+ config.connection_params["webhook_user_password"] = password
+ is_valid = validate_auth_user(headers={}, gateway_config=config)
+ assert is_valid is False
+
+
+def test_validate_auth_user_when_user_is_missing(adyen_plugin):
+ plugin = adyen_plugin()
+ config = plugin.config
+ is_valid = validate_auth_user(
+ headers={"Authorization": "Basic YWRtaW5AZXhhbXBsZS5jb206YWRtaW4="},
+ gateway_config=config,
+ )
+ assert is_valid is False
+
+
+def test_validate_auth_user_when_auth_is_disabled(adyen_plugin):
+ plugin = adyen_plugin()
+ config = plugin.config
+ is_valid = validate_auth_user(headers={}, gateway_config=config)
+ assert is_valid is True
diff --git a/saleor/payment/gateways/adyen/utils.py b/saleor/payment/gateways/adyen/utils.py
index 260f68247d..e2dd6e2d4b 100644
--- a/saleor/payment/gateways/adyen/utils.py
+++ b/saleor/payment/gateways/adyen/utils.py
@@ -6,9 +6,11 @@ import Adyen
from babel.numbers import get_currency_precision
from django.conf import settings
from django_countries.fields import Country
+from graphql_relay import from_global_id
from ....checkout.models import Checkout
from ....core.prices import quantize_price
+from ....discount.utils import fetch_active_discounts
from ... import PaymentError
from ...interface import PaymentData
@@ -43,6 +45,51 @@ def api_call(requst_data: Dict[str, Any], method: Callable) -> Adyen.Adyen:
raise PaymentError("Unable to process the payment request.")
+def append_klarna_data(payment_information: "PaymentData", payment_data):
+ # FIXME Add klarna data
+ pass
+ # _type, payment_id = from_global_id(payment_information.payment_id)
+ # checkout = Checkout.objects.filter(payments__id=payment_data).first()
+ # if not checkout:
+ # raise PaymentError("Unable to calculate products for klarna")
+ # discounts = fetch_active_discounts()
+ # checkout.lines.prefetch_related("variant").all()
+ # def resolve_total_price(self, info):
+ # def calculate_total_price(discounts):
+ # return info.context.plugins.calculate_checkout_line_total(
+ # checkout_line=self, discounts=discounts
+ # )
+ #
+ # return (
+ # DiscountsByDateTimeLoader(info.context)
+ # .load(info.context.request_time)
+ # .then(calculate_total_price)
+ # )
+
+ # payment_data["shopperEmail"] = payment_information.customer_email
+ # payment_data["lineItems"] = [
+ # {
+ # "quantity": "1",
+ # "amountExcludingTax": "450",
+ # "taxPercentage": "1111",
+ # "description": "Sunglasses",
+ # "id": "Item #1",
+ # "taxAmount": "50",
+ # "amountIncludingTax": "500",
+ # "taxCategory": "High"
+ # },
+ # {
+ # "quantity": "1",
+ # "amountExcludingTax": "450",
+ # "taxPercentage": "1111",
+ # "description": "Headphones",
+ # "id": "Item #2",
+ # "taxAmount": "50",
+ # "amountIncludingTax": "500",
+ # "taxCategory": "High"
+ # }]
+
+
def request_data_for_payment(
payment_information: "PaymentData", return_url, merchant_account, origin_url
) -> Dict[str, Any]:
@@ -67,6 +114,11 @@ def request_data_for_payment(
# web1:https://shop.com, web2:https://shop1.com
extra_request_params["origin"] = origin_url
+ method = payment_data["paymentMethod"].get("type", [])
+ if "klarna" in method:
+ # TODO
+ append_klarna_data()
+
request = {
"amount": {
"value": get_price_amount(
diff --git a/saleor/payment/gateways/adyen/webhooks.py b/saleor/payment/gateways/adyen/webhooks.py
index 76e0f8c036..caa90f8dc8 100644
--- a/saleor/payment/gateways/adyen/webhooks.py
+++ b/saleor/payment/gateways/adyen/webhooks.py
@@ -20,7 +20,7 @@ from ....order.actions import (
)
from ....order.events import payment_gateway_notification_event
from ....payment.models import Payment, Transaction
-from ... import TransactionKind
+from ... import ChargeStatus, TransactionKind
from ...interface import GatewayConfig, GatewayResponse
from ...utils import create_transaction, gateway_postprocess
from .utils import convert_adyen_price_format
@@ -80,14 +80,19 @@ def create_payment_notification_for_order(
def handle_authorization(notification: Dict[str, Any], gateway_config: GatewayConfig):
- 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
payment = get_payment(notification.get("merchantReference"))
if not payment:
# We don't know anything about that payment
return
+ if payment.charge_status in {
+ ChargeStatus.FULLY_CHARGED,
+ 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
transaction_id = notification.get("pspReference")
transaction = get_transaction(payment, transaction_id, TransactionKind.AUTH)
@@ -108,12 +113,13 @@ 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"
payment = get_payment(notification.get("merchantReference"))
if not payment:
return
transaction_id = notification.get("pspReference")
transaction = get_transaction(payment, transaction_id, TransactionKind.CANCEL)
- if transaction:
+ if transaction and transaction.is_success:
# it is already cancelled
return
new_transaction = create_new_transaction(
@@ -134,6 +140,7 @@ def handle_cancellation(notification: Dict[str, Any], _gateway_config: GatewayCo
def handle_cancel_or_refund(
notification: Dict[str, Any], gateway_config: GatewayConfig
):
+ "https://docs.adyen.com/checkout/cancel-or-refund#cancel-or-refund-notification"
additional_data = notification.get("additionalData")
action = additional_data.get("modification.action")
if action == "refund":
@@ -143,14 +150,13 @@ def handle_cancel_or_refund(
def handle_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig):
- # FIXME execute order_fully_paid event
+ "https://docs.adyen.com/checkout/capture#capture-notification"
payment = get_payment(notification.get("merchantReference"))
if not payment:
return
transaction_id = notification.get("pspReference")
- transaction = get_transaction(payment, transaction_id, TransactionKind.CAPTURE)
- if transaction and transaction.is_success:
- # it is already captured
+ if payment.charge_status == ChargeStatus.FULLY_CHARGED:
+ # the payment has already status captured.
return
new_transaction = create_new_transaction(
@@ -158,8 +164,6 @@ def handle_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig)
)
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."
@@ -168,10 +172,11 @@ def handle_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig)
payment, success_msg, failed_msg, new_transaction.is_success
)
if payment.order:
- order_captured(payment.orderm, None, transaction.amount, payment)
+ order_captured(payment.order, None, new_transaction.amount, payment)
def handle_failed_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig):
+ "https://docs.adyen.com/checkout/capture#failed-capture"
payment = get_payment(notification.get("merchantReference"))
if not payment:
return
@@ -197,6 +202,8 @@ 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
@@ -222,6 +229,7 @@ def handle_pending(notification: Dict[str, Any], gateway_config: GatewayConfig):
def handle_refund(notification: Dict[str, Any], _gateway_config: GatewayConfig):
+ "https://docs.adyen.com/checkout/refund#refund-notification"
payment = get_payment(notification.get("merchantReference"))
if not payment:
return
@@ -242,22 +250,41 @@ def handle_refund(notification: Dict[str, Any], _gateway_config: GatewayConfig):
payment, success_msg, failed_msg, new_transaction.is_success
)
if payment.order:
- order_refunded(payment.order, None, transaction.amount, payment)
+ order_refunded(payment.order, None, new_transaction.amount, payment)
+
+
+def _get_kind(transaction: Optional[Transaction]) -> TransactionKind:
+ if transaction:
+ return transaction.kind
+ # To proceed the refund we already need to have the capture status so we will use it
+ return TransactionKind.CAPTURE
-def handle_failed_refund(notification: Dict[str, Any], _gateway_config: GatewayConfig):
+def handle_failed_refund(notification: Dict[str, Any], gateway_config: GatewayConfig):
+ "https://docs.adyen.com/checkout/refund#failed-refund"
payment = get_payment(notification.get("merchantReference"))
if not payment:
return
transaction_id = notification.get("pspReference")
- transaction = get_transaction(payment, transaction_id, TransactionKind.REFUND)
- if transaction and not transaction.is_success:
- # The refund is already saved
- return
- new_transaction = create_new_transaction(
- notification, payment, TransactionKind.REFUND
- )
- gateway_postprocess(new_transaction, payment)
+
+ # take the last status of payment before we tried to perform the refund
+ last_transaction = payment.transactions.exclude(
+ kind__in=[
+ TransactionKind.REFUND_ONGOING,
+ TransactionKind.REFUND,
+ TransactionKind.REFUND_FAILED,
+ ]
+ ).last()
+ last_kind = _get_kind(last_transaction)
+
+ refund_transaction = payment.transactions.filter(
+ token=transaction_id,
+ kind__in=[
+ TransactionKind.REFUND_ONGOING,
+ TransactionKind.REFUND,
+ TransactionKind.REFUND_FAILED,
+ ],
+ ).last()
reason = notification.get("reason", "-")
msg = (
@@ -265,12 +292,41 @@ 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, new_transaction.is_success)
+ create_payment_notification_for_order(payment, msg, None, True)
+
+ if not refund_transaction:
+ # we don't know anything about refund so we have to skip the notification about
+ # failed refund.
+ return
+
+ if refund_transaction.kind == TransactionKind.REFUND_FAILED:
+ # The failed refund is already saved
+ return
+ elif refund_transaction.kind == TransactionKind.REFUND_ONGOING:
+ # create new failed transaction which will allows us to discover duplicated
+ # notification
+ create_new_transaction(notification, payment, TransactionKind.REFUND_FAILED)
+
+ # Refund ongoing doesnt do any action on payment.capture_amount so we set
+ # 0 to amount. Thanks to it we can create transaction with the same status and
+ # no worries that we will capture total in payment two times.
+ # (if gateway_postprocess gets transaction with capture it will subtract the
+ # amount from transaction
+ notification["amount"]["value"] = 0
+ new_transaction = create_new_transaction(notification, payment, last_kind)
+ gateway_postprocess(new_transaction, payment)
+ elif refund_transaction.kind == TransactionKind.REFUND:
+ # create new failed transaction which will allows us to discover duplicated
+ # notification
+ create_new_transaction(notification, payment, TransactionKind.REFUND_FAILED)
+ new_transaction = create_new_transaction(notification, payment, last_kind)
+ gateway_postprocess(new_transaction, payment)
def handle_reversed_refund(
notification: Dict[str, Any], _gateway_config: GatewayConfig
):
+ "https://docs.adyen.com/checkout/refund#failed-refund"
payment = get_payment(notification.get("merchantReference"))
if not payment:
return
@@ -279,7 +335,7 @@ def handle_reversed_refund(
payment, transaction_id, TransactionKind.REFUND_REVERSED
)
- if transaction and not transaction.is_success:
+ if transaction:
# it is already refunded
return
new_transaction = create_new_transaction(
@@ -297,30 +353,10 @@ def handle_reversed_refund(
def handle_refund_with_data(
- notification: Dict[str, Any], _gateway_config: GatewayConfig
+ notification: Dict[str, Any], gateway_config: GatewayConfig
):
-
- payment = get_payment(notification.get("merchantReference"))
- if not payment:
- return
- transaction_id = notification.get("pspReference")
- transaction = get_transaction(payment, transaction_id, TransactionKind.REFUND)
- if transaction:
- # it is already refunded
- return
- new_transaction = create_new_transaction(
- notification, payment, TransactionKind.REFUND
- )
- gateway_postprocess(new_transaction, payment)
-
- reason = notification.get("reason", "-")
- 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, new_transaction.is_success
- )
- if payment.order:
- order_refunded(payment.order, None, transaction.amount, payment)
+ "https://docs.adyen.com/checkout/refund#refund-with-data"
+ handle_refund(notification, gateway_config)
def webhook_not_implemented(
@@ -363,26 +399,20 @@ EVENT_MAP = {
def validate_hmac_signature(
notification: Dict[str, Any], gateway_config: "GatewayConfig"
) -> bool:
-
- """
- pspReference 7914073381342284
- originalReference
- merchantAccountCode YOUR_MERCHANT_ACCOUNT
- merchantReference TestPayment-1407325143704
- value 1130
- currency EUR
- eventCode AUTHORISATION
- success true
- """
+ hmac_signature = notification.get("additionalData", {}).get("hmacSignature")
hmac_key = gateway_config.connection_params.get("webhook_hmac")
- if not hmac_key:
+ if not hmac_key and not hmac_signature:
return True
- hmac_signature = notification.get("additionalData", {}).get("hmacSignature")
+ if not hmac_key and hmac_signature:
+ return False
+
if not hmac_signature and hmac_key:
return False
- success = "true" if notification.get("success", "") else "false"
+ hmac_key = hmac_key.encode()
+
+ success = "true" if notification.get("success", "") == "true" else "false"
if notification.get("success", None) is None:
success = ""
@@ -391,13 +421,14 @@ def validate_hmac_signature(
notification.get("originalReference", ""),
notification.get("merchantAccountCode", ""),
notification.get("merchantReference", ""),
- notification.get("value", ""),
- notification.get("currency", ""),
+ str(notification.get("amount", {}).get("value", "")),
+ notification.get("amount", {}).get("currency", ""),
notification.get("eventCode", ""),
success,
]
payload = ":".join(payload_list)
+ hmac_key = binascii.a2b_hex(hmac_key)
hm = hmac.new(hmac_key, payload.encode("utf-8"), hashlib.sha256)
expected_merchant_sign = base64.b64encode(hm.digest())
return hmac_signature == expected_merchant_sign.decode("utf-8")
@@ -409,6 +440,10 @@ def validate_auth_user(headers: HttpHeaders, gateway_config: "GatewayConfig") ->
auth_header = headers.get("Authorization")
if not auth_header and not username:
return True
+ if auth_header and not username:
+ return False
+ if not auth_header and username:
+ return False
split_auth = auth_header.split(maxsplit=1)
prefix = "BASIC"
@@ -418,7 +453,9 @@ def validate_auth_user(headers: HttpHeaders, gateway_config: "GatewayConfig") ->
auth = split_auth[1]
try:
- request_username, request_password = base64.b64decode(auth).split(":")
+ decoded_auth = base64.b64decode(auth)
+ decoded_auth = decoded_auth.decode()
+ request_username, request_password = decoded_auth.split(":")
user_is_correct = request_username == username
if user_is_correct and check_password(request_password, password):
return True
@@ -437,11 +474,11 @@ def handle_webhook(request: WSGIRequest, gateway_config: "GatewayConfig"):
if not validate_hmac_signature(notification, gateway_config):
return HttpResponseBadRequest("Invalid or missing hmac signature.")
- if not validate_auth_user(notification, gateway_config):
+ if not validate_auth_user(request.headers, gateway_config):
return HttpResponseBadRequest("Invalid or missing basic auth.")
- event_handler = EVENT_MAP.get(notification.get("eventCode", ""))
- if event_handler:
- event_handler(notification, gateway_config)
- return HttpResponse("[accepted]")
+ # event_handler = EVENT_MAP.get(notification.get("eventCode", ""))
+ # if event_handler:
+ # event_handler(notification, gateway_config)
+ return HttpResponse("[accepted]")
return HttpResponseNotFound()
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index f43d32e7e2..5e46ee9000 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -226,7 +226,7 @@ def gateway_postprocess(transaction, payment):
TransactionKind.REFUND_REVERSED,
}:
payment.captured_amount += transaction.amount
-
+ payment.is_active = True
# Set payment charge status to fully charged
# only if there is no more amount needs to charge
payment.charge_status = ChargeStatus.PARTIALLY_CHARGED
@@ -265,8 +265,8 @@ def gateway_postprocess(transaction, payment):
}:
payment.captured_amount -= transaction.amount
payment.charge_status = ChargeStatus.PARTIALLY_CHARGED
- if payment.get_charge_amount() <= 0:
- payment.charge_status = ChargeStatus.FULLY_CHARGED
+ if payment.captured_amount <= 0:
+ payment.charge_status = ChargeStatus.NOT_CHARGED
payment.save(update_fields=["charge_status", "captured_amount", "modified"])