Skip to content

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

init commit for adyen payment gateway

Maciej Korycinski432305a857a6
diff --git a/.isort.cfg b/.isort.cfg
index e63075b9ed..944b8a9090 100644
--- a/.isort.cfg
+++ b/.isort.cfg
@@ -1,2 +1,2 @@
[settings]
-known_third_party = PIL,babel,braintree,celery,dj_database_url,dj_email_url,django,django_cache_url,django_countries,django_filters,django_measurement,django_prices,django_prices_openexchangerates,django_prices_vatlayer,draftjs_sanitizer,faker,freezegun,geolite2,google_measurement_protocol,graphene,graphene_django,graphene_federation,graphql,graphql_relay,html_to_draftjs,i18naddress,jaeger_client,jwt,markdown,measurement,mptt,oauthlib,openpyxl,opentracing,petl,phonenumber_field,phonenumbers,pkg_resources,prices,promise,pytest,pythonjsonlogger,pytimeparse,pytz,razorpay,requests,sentry_sdk,storages,stripe,templated_email,tqdm,versatileimagefield,weasyprint
+known_third_party = Adyen,PIL,babel,braintree,celery,dj_database_url,dj_email_url,django,django_cache_url,django_countries,django_filters,django_measurement,django_prices,django_prices_openexchangerates,django_prices_vatlayer,draftjs_sanitizer,faker,freezegun,geolite2,google_measurement_protocol,graphene,graphene_django,graphene_federation,graphql,graphql_relay,html_to_draftjs,i18naddress,jaeger_client,jwt,markdown,measurement,mptt,oauthlib,openpyxl,opentracing,petl,phonenumber_field,phonenumbers,pkg_resources,prices,promise,pytest,pythonjsonlogger,pytimeparse,pytz,razorpay,requests,sentry_sdk,storages,stripe,templated_email,tqdm,versatileimagefield,weasyprint
diff --git a/saleor/checkout/base_calculations.py b/saleor/checkout/base_calculations.py
index e39a5faed0..5c9d772974 100644
--- a/saleor/checkout/base_calculations.py
+++ b/saleor/checkout/base_calculations.py
@@ -8,7 +8,8 @@ from typing import TYPE_CHECKING, Iterable, List, Optional
from prices import TaxedMoney
-from ..core.taxes import quantize_price, zero_taxed_money
+from ..core.prices import quantize_price
+from ..core.taxes import zero_taxed_money
from ..discount import DiscountInfo
if TYPE_CHECKING:
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.py
index 79bae61ce6..37e1587218 100644
--- a/saleor/checkout/calculations.py
+++ b/saleor/checkout/calculations.py
@@ -1,6 +1,6 @@
from typing import TYPE_CHECKING, Iterable, Optional
-from ..core.taxes import quantize_price
+from ..core.prices import quantize_price
from ..discount import DiscountInfo
from ..plugins.manager import get_plugins_manager
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index b716f295f0..ab24fd07ab 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -16,7 +16,8 @@ from ..account.utils import store_user_address
from ..checkout import calculations
from ..checkout.error_codes import CheckoutErrorCode
from ..core.exceptions import ProductNotPublished
-from ..core.taxes import quantize_price, zero_taxed_money
+from ..core.prices import quantize_price
+from ..core.taxes import zero_taxed_money
from ..core.utils.promo_code import (
InvalidPromoCode,
promo_code_is_gift_card,
diff --git a/saleor/core/payments.py b/saleor/core/payments.py
index 9ae8c39164..c25775a11a 100644
--- a/saleor/core/payments.py
+++ b/saleor/core/payments.py
@@ -1,9 +1,10 @@
from abc import ABC, abstractmethod
-from typing import TYPE_CHECKING, List, Optional
+from typing import TYPE_CHECKING, Iterable, List, Optional
if TYPE_CHECKING:
# flake8: noqa
- from ..checkout.models import Checkout
+ from ..checkout.models import Checkout, CheckoutLine
+ from ..discount import DiscountInfo
from ..payment.interface import (
PaymentData,
GatewayResponse,
@@ -22,7 +23,10 @@ class PaymentInterface(ABC):
@abstractmethod
def checkout_available_payment_gateways(
- self, checkout: "Checkout"
+ self,
+ checkout: "Checkout",
+ lines: Iterable["CheckoutLine"],
+ discounts: Iterable["DiscountInfo"],
) -> List["PaymentGateway"]:
pass
diff --git a/saleor/core/prices.py b/saleor/core/prices.py
new file mode 100644
index 0000000000..224c59b254
--- /dev/null
+++ b/saleor/core/prices.py
@@ -0,0 +1,12 @@
+from decimal import Decimal
+from typing import Union
+
+from babel.numbers import get_currency_precision
+
+
+def quantize_price(
+ price: Union["TaxedMoney", "Money", "Decimal", "TaxedMoneyRange"], currency: str
+) -> Union["TaxedMoney", "Money", "Decimal", "TaxedMoneyRange"]:
+ precision = get_currency_precision(currency)
+ number_places = Decimal(10) ** -precision
+ return price.quantize(number_places)
diff --git a/saleor/core/taxes.py b/saleor/core/taxes.py
index 2e2ec6577a..474e545028 100644
--- a/saleor/core/taxes.py
+++ b/saleor/core/taxes.py
@@ -1,8 +1,6 @@
from dataclasses import dataclass
-from decimal import Decimal
from typing import Union
-from babel.numbers import get_currency_precision
from django.conf import settings
from django.contrib.sites.models import Site
from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
@@ -54,14 +52,6 @@ def get_display_price(
return base
-def quantize_price(
- price: Union["TaxedMoney", "Money", "Decimal", "TaxedMoneyRange"], currency: str
-) -> Union["TaxedMoney", "Money", "Decimal", "TaxedMoneyRange"]:
- precision = get_currency_precision(currency)
- number_places = Decimal(10) ** -precision
- return price.quantize(number_places)
-
-
@dataclass(frozen=True)
class TaxType:
"""Dataclass for unifying tax type object that comes from tax gateway."""
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index 3b27fd4c69..b6c295245e 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -732,6 +732,12 @@ class CheckoutComplete(BaseMutation):
" before checkout is complete."
),
)
+ confirmation_data = graphene.JSONString(
+ required=False,
+ description=(
+ "Confirmation data used to process additional authorization steps."
+ ),
+ )
class Arguments:
checkout_id = graphene.ID(description="Checkout ID.", required=True)
@@ -789,6 +795,15 @@ class CheckoutComplete(BaseMutation):
payment = checkout.get_last_active_payment()
+ redirect_url = data.get("redirect_url", "")
+ if redirect_url:
+ try:
+ validate_storefront_url(redirect_url)
+ except ValidationError as error:
+ raise ValidationError(
+ {"redirect_url": error}, code=AccountErrorCode.INVALID
+ )
+
with transaction.atomic():
try:
order_data = prepare_order_data(
@@ -820,14 +835,14 @@ 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)
+ # else:
+ txn = gateway.process_payment(
+ payment=payment, token=payment.token, store_source=store_source
+ )
if not txn.is_success:
raise PaymentError(txn.error)
@@ -839,32 +854,30 @@ class CheckoutComplete(BaseMutation):
if txn.customer_id and user.is_authenticated:
store_customer_id(user, payment.gateway, txn.customer_id)
- redirect_url = data.get("redirect_url", "")
- if redirect_url:
- try:
- validate_storefront_url(redirect_url)
- except ValidationError as error:
- raise ValidationError(
- {"redirect_url": error}, code=AccountErrorCode.INVALID
- )
+ confirmation_needed = False
+ confirmation_data = {}
- order = None
- if not txn.action_required:
- # create the order into the database
- 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()
- # return the success response with the newly created order data
- return CheckoutComplete(order=order, confirmation_needed=False)
+ if txn.action_required:
+ # If gateway returns information that additional steps are required we need
+ # to inform the frontend and pass all required data
+ confirmation_needed = True
+ confirmation_data = txn.action_required_data
- return CheckoutComplete(order=None, confirmation_needed=True)
+ return CheckoutComplete(
+ order=order,
+ confirmation_needed=confirmation_needed,
+ confirmation_data=confirmation_data,
+ )
class CheckoutAddPromoCode(BaseMutation):
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index a47a058bab..d54cd856c1 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -244,8 +244,14 @@ class Checkout(CountableDjangoObjectType):
)
@staticmethod
- def resolve_available_payment_gateways(root: models.Checkout, _info):
- return get_plugins_manager().checkout_available_payment_gateways(checkout=root)
+ 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
+ )
@staticmethod
def resolve_gift_cards(root: models.Checkout, _info):
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index ce00bfc13e..4f7ca4cc90 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -1,3 +1,5 @@
+from typing import Optional
+
import graphene
from django.conf import settings
from django.core.exceptions import ValidationError
@@ -28,12 +30,16 @@ class PaymentInput(graphene.InputObjectType):
required=True,
)
token = graphene.String(
- required=True,
+ required=False,
description=(
"Client-side generated payment token, representing customer's "
"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=(
@@ -118,6 +124,24 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
}
)
+ @classmethod
+ def validate_token_or_data(cls, input_data: dict):
+ token = input_data.get("token")
+ payment_data = input_data.get("payment_data")
+ if not token and not payment_data:
+ raise ValidationError(
+ {
+ "token": ValidationError(
+ "paymentData or token is required.",
+ code=PaymentErrorCode.REQUIRED.value,
+ ),
+ "payment_data": ValidationError(
+ "paymentData or token is required.",
+ code=PaymentErrorCode.REQUIRED.value,
+ ),
+ }
+ )
+
@classmethod
def perform_mutation(cls, _root, info, checkout_id, **data):
checkout_id = from_global_id_strict_type(
@@ -131,6 +155,7 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
gateway = data["gateway"]
cls.validate_gateway(gateway, checkout.currency)
+ cls.validate_token_or_data(data)
checkout_total = cls.calculate_total(info, checkout)
amount = data.get("amount", checkout_total.gross.amount)
@@ -139,17 +164,26 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
)
clean_billing_address(checkout, PaymentErrorCode)
cls.clean_payment_amount(info, checkout_total, amount)
- extra_data = {"customer_user_agent": info.context.META.get("HTTP_USER_AGENT")}
+ extra_data = {
+ "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(
gateway=gateway,
- payment_token=data["token"],
+ payment_token=data.get("token", ""),
total=amount,
currency=settings.DEFAULT_CURRENCY,
email=checkout.email,
extra_data=extra_data,
+ # FIXME this is not a customer IP address. It is a client storefront ip
customer_ip_address=get_client_ip(info.context),
checkout=checkout,
)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index fb385d55b3..227f562d6c 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -897,6 +897,7 @@ type CheckoutComplete {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
order: Order
confirmationNeeded: Boolean!
+ confirmationData: JSONString
checkoutErrors: [CheckoutError!]!
}
@@ -3433,7 +3434,8 @@ type PaymentGateway {
input PaymentInput {
gateway: String!
- token: String!
+ token: String
+ paymentData: JSONString
amount: Decimal
billingAddress: AddressInput
}
diff --git a/saleor/payment/gateways/adyen/__init__.py b/saleor/payment/gateways/adyen/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/payment/gateways/adyen/plugin.py b/saleor/payment/gateways/adyen/plugin.py
new file mode 100644
index 0000000000..29ae71bc57
--- /dev/null
+++ b/saleor/payment/gateways/adyen/plugin.py
@@ -0,0 +1,235 @@
+import json
+from typing import Iterable, Optional
+
+import Adyen
+from django.conf import settings
+from django_countries.fields import Country
+from promise import Promise
+
+from ....checkout import calculations
+from ....checkout.models import Checkout, CheckoutLine
+from ....core.prices import quantize_price
+from ....discount import DiscountInfo
+from ....plugins.base_plugin import BasePlugin, ConfigurationTypeField
+from ... import PaymentError, TransactionKind
+from ...interface import GatewayConfig, GatewayResponse, PaymentData, PaymentGateway
+from ..utils import get_supported_currencies
+
+GATEWAY_NAME = "Adyen"
+
+
+def require_active_plugin(fn):
+ def wrapped(self, *args, **kwargs):
+ previous = kwargs.get("previous_value", None)
+ if not self.active:
+ return previous
+ return fn(self, *args, **kwargs)
+
+ return wrapped
+
+
+class AdyenGatewayPlugin(BasePlugin):
+
+ PLUGIN_ID = "mirumee.payments.adyen"
+ PLUGIN_NAME = GATEWAY_NAME
+ DEFAULT_CONFIGURATION = [
+ {"name": "Merchant Account", "value": None},
+ {"name": "API key", "value": None},
+ {"name": "Supported currencies", "value": ""},
+ {"name": "Return Url", "value": ""},
+ {"name": "Origin Key", "value": ""},
+ {"name": "Origin Url", "value": ""},
+ ]
+
+ CONFIG_STRUCTURE = {
+ "API key": {
+ "type": ConfigurationTypeField.SECRET,
+ "help_text": (
+ "To submit payments to Adyen, you'll be making API requests that are "
+ "authenticated with an API key. You can generate API keys on your "
+ "Customer Area."
+ ),
+ "label": "API key",
+ },
+ "Merchant Account": {
+ "type": ConfigurationTypeField.STRING,
+ "help_text": "Yout merchant account name.",
+ "label": "Merchant Account",
+ },
+ "Supported currencies": {
+ "type": ConfigurationTypeField.STRING,
+ "help_text": "Determines currencies supported by gateway."
+ " Please enter currency codes separated by a comma.",
+ "label": "Supported currencies",
+ },
+ "Return Url": {
+ "type": ConfigurationTypeField.STRING,
+ "help_text": "",
+ "label": "Return Url",
+ },
+ "Origin Key": {
+ "type": ConfigurationTypeField.STRING,
+ "help_text": "",
+ "label": "Origin Key",
+ },
+ "Origin Url": {
+ "type": ConfigurationTypeField.STRING,
+ "help_text": "",
+ "label": "Origin Url",
+ },
+ }
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ configuration = {item["name"]: item["value"] for item in self.configuration}
+ self.config = GatewayConfig(
+ gateway_name=GATEWAY_NAME,
+ auto_capture=True, # FIXME check this
+ supported_currencies=configuration["Supported currencies"],
+ connection_params={
+ "api_key": configuration["API key"],
+ "merchant_account": configuration["Merchant Account"],
+ "return_url": configuration["Return Url"],
+ "origin_key": configuration["Origin Key"],
+ },
+ )
+ api_key = self.config.connection_params["api_key"]
+ self.adyen = Adyen.Adyen(xapikey=api_key)
+
+ def _get_gateway_config(self) -> GatewayConfig:
+ return self.config
+
+ @require_active_plugin
+ def get_payment_gateway_for_checkout(
+ self,
+ checkout: "Checkout",
+ lines: Iterable["CheckoutLine"],
+ discounts: Iterable["DiscountInfo"],
+ 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)
+ return PaymentGateway(
+ id=self.PLUGIN_ID,
+ name=self.PLUGIN_NAME,
+ config=[
+ {
+ "field": "origin_key",
+ "value": config.connection_params["origin_key"],
+ },
+ {
+ "field": "config",
+ "value": json.dumps(response.message["paymentMethods"]),
+ },
+ ],
+ currencies=self.get_supported_currencies([]),
+ )
+
+ @require_active_plugin
+ 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
+ or "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"] = (
+ "https://" + payment_information.customer_ip_address
+ )
+
+ 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,
+ }
+ )
+ 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
+ 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,
+ amount=payment_information.amount,
+ currency=payment_information.currency,
+ transaction_id=payment_data.get("pspReference", ""),
+ error=None, # FIXME
+ raw_response=result.message,
+ )
+
+ @require_active_plugin
+ def get_payment_config(self, previous_value):
+ return []
+
+ @require_active_plugin
+ def get_supported_currencies(self, previous_value):
+ config = self._get_gateway_config()
+ return get_supported_currencies(config, GATEWAY_NAME)
diff --git a/saleor/payment/interface.py b/saleor/payment/interface.py
index bbb78c7fde..defbef5d3c 100644
--- a/saleor/payment/interface.py
+++ b/saleor/payment/interface.py
@@ -1,6 +1,9 @@
from dataclasses import dataclass
from decimal import Decimal
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, List, Optional, Union
+
+JSONValue = Union[str, int, float, bool, None, Dict[str, Any], List[Any]]
+JSONType = Union[Dict[str, JSONValue], List[JSONValue]]
@dataclass
@@ -32,6 +35,7 @@ class GatewayResponse:
customer_id: Optional[str] = None
card_info: Optional[CreditCardInfo] = None
raw_response: Optional[Dict[str, str]] = None
+ action_required_data: Optional[JSONType] = None
@dataclass
@@ -61,12 +65,14 @@ class PaymentData:
currency: str
billing: Optional[AddressData]
shipping: Optional[AddressData]
+ payment_id: str # GraphQL id
order_id: Optional[int]
customer_ip_address: Optional[str]
customer_email: str
token: Optional[str] = None
customer_id: Optional[str] = None
reuse_source: bool = False
+ extra_data: str = None
@dataclass
diff --git a/saleor/payment/migrations/0017_transaction_action_required_data.py b/saleor/payment/migrations/0017_transaction_action_required_data.py
new file mode 100644
index 0000000000..748946873b
--- /dev/null
+++ b/saleor/payment/migrations/0017_transaction_action_required_data.py
@@ -0,0 +1,24 @@
+# Generated by Django 3.0.6 on 2020-07-17 09:37
+
+import django.contrib.postgres.fields.jsonb
+import django.core.serializers.json
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("payment", "0016_auto_20200423_0314"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="transaction",
+ name="action_required_data",
+ field=django.contrib.postgres.fields.jsonb.JSONField(
+ blank=True,
+ default=dict,
+ encoder=django.core.serializers.json.DjangoJSONEncoder,
+ ),
+ ),
+ ]
diff --git a/saleor/payment/models.py b/saleor/payment/models.py
index d28df4bead..b1136f768a 100644
--- a/saleor/payment/models.py
+++ b/saleor/payment/models.py
@@ -195,6 +195,9 @@ class Transaction(models.Model):
kind = models.CharField(max_length=10, choices=TransactionKind.CHOICES)
is_success = models.BooleanField(default=False)
action_required = models.BooleanField(default=False)
+ action_required_data = JSONField(
+ blank=True, default=dict, encoder=DjangoJSONEncoder
+ )
currency = models.CharField(max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH)
amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 9bda393a87..9ed595baa8 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -1,8 +1,9 @@
import json
import logging
from decimal import Decimal
-from typing import Dict
+from typing import Dict, Optional
+import graphene
from django.conf import settings
from django.core.serializers.json import DjangoJSONEncoder
from django.db import transaction
@@ -47,6 +48,7 @@ def create_payment_information(
shipping_address = AddressData(**shipping.as_data()) if shipping else None
order_id = payment.order.pk if payment.order else None
+ payment_id = graphene.Node.to_global_id("Payment", payment.pk)
return PaymentData(
token=payment_token,
@@ -55,10 +57,12 @@ def create_payment_information(
billing=billing_address,
shipping=shipping_address,
order_id=order_id,
+ payment_id=payment_id,
customer_ip_address=payment.customer_ip_address,
customer_id=customer_id,
customer_email=payment.billing_email,
reuse_source=store_source,
+ extra_data=payment.extra_data,
)
@@ -68,7 +72,7 @@ def create_payment(
currency: str,
email: str,
customer_ip_address: str = "",
- payment_token: str = "",
+ payment_token: Optional[str] = "",
extra_data: Dict = None,
checkout: Checkout = None,
order: Order = None,
@@ -85,7 +89,7 @@ def create_payment(
data = {
"is_active": True,
"customer_ip_address": customer_ip_address,
- "extra_data": extra_data,
+ "extra_data": json.dumps(extra_data),
"token": payment_token,
}
@@ -158,6 +162,7 @@ def create_transaction(
error=gateway_response.error,
customer_id=gateway_response.customer_id,
gateway_response=gateway_response.raw_response or {},
+ action_required_data=gateway_response.action_required_data or {},
)
return txn
diff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.py
index 81983423ee..7ccdfabba3 100644
--- a/saleor/plugins/avatax/tests/test_avatax.py
+++ b/saleor/plugins/avatax/tests/test_avatax.py
@@ -5,7 +5,8 @@ from django.core.exceptions import ValidationError
from prices import Money, TaxedMoney
from ....checkout.utils import add_variant_to_checkout
-from ....core.taxes import TaxError, quantize_price
+from ....core.prices import quantize_price
+from ....core.taxes import TaxError
from ...manager import get_plugins_manager
from ...models import PluginConfiguration
from .. import (
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index 29573dcbc7..493ba3256d 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -1,6 +1,6 @@
from copy import copy
from decimal import Decimal
-from typing import TYPE_CHECKING, Any, List, Optional, Union
+from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Union
from django.core.handlers.wsgi import WSGIRequest
from django.http import HttpResponse
@@ -413,7 +413,11 @@ class BasePlugin:
)
def get_payment_gateway_for_checkout(
- self, checkout: "Checkout", previous_value
+ self,
+ checkout: "Checkout",
+ lines: Iterable["CheckoutLine"],
+ discounts: Iterable["DiscountInfo"],
+ 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 54ed3d0c00..6ceae293f6 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -11,7 +11,8 @@ from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
from ..checkout import base_calculations
from ..core.payments import PaymentInterface
-from ..core.taxes import TaxType, quantize_price, zero_taxed_money
+from ..core.prices import quantize_price
+from ..core.taxes import TaxType, zero_taxed_money
from ..discount import DiscountInfo
from .models import PluginConfiguration
@@ -366,13 +367,16 @@ class PluginsManager(PaymentInterface):
return gateways
def checkout_available_payment_gateways(
- self, checkout: "Checkout"
+ self,
+ checkout: "Checkout",
+ lines: Iterable["CheckoutLine"],
+ discounts: Iterable[DiscountInfo],
) -> 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, previous_value=None
+ checkout, lines, discounts, previous_value=None
)
if gateway:
gateways.append(gateway)
diff --git a/saleor/plugins/vatlayer/tests/test_vatlayer.py b/saleor/plugins/vatlayer/tests/test_vatlayer.py
index 020a702f00..bc3b40e881 100644
--- a/saleor/plugins/vatlayer/tests/test_vatlayer.py
+++ b/saleor/plugins/vatlayer/tests/test_vatlayer.py
@@ -9,7 +9,8 @@ from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
from ....checkout import calculations
from ....checkout.utils import add_variant_to_checkout
-from ....core.taxes import quantize_price, zero_taxed_money
+from ....core.prices import quantize_price
+from ....core.taxes import zero_taxed_money
from ...manager import get_plugins_manager
from ...models import PluginConfiguration
from ...vatlayer import (
diff --git a/saleor/settings.py b/saleor/settings.py
index 08e73a4817..ef85c86b62 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -515,6 +515,7 @@ PLUGINS = [
"saleor.payment.gateways.stripe.plugin.StripeGatewayPlugin",
"saleor.payment.gateways.braintree.plugin.BraintreeGatewayPlugin",
"saleor.payment.gateways.razorpay.plugin.RazorpayGatewayPlugin",
+ "saleor.payment.gateways.adyen.plugin.AdyenGatewayPlugin",
"saleor.plugins.invoicing.plugin.InvoicingPlugin",
]
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index d12d9d36c7..e4f4df7ef4 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -7,6 +7,7 @@ from io import BytesIO
from typing import List, Optional
from unittest.mock import MagicMock, Mock
+import graphene
import pytest
import pytz
from django.conf import settings
@@ -1569,10 +1570,11 @@ def dummy_gateway_config():
@pytest.fixture
-def dummy_payment_data():
+def dummy_payment_data(payment_dummy):
return PaymentData(
amount=10,
currency="USD",
+ payment_id=graphene.Node.to_global_id("Payment", payment_dummy.pk),
billing=None,
shipping=None,
order_id=None,