Skip to content

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

Support for Apple Pay on web (#6396)

Maciej Korycinskic89cde136706
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index 3b7a42aab6..1ae22f3ed9 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -18,7 +18,7 @@ from ..core.mutations import BaseMutation
from ..core.scalars import PositiveDecimal
from ..core.types import common as common_types
from ..core.utils import from_global_id_strict_type
-from .types import Payment
+from .types import Payment, PaymentInitialized
class PaymentInput(graphene.InputObjectType):
@@ -254,3 +254,37 @@ class PaymentVoid(BaseMutation):
except PaymentError as e:
raise ValidationError(str(e), code=PaymentErrorCode.PAYMENT_ERROR)
return PaymentVoid(payment=payment)
+
+
+class PaymentInitialize(BaseMutation):
+ initialized_payment = graphene.Field(PaymentInitialized, required=False)
+
+ class Arguments:
+ gateway = graphene.String(
+ description="A gateway name used to initialize the payment.", required=True,
+ )
+ payment_data = graphene.JSONString(
+ required=False,
+ description=(
+ "Client-side generated data required to initialize the payment."
+ ),
+ )
+
+ class Meta:
+ description = "Initializes payment process when it is required by gateway."
+ error_type_class = common_types.PaymentError
+ error_type_field = "payment_errors"
+
+ @classmethod
+ def perform_mutation(cls, _root, info, gateway, payment_data):
+ try:
+ response = info.context.plugins.initialize_payment(gateway, payment_data)
+ except PaymentError as e:
+ raise ValidationError(
+ {
+ "payment_data": ValidationError(
+ str(e), code=PaymentErrorCode.INVALID.value
+ )
+ }
+ )
+ return PaymentInitialize(initialized_payment=response)
diff --git a/saleor/graphql/payment/schema.py b/saleor/graphql/payment/schema.py
index 7bc6111d40..1958e61d33 100644
--- a/saleor/graphql/payment/schema.py
+++ b/saleor/graphql/payment/schema.py
@@ -3,7 +3,7 @@ import graphene
from ...core.permissions import OrderPermissions
from ..core.fields import PrefetchingConnectionField
from ..decorators import permission_required
-from .mutations import PaymentCapture, PaymentRefund, PaymentVoid
+from .mutations import PaymentCapture, PaymentInitialize, PaymentRefund, PaymentVoid
from .resolvers import resolve_payments
from .types import Payment
@@ -31,3 +31,4 @@ class PaymentMutations(graphene.ObjectType):
payment_capture = PaymentCapture.Field()
payment_refund = PaymentRefund.Field()
payment_void = PaymentVoid.Field()
+ payment_initialize = PaymentInitialize.Field()
diff --git a/saleor/graphql/payment/tests/test_payment.py b/saleor/graphql/payment/tests/test_payment.py
index 6019a87a9b..dd3b8177bb 100644
--- a/saleor/graphql/payment/tests/test_payment.py
+++ b/saleor/graphql/payment/tests/test_payment.py
@@ -1,3 +1,4 @@
+import json
from decimal import Decimal
from unittest.mock import patch
@@ -5,14 +6,21 @@ import graphene
import pytest
from ....checkout import calculations
+from ....payment import PaymentError
from ....payment.error_codes import PaymentErrorCode
from ....payment.gateways.dummy_credit_card import (
TOKEN_EXPIRED,
TOKEN_VALIDATION_MAPPING,
)
-from ....payment.interface import CustomerSource, PaymentMethodInfo, TokenConfig
+from ....payment.interface import (
+ CustomerSource,
+ InitializedPaymentResponse,
+ PaymentMethodInfo,
+ TokenConfig,
+)
from ....payment.models import ChargeStatus, Payment, TransactionKind
from ....payment.utils import fetch_customer_id, store_customer_id
+from ....plugins.manager import PluginsManager
from ...tests.utils import assert_no_permission, get_graphql_content
from ..enums import OrderAction, PaymentChargeStatusEnum
@@ -821,3 +829,87 @@ def test_stored_payment_sources_restriction(
query, variables, permissions=[permission_manage_users]
)
assert_no_permission(response)
+
+
+PAYMENT_INITIALIZE_MUTATION = """
+mutation PaymentInitialize($gateway: String!, $paymentData: JSONString){
+ paymentInitialize(gateway: $gateway, paymentData: $paymentData)
+ {
+ initializedPayment{
+ gateway
+ name
+ data
+ }
+ paymentErrors{
+ field
+ message
+ }
+ }
+}
+"""
+
+
[email protected](PluginsManager, "initialize_payment")
+def test_payment_initialize(mocked_initialize_payment, api_client):
+ exected_initialize_payment_response = InitializedPaymentResponse(
+ gateway="gateway.id",
+ name="PaymentPluginName",
+ data={
+ "epochTimestamp": 1604652056653,
+ "expiresAt": 1604655656653,
+ "merchantSessionIdentifier": "SSH5EFCB46BA25C4B14B3F37795A7F5B974_BB8E",
+ },
+ )
+ mocked_initialize_payment.return_value = exected_initialize_payment_response
+
+ query = PAYMENT_INITIALIZE_MUTATION
+ variables = {
+ "gateway": exected_initialize_payment_response.gateway,
+ "paymentData": json.dumps(
+ {"paymentMethod": "applepay", "validationUrl": "https://127.0.0.1/valid"}
+ ),
+ }
+ response = api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ init_payment_data = content["data"]["paymentInitialize"]["initializedPayment"]
+ assert init_payment_data["gateway"] == exected_initialize_payment_response.gateway
+ assert init_payment_data["name"] == exected_initialize_payment_response.name
+ assert (
+ json.loads(init_payment_data["data"])
+ == exected_initialize_payment_response.data
+ )
+
+
+def test_payment_initialize_gateway_doesnt_exist(api_client):
+ query = PAYMENT_INITIALIZE_MUTATION
+ variables = {
+ "gateway": "wrong.gateway",
+ "paymentData": json.dumps(
+ {"paymentMethod": "applepay", "validationUrl": "https://127.0.0.1/valid"}
+ ),
+ }
+ response = api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["paymentInitialize"]["initializedPayment"] is None
+
+
[email protected](PluginsManager, "initialize_payment")
+def test_payment_initialize_plugin_raises_error(mocked_initialize_payment, api_client):
+ error_msg = "Missing paymentMethod field."
+ mocked_initialize_payment.side_effect = PaymentError(error_msg)
+
+ query = PAYMENT_INITIALIZE_MUTATION
+ variables = {
+ "gateway": "gateway.id",
+ "paymentData": json.dumps({"validationUrl": "https://127.0.0.1/valid"}),
+ }
+ response = api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ initialized_payment_data = content["data"]["paymentInitialize"][
+ "initializedPayment"
+ ]
+ errors = content["data"]["paymentInitialize"]["paymentErrors"]
+ assert initialized_payment_data is None
+ assert len(errors) == 1
+ assert errors[0]["field"] == "paymentData"
+ assert errors[0]["message"] == error_msg
diff --git a/saleor/graphql/payment/types.py b/saleor/graphql/payment/types.py
index c737b3f6c1..8639cbcac9 100644
--- a/saleor/graphql/payment/types.py
+++ b/saleor/graphql/payment/types.py
@@ -152,3 +152,18 @@ class Payment(CountableDjangoObjectType):
if not any(data.values()):
return None
return CreditCard(**data)
+
+
+class PaymentInitialized(graphene.ObjectType):
+ class Meta:
+ description = (
+ "Server-side data generated by a payment gateway. Optional step when the "
+ "payment provider requires an additional action to initialize payment "
+ "session."
+ )
+
+ gateway = graphene.String(description="ID of a payment gateway.", required=True)
+ name = graphene.String(description="Payment gateway name.", required=True)
+ data = graphene.JSONString(
+ description="Initialized data by gateway.", required=False
+ )
diff --git a/saleor/graphql/plugins/tests/test_plugins.py b/saleor/graphql/plugins/tests/test_plugins.py
index cf0727c514..99f0effc03 100644
--- a/saleor/graphql/plugins/tests/test_plugins.py
+++ b/saleor/graphql/plugins/tests/test_plugins.py
@@ -80,12 +80,12 @@ def test_query_plugin_configurations(staff_api_client_can_manage_plugins, settin
@pytest.mark.parametrize(
- "password, expected_password, api_key, expected_api_key",
+ "password, expected_password, api_key, expected_api_key, cert, expected_cert",
[
- (None, None, None, None),
- ("ABCDEFGHIJ", "", "123456789", "6789"),
- ("", None, "", None),
- (None, None, "1234", "4"),
+ (None, None, None, None, None, None),
+ ("ABCDEFGHIJ", "", "123456789", "6789", "long text\n with new\n lines", "ines"),
+ ("", None, "", None, "", None),
+ (None, None, "1234", "4", None, None),
],
)
def test_query_plugins_hides_secret_fields(
@@ -93,6 +93,8 @@ def test_query_plugins_hides_secret_fields(
expected_password,
api_key,
expected_api_key,
+ cert,
+ expected_cert,
staff_api_client,
permission_manage_plugins,
settings,
@@ -107,6 +109,8 @@ def test_query_plugins_hides_secret_fields(
conf_field["value"] = password
if conf_field["name"] == "API private key":
conf_field["value"] = api_key
+ if conf_field["name"] == "certificate":
+ conf_field["value"] = cert
manager.save_plugin_configuration(
PluginSample.PLUGIN_ID,
{
diff --git a/saleor/graphql/plugins/types.py b/saleor/graphql/plugins/types.py
index 94cf809e60..555a7a9069 100644
--- a/saleor/graphql/plugins/types.py
+++ b/saleor/graphql/plugins/types.py
@@ -22,7 +22,10 @@ def hide_private_configuration_fields(configuration, config_structure):
if field_type == ConfigurationTypeField.PASSWORD:
field["value"] = "" if value else None
- if field_type == ConfigurationTypeField.SECRET:
+ if field_type in [
+ ConfigurationTypeField.SECRET,
+ ConfigurationTypeField.SECRET_MULTILINE,
+ ]:
if not value:
field["value"] = None
elif len(value) > 4:
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index e536c91dab..ab835c396f 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1148,6 +1148,7 @@ enum ConfigurationTypeFieldEnum {
BOOLEAN
SECRET
PASSWORD
+ SECRETMULTILINE
}
type ConfirmAccount {
@@ -2501,6 +2502,7 @@ type Mutation {
paymentCapture(amount: PositiveDecimal, paymentId: ID!): PaymentCapture
paymentRefund(amount: PositiveDecimal, paymentId: ID!): PaymentRefund
paymentVoid(paymentId: ID!): PaymentVoid
+ paymentInitialize(gateway: String!, paymentData: JSONString): PaymentInitialize
pageCreate(input: PageInput!): PageCreate
pageDelete(id: ID!): PageDelete
pageBulkDelete(ids: [ID]!): PageBulkDelete
@@ -3225,6 +3227,18 @@ type PaymentGateway {
currencies: [String]!
}
+type PaymentInitialize {
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
+ initializedPayment: PaymentInitialized
+ paymentErrors: [PaymentError!]!
+}
+
+type PaymentInitialized {
+ gateway: String!
+ name: String!
+ data: JSONString
+}
+
input PaymentInput {
gateway: String!
token: String
diff --git a/saleor/payment/gateways/adyen/plugin.py b/saleor/payment/gateways/adyen/plugin.py
index 7ef53c797b..17225997a5 100644
--- a/saleor/payment/gateways/adyen/plugin.py
+++ b/saleor/payment/gateways/adyen/plugin.py
@@ -4,20 +4,30 @@ from urllib.parse import urlencode
import Adyen
from django.contrib.auth.hashers import make_password
-from django.core.exceptions import ObjectDoesNotExist
+from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.core.handlers.wsgi import WSGIRequest
from django.http import HttpResponse, HttpResponseNotFound
+from requests.exceptions import SSLError
from ....checkout.models import Checkout
from ....core.utils import build_absolute_uri
from ....core.utils.url import prepare_url
from ....order.events import external_notification_event
from ....plugins.base_plugin import BasePlugin, ConfigurationTypeField
+from ....plugins.error_codes import PluginErrorCode
+from ....plugins.models import PluginConfiguration
from ... import PaymentError, TransactionKind
-from ...interface import GatewayConfig, GatewayResponse, PaymentData, PaymentGateway
+from ...interface import (
+ GatewayConfig,
+ GatewayResponse,
+ InitializedPaymentResponse,
+ PaymentData,
+ PaymentGateway,
+)
from ...models import Payment, Transaction
from ..utils import get_supported_currencies
-from .utils import (
+from .utils.apple_pay import initialize_apple_pay, make_request_to_initialize_apple_pay
+from .utils.common import (
AUTH_STATUS,
FAILED_STATUSES,
PENDING_STATUSES,
@@ -62,6 +72,7 @@ class AdyenGatewayPlugin(BasePlugin):
{"name": "notification-user", "value": ""},
{"name": "notification-password", "value": ""},
{"name": "enable-native-3d-secure", "value": False},
+ {"name": "apple-pay-cert", "value": None},
]
CONFIG_STRUCTURE = {
@@ -168,6 +179,17 @@ class AdyenGatewayPlugin(BasePlugin):
),
"label": "Enable native 3D Secure",
},
+ "apple-pay-cert": {
+ "type": ConfigurationTypeField.SECRET_MULTILINE,
+ "help_text": (
+ "Follow the Adyen docs related to activating the Apple Pay for the "
+ "web - https://docs.adyen.com/payment-methods/apple-pay/"
+ "enable-apple-pay. This certificate is only required when you offer "
+ "the Apple Pay as a web payment method. Leave it blank if you don't "
+ "offer Apple Pay or offer it only as a payment method in your iOS app."
+ ),
+ "label": "Apple Pay certificate",
+ },
}
def __init__(self, *args, **kwargs):
@@ -187,6 +209,7 @@ class AdyenGatewayPlugin(BasePlugin):
"webhook_user_password": configuration["notification-password"],
"adyen_auto_capture": configuration["adyen-auto-capture"],
"enable_native_3d_secure": configuration["enable-native-3d-secure"],
+ "apple_pay_cert": configuration["apple-pay-cert"],
},
)
api_key = self.config.connection_params["api_key"]
@@ -214,6 +237,21 @@ class AdyenGatewayPlugin(BasePlugin):
def token_is_required_as_payment_input(self, previous_value):
return False
+ @require_active_plugin
+ def initialize_payment(
+ self, payment_data, previous_value
+ ) -> "InitializedPaymentResponse":
+ payment_method = payment_data.get("paymentMethod")
+ if payment_method == "applepay":
+ # The apple pay on the web requires additional step
+ session_obj = initialize_apple_pay(
+ payment_data, self.config.connection_params["apple_pay_cert"]
+ )
+ return InitializedPaymentResponse(
+ gateway=self.PLUGIN_ID, name=self.PLUGIN_NAME, data=session_obj
+ )
+ return previous_value
+
@require_active_plugin
def get_payment_gateway_for_checkout(
self, checkout: "Checkout", previous_value,
@@ -551,3 +589,40 @@ class AdyenGatewayPlugin(BasePlugin):
raw_response=result.message,
searchable_key=result.message.get("pspReference", ""),
)
+
+ @classmethod
+ def validate_plugin_configuration(cls, plugin_configuration: "PluginConfiguration"):
+ """Validate if provided configuration is correct."""
+ configuration = plugin_configuration.configuration
+ configuration = {item["name"]: item["value"] for item in configuration}
+ apple_certificate = configuration["apple-pay-cert"]
+ if plugin_configuration.active and apple_certificate:
+ global_apple_url = (
+ "https://apple-pay-gateway.apple.com/paymentservices/paymentSession"
+ )
+ request_data = {
+ "merchantIdentifier": "",
+ "displayName": "",
+ "initiative": "web",
+ "initiativeContext": "",
+ }
+ # Try to exectue the session request without all required data. If the
+ # apple certificate is correct we will get the error related to the missing
+ # parameters. If certificate is incorrect, the SSL error will be raised.
+ try:
+ make_request_to_initialize_apple_pay(
+ validation_url=global_apple_url,
+ request_data=request_data,
+ certificate=apple_certificate,
+ )
+ except SSLError:
+ raise ValidationError(
+ {
+ "apple-pay-cert": ValidationError(
+ "The provided apple certificate is invalid.",
+ code=PluginErrorCode.INVALID.value,
+ )
+ }
+ )
+ except Exception:
+ pass
diff --git a/saleor/payment/gateways/adyen/tests/conftest.py b/saleor/payment/gateways/adyen/tests/conftest.py
index c58404c52f..7092b803c1 100644
--- a/saleor/payment/gateways/adyen/tests/conftest.py
+++ b/saleor/payment/gateways/adyen/tests/conftest.py
@@ -1,3 +1,5 @@
+from unittest import mock
+
import pytest
from .....checkout import calculations
@@ -18,6 +20,7 @@ def adyen_plugin(settings):
origin_url=None,
adyen_auto_capture=None,
auto_capture=None,
+ apple_pay_cert=None,
):
api_key = api_key or "test_key"
merchant_account = merchant_account or "SaleorECOM"
@@ -28,22 +31,25 @@ def adyen_plugin(settings):
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": "client-key", "value": client_key},
- {"name": "origin-url", "value": origin_url},
- {"name": "adyen-auto-capture", "value": adyen_auto_capture},
- {"name": "auto-capture", "value": auto_capture},
- {"name": "supported-currencies", "value": "USD"},
- ],
- },
- )
+
+ with mock.patch("saleor.payment.gateways.adyen.utils.apple_pay.requests.post"):
+ 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": "client-key", "value": client_key},
+ {"name": "origin-url", "value": origin_url},
+ {"name": "adyen-auto-capture", "value": adyen_auto_capture},
+ {"name": "auto-capture", "value": auto_capture},
+ {"name": "supported-currencies", "value": "USD"},
+ {"name": "apple-pay-cert", "value": apple_pay_cert},
+ ],
+ },
+ )
manager = get_plugins_manager()
return manager.plugins[0]
diff --git a/saleor/payment/gateways/adyen/tests/test_plugin.py b/saleor/payment/gateways/adyen/tests/test_plugin.py
index 6972902ac7..ffade9edca 100644
--- a/saleor/payment/gateways/adyen/tests/test_plugin.py
+++ b/saleor/payment/gateways/adyen/tests/test_plugin.py
@@ -3,7 +3,10 @@ from decimal import Decimal
from unittest import mock
import pytest
+from django.core.exceptions import ValidationError
+from requests.exceptions import RequestException, SSLError
+from .....plugins.models import PluginConfiguration
from .... import PaymentError, TransactionKind
from ....interface import GatewayResponse, PaymentMethodInfo
from ....models import Payment
@@ -473,3 +476,22 @@ def test_capture_payment(payment_adyen_for_order, order_with_lines, adyen_plugin
assert response.currency == order_with_lines.currency
assert response.transaction_id == "852595499936560C" # ID returned by Adyen
assert response.payment_method_info == PaymentMethodInfo(brand="visa", type="test")
+
+
[email protected]("saleor.payment.gateways.adyen.utils.apple_pay.requests.post")
+def test_validate_plugin_configuration_incorrect_certificate(
+ mocked_request, adyen_plugin
+):
+ plugin = adyen_plugin(apple_pay_cert="cert")
+ mocked_request.side_effect = SSLError()
+ configuration = PluginConfiguration.objects.get()
+ with pytest.raises(ValidationError):
+ plugin.validate_plugin_configuration(configuration)
+
+
[email protected]("saleor.payment.gateways.adyen.utils.apple_pay.requests.post")
+def test_validate_plugin_configuration_correct_cert(mocked_request, adyen_plugin):
+ plugin = adyen_plugin(apple_pay_cert="correct_cert")
+ mocked_request.side_effect = RequestException()
+ configuration = PluginConfiguration.objects.get()
+ plugin.validate_plugin_configuration(configuration)
diff --git a/saleor/payment/gateways/adyen/tests/utils/__init__.py b/saleor/payment/gateways/adyen/tests/utils/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/payment/gateways/adyen/tests/utils/test_apple_pay.py b/saleor/payment/gateways/adyen/tests/utils/test_apple_pay.py
new file mode 100644
index 0000000000..3b6275032e
--- /dev/null
+++ b/saleor/payment/gateways/adyen/tests/utils/test_apple_pay.py
@@ -0,0 +1,131 @@
+from unittest import mock
+
+import pytest
+
+from saleor.payment import PaymentError
+from saleor.payment.gateways.adyen.utils.apple_pay import (
+ initialize_apple_pay_session,
+ validate_payment_data_for_apple_pay,
+)
+
+
+ "validation_url,merchant_identifier,domain,display_name,certificate",
+ [
+ (
+ "https://apple-pay-gateway.apple.com/paymentservices/startSession",
+ "merchant.com.identifier",
+ "saleor.com",
+ None,
+ "certifiate data",
+ ),
+ (None, "merchant.com.identifier", "saleor.com", "Saleor", "certifiate data"),
+ (
+ "https://apple-pay-gateway.apple.com/paymentservices/startSession",
+ None,
+ "saleor.com",
+ "Saleor",
+ "certifiate data",
+ ),
+ (
+ "https://apple-pay-gateway.apple.com/paymentservices/startSession",
+ "merchant.com.identifier",
+ None,
+ "Saleor",
+ "certifiate data",
+ ),
+ (
+ "https://not-whitelisted-domain.com/paymentservices/startSession",
+ "merchant.com.identifier",
+ "saleor.com",
+ "Saleor",
+ "certifiate data",
+ ),
+ (
+ "https://apple-pay-gateway.apple.com/paymentservices/startSession",
+ "merchant.com.identifier",
+ "saleor.com",
+ "Saleor",
+ None,
+ ),
+ ],
+)
+def test_validate_payment_data_for_apple_pay_raises_payment_error(
+ validation_url, merchant_identifier, domain, display_name, certificate
+):
+ with pytest.raises(PaymentError):
+ validate_payment_data_for_apple_pay(
+ validation_url, merchant_identifier, domain, display_name, certificate
+ )
+
+
+def test_validate_payment_data_for_apple_pay():
+ validation_url = "https://apple-pay-gateway.apple.com/paymentservices/startSession"
+ merchant_identifier = "merchant.com.identifier"
+ domain = "saleor.com"
+ display_name = "Saleor "
+ certificate = "certifiate data"
+
+ validate_payment_data_for_apple_pay(
+ validation_url, merchant_identifier, domain, display_name, certificate
+ )
+
+
[email protected]("saleor.payment.gateways.adyen.utils.apple_pay.NamedTemporaryFile")
[email protected]("saleor.payment.gateways.adyen.utils.apple_pay.requests.post")
+def test_initialize_payment_for_apple_pay(mocked_request, mocked_tmp_file):
+ mocked_cert_file_name = "cert-file-name"
+ mocked_file = mock.MagicMock()
+ mocked_file.__enter__.return_value = mocked_file
+ mocked_file.name = mocked_cert_file_name
+ mocked_tmp_file.return_value = mocked_file
+
+ mocked_response = mock.Mock()
+ mocked_response.ok = True
+ mocked_response.json.return_value = {
+ "epochTimestamp": 1604652056653,
+ "expiresAt": 1604655656653,
+ "merchantSessionIdentifier": "SSH5EFCB46BA25C4B14B3F37795A7F5B974_BB8E",
+ }
+ mocked_request.return_value = mocked_response
+
+ validation_url = "https://apple-pay-gateway.apple.com/paymentservices/startSession"
+ merchant_identifier = "merchant.com.identifier"
+ domain = "saleor.com"
+ display_name = "Saleor Shop"
+ certificate = "certifiate data"
+
+ initialize_apple_pay_session(
+ validation_url, merchant_identifier, domain, display_name, certificate,
+ )
+
+ expected_data = {
+ "merchantIdentifier": merchant_identifier,
+ "displayName": display_name,
+ "initiative": "web",
+ "initiativeContext": domain,
+ }
+
+ mocked_request.assert_called_with(
+ validation_url, json=expected_data, cert=mocked_cert_file_name
+ )
+
+
[email protected]("saleor.payment.gateways.adyen.utils.apple_pay.requests.post")
+def test_initialize_payment_for_apple_pay_request_failed(mocked_request):
+
+ mocked_response = mock.Mock()
+ mocked_response.ok = False
+ mocked_response.json.return_value = {}
+ mocked_request.return_value = mocked_response
+
+ validation_url = "https://apple-pay-gateway.apple.com/paymentservices/startSession"
+ merchant_identifier = "merchant.com.identifier"
+ domain = "saleor.com"
+ display_name = "Saleor Shop"
+ certificate = "certifiate data"
+
+ with pytest.raises(PaymentError):
+ initialize_apple_pay_session(
+ validation_url, merchant_identifier, domain, display_name, certificate,
+ )
diff --git a/saleor/payment/gateways/adyen/tests/test_utils.py b/saleor/payment/gateways/adyen/tests/utils/test_common.py
similarity index 97%
rename from saleor/payment/gateways/adyen/tests/test_utils.py
rename to saleor/payment/gateways/adyen/tests/utils/test_common.py
index 2766fb2ca9..16c0ba4593 100644
--- a/saleor/payment/gateways/adyen/tests/test_utils.py
+++ b/saleor/payment/gateways/adyen/tests/utils/test_common.py
@@ -5,10 +5,9 @@ from unittest import mock
import pytest
from prices import Money, TaxedMoney
-from .....core.prices import quantize_price
-from .... import PaymentError
-from ....interface import PaymentMethodInfo
-from ..utils import (
+from saleor.core.prices import quantize_price
+from saleor.payment import PaymentError
+from saleor.payment.gateways.adyen.utils.common import (
append_klarna_data,
from_adyen_price,
get_payment_method_info,
@@ -18,6 +17,7 @@ from ..utils import (
to_adyen_price,
update_payment_with_action_required_data,
)
+from saleor.payment.interface import PaymentMethodInfo
@pytest.mark.parametrize(
@@ -77,7 +77,7 @@ def test_append_klarna_data(
}
[email protected]("saleor.payment.gateways.adyen.utils.checkout_line_total")
[email protected]("saleor.payment.gateways.adyen.utils.common.checkout_line_total")
def test_append_klarna_data_tax_included(
mocked_checkout_line_total,
dummy_payment_data,
@@ -272,7 +272,7 @@ def test_request_data_for_payment_channel_different_than_web(dummy_payment_data)
}
[email protected]("saleor.payment.gateways.adyen.utils.append_klarna_data")
[email protected]("saleor.payment.gateways.adyen.utils.common.append_klarna_data")
def test_request_data_for_payment_append_klarna_data(
append_klarna_data_mock, dummy_payment_data
):
diff --git a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py b/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py
index 4ef9266013..afb2e35010 100644
--- a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py
+++ b/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py
@@ -8,7 +8,7 @@ import pytest
from ......checkout import calculations
from ......order import OrderEvents, OrderStatus
from ..... import ChargeStatus, TransactionKind
-from ...utils import to_adyen_price
+from ...utils.common import to_adyen_price
from ...webhooks import (
create_new_transaction,
handle_authorization,
diff --git a/saleor/payment/gateways/adyen/utils/__init__.py b/saleor/payment/gateways/adyen/utils/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/payment/gateways/adyen/utils/apple_pay.py b/saleor/payment/gateways/adyen/utils/apple_pay.py
new file mode 100644
index 0000000000..6ff74bd779
--- /dev/null
+++ b/saleor/payment/gateways/adyen/utils/apple_pay.py
@@ -0,0 +1,125 @@
+import logging
+from tempfile import NamedTemporaryFile
+from typing import Optional
+from urllib.parse import urlsplit
+
+import requests
+
+from .... import PaymentError
+
+# https://developer.apple.com/documentation/apple_pay_on_the_web/
+# setting_up_your_server#3172427
+
+APPLE_DOMAINS = [
+ "apple-pay-gateway.apple.com",
+ "cn-apple-pay-gateway.apple.com",
+ "apple-pay-gateway-nc-pod1.apple.com",
+ "apple-pay-gateway-nc-pod2.apple.com",
+ "apple-pay-gateway-nc-pod3.apple.com",
+ "apple-pay-gateway-nc-pod4.apple.com",
+ "apple-pay-gateway-nc-pod5.apple.com",
+ "apple-pay-gateway-pr-pod1.apple.com",
+ "apple-pay-gateway-pr-pod2.apple.com",
+ "apple-pay-gateway-pr-pod3.apple.com",
+ "apple-pay-gateway-pr-pod4.apple.com",
+ "apple-pay-gateway-pr-pod5.apple.com",
+ "cn-apple-pay-gateway-sh-pod1.apple.com",
+ "cn-apple-pay-gateway-sh-pod2.apple.com",
+ "cn-apple-pay-gateway-sh-pod3.apple.com",
+ "cn-apple-pay-gateway-tj-pod1.apple.com",
+ "cn-apple-pay-gateway-tj-pod2.apple.com",
+ "cn-apple-pay-gateway-tj-pod3.apple.com",
+ "apple-pay-gateway-cert.apple.com",
+ "cn-apple-pay-gateway-cert.apple.com",
+]
+
+logger = logging.getLogger(__name__)
+
+
+def validate_payment_data_for_apple_pay(
+ validation_url: Optional[str],
+ merchant_identifier: Optional[str],
+ domain: Optional[str],
+ display_name: Optional[str],
+ certificate,
+):
+ if not certificate:
+ raise PaymentError("Support for Apple Pay on the web is disabled.")
+
+ required_fields = [
+ (validation_url, "validationUrl"),
+ (merchant_identifier, "merchantIdentifier"),
+ (domain, "domain"),
+ (display_name, "displayName"),
+ ]
+ for field, name in required_fields:
+ if not field:
+ raise PaymentError(f"Missing {name} in the input data.")
+
+ domain = urlsplit(validation_url).netloc
+ if domain not in APPLE_DOMAINS:
+ raise PaymentError(
+ "The domain of the validation url is not defined as an Apple Pay domain."
+ )
+
+
+def initialize_apple_pay_session(
+ validation_url: str,
+ merchant_identifier: str,
+ domain: str,
+ display_name: str,
+ certificate: str,
+) -> dict:
+
+ request_data = {
+ "merchantIdentifier": merchant_identifier,
+ "displayName": display_name,
+ "initiative": "web",
+ "initiativeContext": domain,
+ }
+ request_exception = False
+ response = None
+ try:
+ response = make_request_to_initialize_apple_pay(
+ validation_url, request_data, certificate
+ )
+ except requests.exceptions.RequestException:
+ logger.warning("Failed to fetch the Apple Pay session", exc_info=True)
+ request_exception = True
+ if request_exception or response and not response.ok:
+ raise PaymentError(
+ "Unable to create Apple Pay payment session. Make sure that input data "
+ " and certificate are correct."
+ )
+ return response.json() # type: ignore
+
+
+def make_request_to_initialize_apple_pay(
+ validation_url: str, request_data: dict, certificate: str
+):
+ with NamedTemporaryFile() as f:
+ f.write(certificate.encode())
+ f.flush() # ensure all data written
+ return requests.post(validation_url, json=request_data, cert=f.name)
+
+
+def initialize_apple_pay(payment_data: dict, certificate: str) -> dict:
+ # The apple pay on the web requires additional step
+ validation_url = payment_data.get("validationUrl", "")
+ merchant_identifier = payment_data.get("merchantIdentifier", "")
+ domain = payment_data.get("domain", "")
+ display_name = payment_data.get("displayName", "")
+ validate_payment_data_for_apple_pay(
+ validation_url=validation_url,
+ merchant_identifier=merchant_identifier,
+ domain=domain,
+ display_name=display_name,
+ certificate=certificate,
+ )
+ return initialize_apple_pay_session(
+ validation_url=validation_url,
+ merchant_identifier=merchant_identifier,
+ domain=domain,
+ display_name=display_name,
+ certificate=certificate,
+ )
diff --git a/saleor/payment/gateways/adyen/utils.py b/saleor/payment/gateways/adyen/utils/common.py
similarity index 97%
rename from saleor/payment/gateways/adyen/utils.py
rename to saleor/payment/gateways/adyen/utils/common.py
index 599d6aebc1..c0132e34ee 100644
--- a/saleor/payment/gateways/adyen/utils.py
+++ b/saleor/payment/gateways/adyen/utils/common.py
@@ -8,17 +8,17 @@ from babel.numbers import get_currency_precision
from django.conf import settings
from django_countries.fields import Country
-from ....checkout.calculations import (
+from .....checkout.calculations import (
checkout_line_total,
checkout_shipping_price,
checkout_total,
)
-from ....checkout.models import Checkout
-from ....core.prices import quantize_price
-from ....discount.utils import fetch_active_discounts
-from ....payment.models import Payment
-from ... import PaymentError
-from ...interface import PaymentData, PaymentMethodInfo
+from .....checkout.models import Checkout
+from .....core.prices import quantize_price
+from .....discount.utils import fetch_active_discounts
+from .....payment.models import Payment
+from .... import PaymentError
+from ....interface import PaymentData, PaymentMethodInfo
logger = logging.getLogger(__name__)
diff --git a/saleor/payment/gateways/adyen/webhooks.py b/saleor/payment/gateways/adyen/webhooks.py
index 0732cfbe4c..a167aa10cc 100644
--- a/saleor/payment/gateways/adyen/webhooks.py
+++ b/saleor/payment/gateways/adyen/webhooks.py
@@ -41,7 +41,7 @@ from ... import ChargeStatus, PaymentError, TransactionKind
from ...gateway import payment_refund_or_void
from ...interface import GatewayConfig, GatewayResponse
from ...utils import create_payment_information, create_transaction, gateway_postprocess
-from .utils import FAILED_STATUSES, api_call, from_adyen_price
+from .utils.common import FAILED_STATUSES, api_call, from_adyen_price
logger = logging.getLogger(__name__)
diff --git a/saleor/payment/interface.py b/saleor/payment/interface.py
index db4709e114..b594ddffd2 100644
--- a/saleor/payment/interface.py
+++ b/saleor/payment/interface.py
@@ -123,3 +123,10 @@ class PaymentGateway:
name: str
currencies: List[str]
config: List[Dict[str, Any]]
+
+
+@dataclass
+class InitializedPaymentResponse:
+ gateway: str
+ name: str
+ data: Optional[JSONType] = None
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index 8949294247..0136cf66c5 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -10,6 +10,7 @@ from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
from ..payment.interface import (
CustomerSource,
GatewayResponse,
+ InitializedPaymentResponse,
PaymentData,
PaymentGateway,
)
@@ -33,12 +34,14 @@ class ConfigurationTypeField:
STRING = "String"
BOOLEAN = "Boolean"
SECRET = "Secret"
+ SECRET_MULTILINE = "SecretMultiline"
PASSWORD = "Password"
CHOICES = [
(STRING, "Field is a String"),
(BOOLEAN, "Field is a Boolean"),
(SECRET, "Field is a Secret"),
(PASSWORD, "Field is a Password"),
+ (SECRET_MULTILINE, "Field is a Secret multiline"),
]
@@ -368,6 +371,11 @@ class BasePlugin:
"""Triggered when ShopFetchTaxRates mutation is called."""
return NotImplemented
+ def initialize_payment(
+ self, payment_data: dict, previous_value
+ ) -> "InitializedPaymentResponse":
+ return NotImplemented
+
def authorize_payment(
self, payment_information: "PaymentData", previous_value
) -> "GatewayResponse":
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 4b72a726fc..27712f7679 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -27,6 +27,7 @@ if TYPE_CHECKING:
GatewayResponse,
PaymentData,
PaymentGateway,
+ InitializedPaymentResponse,
TokenConfig,
)
from ..product.models import Product, ProductType
@@ -314,6 +315,19 @@ class PluginsManager(PaymentInterface):
default_value = None
return self.__run_method_on_plugins("checkout_updated", default_value, checkout)
+ def initialize_payment(
+ self, gateway, payment_data: dict
+ ) -> Optional["InitializedPaymentResponse"]:
+ method_name = "initialize_payment"
+ default_value = None
+ gtw = self.get_plugin(gateway)
+ if not gtw:
+ return None
+
+ return self.__run_method_on_single_plugin(
+ gtw, method_name, previous_value=default_value, payment_data=payment_data,
+ )
+
def authorize_payment(
self, gateway: str, payment_information: "PaymentData"
) -> "GatewayResponse":
diff --git a/saleor/plugins/tests/sample_plugins.py b/saleor/plugins/tests/sample_plugins.py
index 4d432ed705..8235565534 100644
--- a/saleor/plugins/tests/sample_plugins.py
+++ b/saleor/plugins/tests/sample_plugins.py
@@ -47,6 +47,11 @@ class PluginSample(BasePlugin):
"help_text": "API key",
"label": "Private key",
},
+ "certificate": {
+ "type": ConfigurationTypeField.SECRET_MULTILINE,
+ "help_text": "",
+ "label": "Multiline certificate",
+ },
}
def webhook(self, request: WSGIRequest, path: str, previous_value) -> HttpResponse: