Skip to content

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

Add base functionalities for adyen

Maciej Korycinski77c9484c2585
diff --git a/saleor/core/payments.py b/saleor/core/payments.py
index c25775a11a..2d924585e7 100644
--- a/saleor/core/payments.py
+++ b/saleor/core/payments.py
@@ -23,10 +23,7 @@ class PaymentInterface(ABC):
@abstractmethod
def checkout_available_payment_gateways(
- self,
- checkout: "Checkout",
- lines: Iterable["CheckoutLine"],
- discounts: Iterable["DiscountInfo"],
+ self, checkout: "Checkout",
) -> List["PaymentGateway"]:
pass
@@ -60,6 +57,10 @@ class PaymentInterface(ABC):
) -> "GatewayResponse":
pass
+ @abstractmethod
+ def token_is_required_as_payment_input(self, gateway) -> bool:
+ pass
+
@abstractmethod
def process_payment(
self, gateway: str, payment_information: "PaymentData"
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index b6c295245e..2751884e6f 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -754,6 +754,12 @@ class CheckoutComplete(BaseMutation):
"see the order details. URL in RFC 1808 format."
),
)
+ payment_data = graphene.JSONString(
+ required=False,
+ description=(
+ "Client-side generated data required to finalize the payment."
+ ),
+ )
class Meta:
description = (
@@ -835,15 +841,17 @@ class CheckoutComplete(BaseMutation):
if shipping_address is not None:
shipping_address = AddressData(**shipping_address.as_data())
- # payment_confirmation = payment.to_confirm
+ payment_confirmation = payment.to_confirm
try:
- # if payment_confirmation:
- # txn = gateway.confirm(payment)
- # else:
- txn = gateway.process_payment(
- payment=payment, token=payment.token, store_source=store_source
- )
-
+ if payment_confirmation:
+ txn = gateway.confirm(payment, additional_data=data.get("payment_data"))
+ else:
+ txn = gateway.process_payment(
+ payment=payment,
+ token=payment.token,
+ store_source=store_source,
+ additional_data=data.get("payment_data"),
+ )
if not txn.is_success:
raise PaymentError(txn.error)
@@ -856,18 +864,20 @@ class CheckoutComplete(BaseMutation):
confirmation_needed = False
confirmation_data = {}
+ order = None
+
+ if not txn.action_required:
+ order = create_order(
+ checkout=checkout,
+ order_data=order_data,
+ user=user,
+ redirect_url=redirect_url,
+ )
- order = create_order(
- checkout=checkout,
- order_data=order_data,
- user=user,
- redirect_url=redirect_url,
- )
-
- # remove checkout after order is successfully paid
- checkout.delete()
+ # remove checkout after order is successfully paid
+ checkout.delete()
- if txn.action_required:
+ else:
# If gateway returns information that additional steps are required we need
# to inform the frontend and pass all required data
confirmation_needed = True
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index d54cd856c1..0b0383e378 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -245,13 +245,7 @@ class Checkout(CountableDjangoObjectType):
@staticmethod
def resolve_available_payment_gateways(root: models.Checkout, info):
- lines = CheckoutLinesByCheckoutTokenLoader(info.context).load(root.token)
- discounts = DiscountsByDateTimeLoader(info.context).load(
- info.context.request_time
- )
- return get_plugins_manager().checkout_available_payment_gateways(
- checkout=root, lines=lines, discounts=discounts
- )
+ return get_plugins_manager().checkout_available_payment_gateways(checkout=root)
@staticmethod
def resolve_gift_cards(root: models.Checkout, _info):
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index 4f7ca4cc90..2836b2e1cc 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -36,10 +36,6 @@ class PaymentInput(graphene.InputObjectType):
"billing data in a secure manner."
),
)
- payment_data = graphene.JSONString(
- required=False,
- description=("Client-side generated data required to finalize the payment."),
- )
amount = Decimal(
required=False,
description=(
@@ -125,18 +121,14 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
)
@classmethod
- def validate_token_or_data(cls, input_data: dict):
+ def validate_token(cls, manager, gateway: str, input_data: dict):
token = input_data.get("token")
- payment_data = input_data.get("payment_data")
- if not token and not payment_data:
+ is_required = manager.token_is_required_as_payment_input(gateway)
+ if not token and is_required:
raise ValidationError(
{
"token": ValidationError(
- "paymentData or token is required.",
- code=PaymentErrorCode.REQUIRED.value,
- ),
- "payment_data": ValidationError(
- "paymentData or token is required.",
+ f"Token is required for {gateway}.",
code=PaymentErrorCode.REQUIRED.value,
),
}
@@ -155,7 +147,7 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
gateway = data["gateway"]
cls.validate_gateway(gateway, checkout.currency)
- cls.validate_token_or_data(data)
+ cls.validate_token(info.context.plugins, gateway, data)
checkout_total = cls.calculate_total(info, checkout)
amount = data.get("amount", checkout_total.gross.amount)
@@ -168,12 +160,6 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
"customer_user_agent": info.context.META.get("HTTP_USER_AGENT"),
}
- # TODO Define if we want to store it in extra data as this field is available
- # over API
- payment_data = data.get("payment_data")
- if payment_data:
- extra_data["payment_data"] = payment_data
-
cancel_active_payments(checkout)
payment = create_payment(
diff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.py
index 9152c0aae3..6eae0cf6c1 100644
--- a/saleor/payment/__init__.py
+++ b/saleor/payment/__init__.py
@@ -60,14 +60,18 @@ class TransactionKind:
AUTH = "auth"
CAPTURE = "capture"
VOID = "void"
+ PENDING = "pending"
REFUND = "refund"
+ REFUND_ONGOING = "refund_ongoing"
CONFIRM = "confirm"
# FIXME we could use another status like WAITING_FOR_AUTH for transactions
# Which were authorized, but needs to be confirmed manually by staff
# eg. Braintree with "submit_for_settlement" enabled
CHOICES = [
(AUTH, "Authorization"),
+ (PENDING, "Pending"),
(REFUND, "Refund"),
+ (REFUND_ONGOING, "Refund in progress"),
(CAPTURE, "Capture"),
(VOID, "Void"),
(CONFIRM, "Confirm"),
@@ -88,6 +92,7 @@ class ChargeStatus:
"""
NOT_CHARGED = "not-charged"
+ PENDING = "pending"
PARTIALLY_CHARGED = "partially-charged"
FULLY_CHARGED = "fully-charged"
PARTIALLY_REFUNDED = "partially-refunded"
@@ -95,6 +100,7 @@ class ChargeStatus:
CHOICES = [
(NOT_CHARGED, "Not charged"),
+ (PENDING, "Pending"),
(PARTIALLY_CHARGED, "Partially charged"),
(FULLY_CHARGED, "Fully charged"),
(PARTIALLY_REFUNDED, "Partially refunded"),
diff --git a/saleor/payment/gateway.py b/saleor/payment/gateway.py
index 06e4b6708a..8b67679a39 100644
--- a/saleor/payment/gateway.py
+++ b/saleor/payment/gateway.py
@@ -1,6 +1,6 @@
import logging
from decimal import Decimal
-from typing import TYPE_CHECKING, Callable, List
+from typing import TYPE_CHECKING, Callable, List, Optional
from ..payment.interface import TokenConfig
from ..plugins.manager import get_plugins_manager
@@ -58,11 +58,17 @@ def require_active_payment(fn: Callable) -> Callable:
@raise_payment_error
@require_active_payment
def process_payment(
- payment: Payment, token: str, store_source: bool = False
+ payment: Payment,
+ token: str,
+ store_source: bool = False,
+ additional_data: Optional[dict] = None,
) -> Transaction:
plugin_manager = get_plugins_manager()
payment_data = create_payment_information(
- payment=payment, payment_token=token, store_source=store_source
+ payment=payment,
+ payment_token=token,
+ store_source=store_source,
+ additional_data=additional_data,
)
response, error = _fetch_gateway_response(
plugin_manager.process_payment, payment.gateway, payment_data
@@ -175,10 +181,12 @@ def void(payment: Payment) -> Transaction:
@payment_postprocess
@raise_payment_error
@require_active_payment
-def confirm(payment: Payment) -> Transaction:
+def confirm(payment: Payment, additional_data: Optional[dict] = None) -> Transaction:
plugin_manager = get_plugins_manager()
token = _get_past_transaction_token(payment, TransactionKind.CAPTURE)
- payment_data = create_payment_information(payment=payment, payment_token=token)
+ 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
)
diff --git a/saleor/payment/gateways/adyen/plugin.py b/saleor/payment/gateways/adyen/plugin.py
index 63d68e23cf..a9e4888a5f 100644
--- a/saleor/payment/gateways/adyen/plugin.py
+++ b/saleor/payment/gateways/adyen/plugin.py
@@ -1,19 +1,26 @@
import json
-from typing import Iterable, Optional
+from typing import Optional
import Adyen
-from django.conf import settings
-from django_countries.fields import Country
-from promise import Promise
+from babel.numbers import get_currency_precision
+from django.core.handlers.wsgi import WSGIRequest
+from django.http import HttpResponse, JsonResponse
+from graphql_relay import from_global_id
-from ....checkout import calculations
-from ....checkout.models import Checkout, CheckoutLine
+from ....checkout.models import Checkout
from ....core.prices import quantize_price
-from ....discount import DiscountInfo
+from ....graphql.core.scalars import Decimal
from ....plugins.base_plugin import BasePlugin, ConfigurationTypeField
from ... import PaymentError, TransactionKind
from ...interface import GatewayConfig, GatewayResponse, PaymentData, PaymentGateway
+from ...models import Transaction
from ..utils import get_supported_currencies
+from .utils import (
+ api_call,
+ request_data_for_gateway_config,
+ request_data_for_payment,
+ request_for_payment_refund,
+)
GATEWAY_NAME = "Adyen"
@@ -28,6 +35,9 @@ def require_active_plugin(fn):
return wrapped
+FAILED_STATUSES = ["refused", "error", "cancelled"]
+
+
class AdyenGatewayPlugin(BasePlugin):
PLUGIN_ID = "mirumee.payments.adyen"
@@ -39,6 +49,12 @@ class AdyenGatewayPlugin(BasePlugin):
{"name": "Return Url", "value": ""},
{"name": "Origin Key", "value": ""},
{"name": "Origin Url", "value": ""},
+ {"name": "Live", "value": ""},
+ {"name": "Enable notifications", "value": True},
+ {"name": "Automatically mark payment as a capture", "value": True},
+ {"name": "HMAC secret key", "value": ""},
+ {"name": "Notification user", "value": ""},
+ {"name": "Notification password", "value": ""},
]
CONFIG_STRUCTURE = {
@@ -64,19 +80,82 @@ class AdyenGatewayPlugin(BasePlugin):
},
"Return Url": {
"type": ConfigurationTypeField.STRING,
- "help_text": "",
+ "help_text": "", # FIXME define them as per channel
"label": "Return Url",
},
"Origin Key": {
"type": ConfigurationTypeField.STRING,
- "help_text": "",
+ "help_text": "", # FIXME define them as per channel
"label": "Origin Key",
},
"Origin Url": {
"type": ConfigurationTypeField.STRING,
- "help_text": "",
+ "help_text": "", # FIXME define them as per channel
"label": "Origin Url",
},
+ "Live": {
+ "type": ConfigurationTypeField.STRING,
+ "help_text": (
+ "Live 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 "
+ "data to the Adyen payments platform. "
+ "https://docs.adyen.com/development-resources/live-endpoints"
+ ),
+ "label": "Live",
+ },
+ "Enable notifications": {
+ "type": ConfigurationTypeField.BOOLEAN,
+ "help_text": (
+ "Enable the support for processing the Adyen's webhooks. The Saleor "
+ "webhook url is <your-backend-url>/plugins/mirumee.payments.adyen/"
+ "webhooks/ "
+ "https://docs.adyen.com/development-resources/webhooks"
+ ),
+ "label": "Enable notifications",
+ },
+ "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."
+ ),
+ "label": "Automatically mark payment as a capture",
+ },
+ "HMAC secret key": {
+ "type": ConfigurationTypeField.SECRET,
+ "help_text": (
+ "Provide secret key generated on Adyen side."
+ "https://docs.adyen.com/development-resources/webhooks#set-up-notificat"
+ "ions-in-your-customer-area"
+ ),
+ "label": "HMAC secret key",
+ },
+ "Notification user": {
+ "type": ConfigurationTypeField.STRING,
+ "help_text": (
+ "Base User provided on the Adyen side for authenticate incoming "
+ "notifications. https://docs.adyen.com/development-resources/webhooks#"
+ "set-up-notifications-in-your-customer-area"
+ ),
+ "label": "Notification user",
+ },
+ "Notification password": {
+ "type": ConfigurationTypeField.SECRET,
+ "help_text": (
+ "User password provided on the Adyen side for authenticate incoming "
+ "notifications. https://docs.adyen.com/development-resources/webhooks#"
+ "set-up-notifications-in-your-customer-area"
+ ),
+ "label": "Notification password",
+ },
}
def __init__(self, *args, **kwargs):
@@ -97,52 +176,28 @@ class AdyenGatewayPlugin(BasePlugin):
api_key = self.config.connection_params["api_key"]
self.adyen = Adyen.Adyen(xapikey=api_key)
+ def webhook(self, request: WSGIRequest, path: str, previous_value) -> HttpResponse:
+
+ print(request.body)
+ return HttpResponse("[accepted]")
+
def _get_gateway_config(self) -> GatewayConfig:
return self.config
+ @require_active_plugin
+ def token_is_required_as_payment_input(self, previous_value):
+ return False
+
@require_active_plugin
def get_payment_gateway_for_checkout(
- self,
- checkout: "Checkout",
- lines: Iterable["CheckoutLine"],
- discounts: Iterable["DiscountInfo"],
- previous_value,
+ self, checkout: "Checkout", previous_value,
) -> Optional["PaymentGateway"]:
- def checkout_total(data):
- lines, discounts = data
- return calculations.checkout_total(
- checkout=checkout, lines=lines, discounts=discounts
- )
-
- total = Promise.all([lines, discounts]).then(checkout_total)
config = self._get_gateway_config()
- merchant_account = config.connection_params["merchant_account"]
- address = checkout.billing_address or checkout.shipping_address
-
- # FIXME check how it works if we have None here
- country = address.country if address else None
- if country:
- country_code = country.code
- else:
- country_code = Country(settings.DEFAULT_COUNTRY).code
- channel = checkout.get_value_from_metadata("channel", "web")
- checkout.get_total_gift_cards_balance()
- request = {
- "merchantAccount": merchant_account,
- "countryCode": country_code,
- # "shopperLocale":
- # "amount": {
- # "value": float(
- # quantize_price(total.get().gross.amount, checkout.currency)
- # ),
- # "currency": checkout.currency,
- # },
- "channel": channel,
- }
- response = self.adyen.checkout.payment_methods(request)
- # self.adyen.checkout.origin_keys()
- print(response.message)
+ request = request_data_for_gateway_config(
+ checkout, config.connection_params["merchant_account"]
+ )
+ response = api_call(request, self.adyen.checkout.payment_methods)
return PaymentGateway(
id=self.PLUGIN_ID,
name=self.PLUGIN_NAME,
@@ -153,7 +208,7 @@ class AdyenGatewayPlugin(BasePlugin):
},
{
"field": "config",
- "value": json.dumps(response.message["paymentMethods"]),
+ "value": json.dumps(response.message.get("paymentMethods", {})),
},
],
currencies=self.get_supported_currencies([]),
@@ -163,64 +218,23 @@ class AdyenGatewayPlugin(BasePlugin):
def process_payment(
self, payment_information: "PaymentData", previous_value
) -> "GatewayResponse":
- extra_data = json.loads(payment_information.extra_data) # try catch here
- print(extra_data)
- payment_data = extra_data.get("payment_data")
- # this is additional parameter which comes from
- if not payment_data.pop("is_valid", True):
- raise PaymentError("Payment data are not valid")
-
- extra_request_params = {}
- if "browserInfo" in payment_data:
- extra_request_params["browserInfo"] = payment_data["browserInfo"]
- if "billingAddress" in payment_data:
- extra_request_params["billingAddress"] = payment_data["billingAddress"]
- if "shopperIP" in payment_data:
- extra_request_params["shopperIP"] = payment_data["shopperIP"]
- if (
- "browserInfo" in extra_request_params
- and "billingAddress" in extra_request_params
- ):
- # Replace this assigment. Add note that customer_ip_address has incorrect name
- # Add to dashboard config the flow to combine channel with url like:
- # web1:https://shop.com, web2:https://shop1.com
- extra_request_params["origin"] = self.config.connection_params["origin_url"]
-
- result = self.adyen.checkout.payments(
- {
- "amount": {
- "value": float(
- quantize_price(
- payment_information.amount, payment_information.currency
- )
- ),
- "currency": payment_information.currency,
- },
- "reference": payment_information.payment_id,
- "paymentMethod": payment_data["paymentMethod"],
- "returnUrl": self.config.connection_params["return_url"],
- "merchantAccount": self.config.connection_params["merchant_account"],
- **extra_request_params,
- }
+ request_data = request_data_for_payment(
+ payment_information,
+ return_url=self.config.connection_params["return_url"],
+ merchant_account=self.config.connection_params["merchant_account"],
+ origin_url=self.config.connection_params["origin_url"],
)
- FAILED_STATUSES = ["refused", "error", "cancelled"]
- # Check if further action is needed
- # if 'action' in result.message:
- # Pass the action object to your front end
- # result.message['action']
- # else:
- # No further action needed, pass the resultCode to your front end
- # result.message['resultCode']
- # FIXME Assign token
+
+ result = api_call(request_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.CAPTURE,
+ kind=TransactionKind.AUTH,
amount=payment_information.amount,
currency=payment_information.currency,
- transaction_id=payment_data.get("pspReference", ""),
- error=None, # FIXME
+ transaction_id=result.message.get("pspReference", ""),
+ error=result.message.get("refusalReason"),
raw_response=result.message,
)
@@ -232,3 +246,67 @@ class AdyenGatewayPlugin(BasePlugin):
def get_supported_currencies(self, previous_value):
config = self._get_gateway_config()
return get_supported_currencies(config, GATEWAY_NAME)
+
+ @require_active_plugin
+ def confirm_payment(
+ self, payment_information: "PaymentData", previous_value
+ ) -> "GatewayResponse":
+ additional_data = payment_information.data
+ 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,
+ )
+
+ @require_active_plugin
+ def refund_payment(
+ self, payment_information: "PaymentData", previous_value
+ ) -> "GatewayResponse":
+
+ _type, payment_id = from_global_id(payment_information.payment_id)
+ transaction = (
+ Transaction.objects.filter(
+ payment__id=payment_id, kind=TransactionKind.CAPTURE
+ )
+ .exclude(token__isnull=True, token__exact="")
+ .last()
+ )
+
+ if not transaction:
+ raise PaymentError("Cannot find a payment reference to refund.")
+
+ request = request_for_payment_refund(
+ payment_information=payment_information,
+ merchant_account=self.config.connection_params["merchant_account"],
+ token=transaction.token,
+ )
+ result = api_call(request, self.adyen.payment.refund)
+
+ return GatewayResponse(
+ is_success=True,
+ action_required=False,
+ kind=TransactionKind.REFUND_ONGOING,
+ amount=payment_information.amount,
+ currency=payment_information.currency,
+ transaction_id=result.message.get("pspReference", ""),
+ error="",
+ raw_response=result.message,
+ )
+
+ def capture_payment(
+ self, payment_information: "PaymentData", previous_value
+ ) -> "GatewayResponse":
+ pass
+
+ def void_payment(
+ self, payment_information: "PaymentData", previous_value
+ ) -> "GatewayResponse":
+ pass
diff --git a/saleor/payment/gateways/adyen/utils.py b/saleor/payment/gateways/adyen/utils.py
new file mode 100644
index 0000000000..41009cb812
--- /dev/null
+++ b/saleor/payment/gateways/adyen/utils.py
@@ -0,0 +1,113 @@
+import logging
+from decimal import Decimal
+from typing import Any, Callable, Dict
+
+import Adyen
+from babel.numbers import get_currency_precision
+from django.conf import settings
+from django_countries.fields import Country
+
+from ....checkout.models import Checkout
+from ....core.prices import quantize_price
+from ... import PaymentError
+from ...interface import PaymentData
+
+logger = logging.getLogger(__name__)
+
+
+def get_price_amount(value: Decimal, currency: str):
+ """Adyen doesn't use values with comma.
+
+ Take the value, discover the precision of currency and multiply value by
+ Decimal('10.0'), then change quantization to remove the comma.
+ """
+ value = quantize_price(value, currency=currency)
+ precision = get_currency_precision(currency)
+ number_places = Decimal("10.0") ** precision
+ value_without_comma = value * number_places
+ return str(value_without_comma.quantize(Decimal("1")))
+
+
+def api_call(requst_data: Dict[str, Any], method: Callable) -> Adyen.Adyen:
+ try:
+ return method(requst_data)
+ except (Adyen.AdyenError, ValueError, TypeError) as e:
+ logger.error(f"Unable to process the payment: {e}")
+ raise PaymentError("Unable to process the payment request.")
+
+
+def request_data_for_payment(
+ payment_information: "PaymentData", return_url, merchant_account, origin_url
+) -> Dict[str, Any]:
+ payment_data = payment_information.data or {}
+
+ if not payment_data.pop("is_valid", True):
+ raise PaymentError("Payment data are not valid")
+
+ extra_request_params = {}
+ if "browserInfo" in payment_data:
+ extra_request_params["browserInfo"] = payment_data["browserInfo"]
+ if "billingAddress" in payment_data:
+ extra_request_params["billingAddress"] = payment_data["billingAddress"]
+ if "shopperIP" in payment_data:
+ extra_request_params["shopperIP"] = payment_data["shopperIP"]
+ if (
+ "browserInfo" in extra_request_params
+ and "billingAddress" in extra_request_params
+ ):
+ # Replace this assigment. Add note that customer_ip_address has incorrect name
+ # Add to dashboard config the flow to combine channel with url like:
+ # web1:https://shop.com, web2:https://shop1.com
+ extra_request_params["origin"] = origin_url
+ print(
+ float(quantize_price(payment_information.amount, payment_information.currency))
+ )
+ request = {
+ "amount": {
+ "value": get_price_amount(
+ payment_information.amount, payment_information.currency
+ ),
+ "currency": payment_information.currency,
+ },
+ "reference": payment_information.payment_id,
+ "paymentMethod": payment_data["paymentMethod"],
+ "returnUrl": return_url,
+ "merchantAccount": merchant_account,
+ **extra_request_params,
+ }
+ return request
+
+
+def request_data_for_gateway_config(
+ checkout: "Checkout", merchant_account
+) -> Dict[str, str]:
+ address = checkout.billing_address or checkout.shipping_address
+
+ # FIXME check how it works if we have None here
+ country = address.country if address else None
+ if country:
+ country_code = country.code
+ else:
+ country_code = Country(settings.DEFAULT_COUNTRY).code
+ channel = checkout.get_value_from_metadata("channel", "web")
+ return {
+ "merchantAccount": merchant_account,
+ "countryCode": country_code,
+ "channel": channel,
+ }
+
+
+def request_for_payment_refund(
+ payment_information: "PaymentData", merchant_account, token
+) -> Dict[str, Any]:
+ return {
+ "merchantAccount": merchant_account,
+ "modificationAmount": {
+ "value": get_price_amount(
+ payment_information.amount, payment_information.currency
+ ),
+ "currency": payment_information.currency,
+ },
+ "originalReference": token,
+ "reference": payment_information.payment_id,
+ }
diff --git a/saleor/payment/interface.py b/saleor/payment/interface.py
index defbef5d3c..3f074dd9b6 100644
--- a/saleor/payment/interface.py
+++ b/saleor/payment/interface.py
@@ -72,7 +72,7 @@ class PaymentData:
token: Optional[str] = None
customer_id: Optional[str] = None
reuse_source: bool = False
- extra_data: str = None
+ data: Optional[JSONType] = None
@dataclass
diff --git a/saleor/payment/migrations/0018_auto_20200720_1118.py b/saleor/payment/migrations/0018_auto_20200720_1118.py
new file mode 100644
index 0000000000..a82d360465
--- /dev/null
+++ b/saleor/payment/migrations/0018_auto_20200720_1118.py
@@ -0,0 +1,45 @@
+# Generated by Django 3.0.6 on 2020-07-20 11:18
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("payment", "0017_transaction_action_required_data"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="payment",
+ name="charge_status",
+ field=models.CharField(
+ choices=[
+ ("action-required", "Action required"),
+ ("not-charged", "Not charged"),
+ ("partially-charged", "Partially charged"),
+ ("fully-charged", "Fully charged"),
+ ("partially-refunded", "Partially refunded"),
+ ("fully-refunded", "Fully refunded"),
+ ],
+ default="not-charged",
+ max_length=20,
+ ),
+ ),
+ migrations.AlterField(
+ model_name="transaction",
+ name="kind",
+ field=models.CharField(
+ choices=[
+ ("action", "Action required"),
+ ("auth", "Authorization"),
+ ("refund", "Refund"),
+ ("refund_ongoing", "Refund in progress"),
+ ("capture", "Capture"),
+ ("void", "Void"),
+ ("confirm", "Confirm"),
+ ],
+ max_length=25,
+ ),
+ ),
+ ]
diff --git a/saleor/payment/models.py b/saleor/payment/models.py
index b1136f768a..7c651ee52c 100644
--- a/saleor/payment/models.py
+++ b/saleor/payment/models.py
@@ -192,7 +192,7 @@ class Transaction(models.Model):
Payment, related_name="transactions", on_delete=models.PROTECT
)
token = models.CharField(max_length=128, blank=True, default="")
- kind = models.CharField(max_length=10, choices=TransactionKind.CHOICES)
+ kind = models.CharField(max_length=25, choices=TransactionKind.CHOICES)
is_success = models.BooleanField(default=False)
action_required = models.BooleanField(default=False)
action_required_data = JSONField(
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 9ed595baa8..99d0fc03c8 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -29,6 +29,7 @@ def create_payment_information(
amount: Decimal = None,
customer_id: str = None,
store_source: bool = False,
+ additional_data: Optional[dict] = None,
) -> PaymentData:
"""Extract order information along with payment details.
@@ -62,7 +63,7 @@ def create_payment_information(
customer_id=customer_id,
customer_email=payment.billing_email,
reuse_source=store_source,
- extra_data=payment.extra_data,
+ data=additional_data or {},
)
@@ -215,6 +216,9 @@ def gateway_postprocess(transaction, payment):
return
transaction_kind = transaction.kind
+ # if transaction.action_required:
+ # payment.charge_status = ChargeStatus.ACTION_REQUIRED
+ # payment.save(update_fields=["charge_status", ])
if transaction_kind in {TransactionKind.CAPTURE, TransactionKind.CONFIRM}:
payment.captured_amount += transaction.amount
@@ -240,6 +244,11 @@ def gateway_postprocess(transaction, payment):
payment.is_active = False
changed_fields += ["charge_status", "is_active"]
payment.save(update_fields=changed_fields)
+ elif transaction_kind == TransactionKind.PENDING:
+ payment.charge_status = ChargeStatus.PENDING
+ payment.save(
+ update_fields=["charge_status",]
+ )
def fetch_customer_id(user: User, gateway: str):
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index 493ba3256d..77782c342f 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -367,6 +367,11 @@ class BasePlugin:
) -> "GatewayResponse":
return NotImplemented
+ def void_payment(
+ self, payment_information: "PaymentData", previous_value
+ ) -> "GatewayResponse":
+ return NotImplemented
+
def refund_payment(
self, payment_information: "PaymentData", previous_value
) -> "GatewayResponse":
@@ -396,6 +401,9 @@ class BasePlugin:
def get_supported_currencies(self, previous_value):
return NotImplemented
+ def token_is_required_as_payment_input(self, previous_value):
+ return previous_value
+
def get_payment_gateway(
self, currency: Optional[str], previous_value
) -> Optional["PaymentGateway"]:
@@ -413,11 +421,7 @@ class BasePlugin:
)
def get_payment_gateway_for_checkout(
- self,
- checkout: "Checkout",
- lines: Iterable["CheckoutLine"],
- discounts: Iterable["DiscountInfo"],
- previous_value,
+ self, checkout: "Checkout", previous_value,
) -> Optional["PaymentGateway"]:
return self.get_payment_gateway(checkout.currency, previous_value)
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 6ceae293f6..51aa9d68c2 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -319,6 +319,16 @@ class PluginsManager(PaymentInterface):
method_name = "process_payment"
return self.__run_payment_method(gateway, method_name, payment_information)
+ def token_is_required_as_payment_input(self, gateway) -> bool:
+ method_name = "token_is_required_as_payment_input"
+ default_value = True
+ gtw = self.get_plugin(gateway)
+ if gtw is not None:
+ return self.__run_method_on_single_plugin(
+ gtw, method_name, previous_value=default_value,
+ )
+ return default_value
+
def get_client_token(self, gateway, token_config: "TokenConfig") -> str:
method_name = "get_client_token"
default_value = None
@@ -367,16 +377,13 @@ class PluginsManager(PaymentInterface):
return gateways
def checkout_available_payment_gateways(
- self,
- checkout: "Checkout",
- lines: Iterable["CheckoutLine"],
- discounts: Iterable[DiscountInfo],
+ self, checkout: "Checkout",
) -> List["PaymentGateway"]:
payment_plugins = self.list_payment_plugin(active_only=True)
gateways = []
for plugin in payment_plugins.values():
gateway = plugin.get_payment_gateway_for_checkout(
- checkout, lines, discounts, previous_value=None
+ checkout, previous_value=None
)
if gateway:
gateways.append(gateway)