Skip to content

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

Handle additional payment actions in adyen

IKarbowiak4a0e3d9a2665
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index 76407528f9..f5931bc1ea 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -192,6 +192,7 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
# FIXME this is not a customer IP address. It is a client storefront ip
customer_ip_address=get_client_ip(info.context),
checkout=checkout,
+ return_url=data.get("return_url"),
)
return CheckoutPaymentCreate(payment=payment, checkout=checkout)
diff --git a/saleor/graphql/payment/tests/test_payment.py b/saleor/graphql/payment/tests/test_payment.py
index 1349a49131..6182a6922a 100644
--- a/saleor/graphql/payment/tests/test_payment.py
+++ b/saleor/graphql/payment/tests/test_payment.py
@@ -204,12 +204,14 @@ def test_checkout_add_payment(
checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
total = calculations.checkout_total(checkout=checkout, lines=list(checkout))
+ return_url = "https://www.example.com"
variables = {
"checkoutId": checkout_id,
"input": {
"gateway": DUMMY_GATEWAY,
"token": "sample-token",
"amount": total.gross.amount,
+ "returnUrl": return_url,
},
}
response = user_api_client.post_graphql(CREATE_PAYMENT_MUTATION, variables)
@@ -229,6 +231,7 @@ def test_checkout_add_payment(
assert payment.billing_address_1 == checkout.billing_address.street_address_1
assert payment.billing_first_name == checkout.billing_address.first_name
assert payment.billing_last_name == checkout.billing_address.last_name
+ assert payment.return_url == return_url
def test_checkout_add_payment_default_amount(
diff --git a/saleor/payment/gateways/adyen/plugin.py b/saleor/payment/gateways/adyen/plugin.py
index 67c7ac2152..c051fef495 100644
--- a/saleor/payment/gateways/adyen/plugin.py
+++ b/saleor/payment/gateways/adyen/plugin.py
@@ -1,5 +1,6 @@
import json
from typing import List, Optional
+from urllib.parse import urlencode
import Adyen
from django.contrib.auth.hashers import make_password
@@ -8,6 +9,8 @@ from django.http import HttpResponse
from graphql_relay import from_global_id
from ....checkout.models import Checkout
+from ....core.emails import prepare_url
+from ....payment.models import Payment
from ....plugins.base_plugin import BasePlugin, ConfigurationTypeField
from ... import PaymentError, TransactionKind
from ...interface import GatewayConfig, GatewayResponse, PaymentData, PaymentGateway
@@ -190,7 +193,7 @@ class AdyenGatewayPlugin(BasePlugin):
def webhook(self, request: WSGIRequest, path: str, previous_value) -> HttpResponse:
config = self._get_gateway_config()
- return handle_webhook(request, config)
+ return handle_webhook(request, config, self.adyen.checkout.payments_details)
def _get_gateway_config(self) -> GatewayConfig:
return self.config
@@ -229,9 +232,10 @@ class AdyenGatewayPlugin(BasePlugin):
def process_payment(
self, payment_information: "PaymentData", previous_value
) -> "GatewayResponse":
+ params = urlencode({"payment": payment_information.payment_id})
request_data = request_data_for_payment(
payment_information,
- return_url=self.config.connection_params["return_url"],
+ return_url=prepare_url(params, self.config.connection_params["return_url"]),
merchant_account=self.config.connection_params["merchant_account"],
origin_url=self.config.connection_params["origin_url"],
)
@@ -242,6 +246,25 @@ class AdyenGatewayPlugin(BasePlugin):
kind = TransactionKind.CAPTURE
else:
kind = TransactionKind.AUTH
+
+ action = result.message.get("action")
+ if action:
+ _type, payment_id = from_global_id(payment_information.payment_id)
+ payment = Payment.objects.filter(pk=payment_id).first()
+ if not payment:
+ # todo: return error
+ raise Exception("Payment does not exists")
+ details = result.message.get("details")
+ payment.extra_data = json.dumps(
+ {
+ "payment_data": action["paymentData"],
+ "parameters": [detail["key"] for detail in details]
+ if details
+ else [],
+ }
+ )
+ payment.save(update_fields=["extra_data"])
+
return GatewayResponse(
is_success=is_success,
action_required="action" in result.message,
@@ -251,7 +274,7 @@ class AdyenGatewayPlugin(BasePlugin):
transaction_id=result.message.get("pspReference", ""),
error=result.message.get("refusalReason"),
raw_response=result.message,
- action_required_data=result.message.get("action"),
+ action_required_data=action,
)
@classmethod
diff --git a/saleor/payment/gateways/adyen/webhooks.py b/saleor/payment/gateways/adyen/webhooks.py
index db7d81f39b..34ccba63e9 100644
--- a/saleor/payment/gateways/adyen/webhooks.py
+++ b/saleor/payment/gateways/adyen/webhooks.py
@@ -3,12 +3,13 @@ import binascii
import hashlib
import hmac
import json
-from typing import Any, Dict, Optional
+from typing import Any, Callable, Dict, Optional
from django.contrib.auth.hashers import check_password
from django.core.handlers.wsgi import WSGIRequest
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotFound
from django.http.request import HttpHeaders
+from django.shortcuts import redirect
from graphql_relay import from_global_id
from ....order.actions import (
@@ -468,8 +469,13 @@ def validate_auth_user(headers: HttpHeaders, gateway_config: "GatewayConfig") ->
return False
-def handle_webhook(request: WSGIRequest, gateway_config: "GatewayConfig"):
- json_data = json.loads(request.body)
+def handle_webhook(
+ request: WSGIRequest, gateway_config: "GatewayConfig", payment_details: Callable
+):
+ try:
+ json_data = json.loads(request.body)
+ except json.decoder.JSONDecodeError:
+ return handle_additional_actions(request, payment_details)
# JSON and HTTP POST notifications always contain a single NotificationRequestItem
# object.
notification = json_data.get("notificationItems")[0].get(
@@ -486,3 +492,33 @@ def handle_webhook(request: WSGIRequest, gateway_config: "GatewayConfig"):
event_handler(notification, gateway_config)
return HttpResponse("[accepted]")
return HttpResponseNotFound()
+
+
+def handle_additional_actions(request: WSGIRequest, payment_details: Callable):
+ payment_id = request.GET["payment"]
+ _type, payment_pk = from_global_id(payment_id)
+ payment = Payment.objects.filter(pk=payment_pk).first()
+
+ if not payment:
+ # TODO: raise error
+ return
+
+ data = json.loads(payment.extra_data)
+ return_url = payment.return_url
+
+ if not return_url:
+ # TODO: raise error
+ pass
+
+ request_data = {
+ "paymentData": data["payment_data"],
+ "details": {key: request.POST[key] for key in data["parameters"]},
+ }
+
+ result = payment_details(request_data)
+
+ # Check if further action is needed.
+ if "action" in result.message:
+ redirect(return_url, result.message["action"])
+ else:
+ redirect(return_url, result.message["resultCode"])
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index c563a7c580..02f5d47051 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -77,6 +77,7 @@ def create_payment(
extra_data: Dict = None,
checkout: Checkout = None,
order: Order = None,
+ return_url: str = None,
) -> Payment:
"""Create a payment instance.
@@ -123,6 +124,7 @@ def create_payment(
"currency": currency,
"gateway": gateway,
"total": total,
+ "return_url": return_url,
}
payment, _ = Payment.objects.get_or_create(defaults=defaults, **data)