Skip to content

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

Add metadata to payment_method in webhook handlers

Mateusz Grzyb0d858f9356f0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 79c800ac1c..b023590041 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,10 +6,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Extend app by `AppExtension` - #7701 by @korycins
- Deprecate interface field `PaymentData.reuse_source` - #7988 by @mateuszgrzyb
- Add ExternalNotificationTrigger mutation - #7821 by @mstrumeck
-
-
- Add Click&Collect feature - #7673 by @kuchichan
-
- Deprecate `setup_future_usage` from `checkoutComplete.paymentData` input - will be removed in Saleor 4.0 - #7994 by @mateuszgrzyb
# 3.0.0 [Unreleased]
diff --git a/saleor/payment/gateways/stripe/consts.py b/saleor/payment/gateways/stripe/consts.py
index 724fef1816..f7cadf5ef1 100644
--- a/saleor/payment/gateways/stripe/consts.py
+++ b/saleor/payment/gateways/stripe/consts.py
@@ -27,6 +27,7 @@ ACTION_REQUIRED_STATUSES = [
"requires_action",
]
+# todo: fix this?
FAILED_STATUSES = ["requires_payment_method" "canceled"]
SUCCESS_STATUS = "succeeded"
diff --git a/saleor/payment/gateways/stripe/deprecated/tests/test_plugin.py b/saleor/payment/gateways/stripe/deprecated/tests/test_plugin.py
new file mode 100644
index 0000000000..e04ad7bae5
--- /dev/null
+++ b/saleor/payment/gateways/stripe/deprecated/tests/test_plugin.py
@@ -0,0 +1,84 @@
+from unittest.mock import Mock, patch
+
+from saleor.payment import TransactionKind
+from saleor.payment.gateways.stripe.consts import (
+ AUTOMATIC_CAPTURE_METHOD,
+ STRIPE_API_VERSION,
+ SUCCESS_STATUS,
+)
+from saleor.payment.utils import create_payment_information, price_to_minor_unit
+
+
+@patch("saleor.payment.gateways.stripe.stripe_api.stripe.Customer.create")
+@patch("saleor.payment.gateways.stripe.stripe_api.stripe.PaymentIntent.create")
+def test_process_payment_with_customer_and_future_usage(
+ mocked_payment_intent,
+ mocked_customer_create,
+ stripe_plugin,
+ payment_stripe_for_checkout,
+ channel_USD,
+ customer_user,
+):
+ customer = Mock()
+ mocked_customer_create.return_value = customer
+
+ payment_intent = Mock()
+ mocked_payment_intent.return_value = payment_intent
+
+ client_secret = "client-secret"
+ dummy_response = {
+ "id": "evt_1Ip9ANH1Vac4G4dbE9ch7zGS",
+ }
+ payment_intent_id = "payment-intent-id"
+ payment_intent.id = payment_intent_id
+ payment_intent.client_secret = client_secret
+ payment_intent.last_response.data = dummy_response
+ payment_intent.status = SUCCESS_STATUS
+
+ plugin = stripe_plugin(auto_capture=True)
+
+ payment_stripe_for_checkout.checkout.user = customer_user
+ payment_stripe_for_checkout.checkout.email = customer_user.email
+ payment_info = create_payment_information(
+ payment_stripe_for_checkout,
+ customer_id=None,
+ store_source=True,
+ additional_data={"setup_future_usage": "off_session"},
+ )
+
+ response = plugin.process_payment(payment_info, None)
+
+ assert response.is_success is True
+ assert response.action_required is False
+ assert response.kind == TransactionKind.CAPTURE
+ assert response.amount == payment_info.amount
+ assert response.currency == payment_info.currency
+ assert response.transaction_id == payment_intent_id
+ assert response.error is None
+ assert response.raw_response == dummy_response
+ assert response.action_required_data == {
+ "client_secret": client_secret,
+ "id": payment_intent_id,
+ }
+
+ api_key = plugin.config.connection_params["secret_api_key"]
+ mocked_payment_intent.assert_called_once_with(
+ api_key=api_key,
+ amount=price_to_minor_unit(payment_info.amount, payment_info.currency),
+ currency=payment_info.currency,
+ capture_method=AUTOMATIC_CAPTURE_METHOD,
+ customer=customer,
+ setup_future_usage="off_session",
+ metadata={
+ "channel": channel_USD.slug,
+ "payment_id": payment_info.graphql_payment_id,
+ },
+ receipt_email=payment_stripe_for_checkout.checkout.email,
+ stripe_version=STRIPE_API_VERSION,
+ )
+
+ mocked_customer_create.assert_called_once_with(
+ api_key="secret_key",
+ email=customer_user.email,
+ stripe_version=STRIPE_API_VERSION,
+ )
diff --git a/saleor/payment/gateways/stripe/plugin.py b/saleor/payment/gateways/stripe/plugin.py
index d585ac95ef..a797df576e 100644
--- a/saleor/payment/gateways/stripe/plugin.py
+++ b/saleor/payment/gateways/stripe/plugin.py
@@ -1,5 +1,5 @@
import logging
-from typing import TYPE_CHECKING, List, Tuple
+from typing import TYPE_CHECKING, List, Optional, Tuple
from django.contrib.sites.models import Site
from django.core.exceptions import ValidationError
@@ -162,6 +162,16 @@ class StripeGatewayPlugin(BasePlugin):
return kind, action_required
+ def _get_setup_future_usage_from_store_payment_method(
+ self, store_payment_method: StorePaymentMethodEnum
+ ) -> Optional[str]:
+ if store_payment_method == StorePaymentMethodEnum.ON_SESSION:
+ return "on_session"
+ elif store_payment_method == StorePaymentMethodEnum.OFF_SESSION:
+ return "off_session"
+ else:
+ return None
+
@require_active_plugin
def process_payment(
self, payment_information: "PaymentData", previous_value
@@ -187,9 +197,9 @@ class StripeGatewayPlugin(BasePlugin):
payment_method_types = data.get("payment_method_types") if data else None
if not setup_future_usage:
- store = payment_information.store_payment_method
- if store != StorePaymentMethodEnum.NONE:
- setup_future_usage = store.lower()
+ setup_future_usage = self._get_setup_future_usage_from_store_payment_method(
+ payment_information.store_payment_method
+ )
customer = None
# confirm that we creates customer on stripe side only for log-in customers
@@ -303,9 +313,6 @@ class StripeGatewayPlugin(BasePlugin):
payment_intent.status
)
- if payment_intent.get("setup_future_usage"):
- payment_intent.metadata = payment_information.payment_metadata
-
if kind == TransactionKind.CAPTURE:
payment_method_info = get_payment_method_details(payment_intent)
diff --git a/saleor/payment/gateways/stripe/stripe_api.py b/saleor/payment/gateways/stripe/stripe_api.py
index 9adb65ebe9..dd89c1bb91 100644
--- a/saleor/payment/gateways/stripe/stripe_api.py
+++ b/saleor/payment/gateways/stripe/stripe_api.py
@@ -300,12 +300,14 @@ def get_payment_method_details(
exp_year = int(exp_year) if exp_year else None
exp_month = card_details.get("exp_month", "")
exp_month = int(exp_month) if exp_month else None
+ payment_method = payment_intent.get("payment_method", {})
+ metadata = payment_method.get("metadata", {})
payment_method_info = PaymentMethodInfo(
last_4=card_details.get("last4", ""),
exp_year=exp_year,
exp_month=exp_month,
brand=card_details.get("brand", ""),
type="card",
- payment_metadata=payment_intent.get("metadata", {}),
+ metadata=metadata,
)
return payment_method_info
diff --git a/saleor/payment/gateways/stripe/tests/test_plugin.py b/saleor/payment/gateways/stripe/tests/test_plugin.py
index 77f0dab1e1..24125a6e04 100644
--- a/saleor/payment/gateways/stripe/tests/test_plugin.py
+++ b/saleor/payment/gateways/stripe/tests/test_plugin.py
@@ -289,88 +289,13 @@ def test_process_payment_with_customer(
)
-@patch("saleor.payment.gateways.stripe.stripe_api.stripe.Customer.create")
-@patch("saleor.payment.gateways.stripe.stripe_api.stripe.PaymentIntent.create")
-def test_process_payment_with_customer_and_deprecated_future_usage(
- mocked_payment_intent,
- mocked_customer_create,
- stripe_plugin,
- payment_stripe_for_checkout,
- channel_USD,
- customer_user,
-):
- customer = Mock()
- mocked_customer_create.return_value = customer
-
- payment_intent = Mock()
- mocked_payment_intent.return_value = payment_intent
-
- client_secret = "client-secret"
- dummy_response = {
- "id": "evt_1Ip9ANH1Vac4G4dbE9ch7zGS",
- }
- payment_intent_id = "payment-intent-id"
- payment_intent.id = payment_intent_id
- payment_intent.client_secret = client_secret
- payment_intent.last_response.data = dummy_response
- payment_intent.status = SUCCESS_STATUS
-
- plugin = stripe_plugin(auto_capture=True)
-
- payment_stripe_for_checkout.checkout.user = customer_user
- payment_stripe_for_checkout.checkout.email = customer_user.email
- payment_info = create_payment_information(
- payment_stripe_for_checkout,
- customer_id=None,
- store_source=True,
- additional_data={"setup_future_usage": "off_session"},
- )
-
- response = plugin.process_payment(payment_info, None)
-
- assert response.is_success is True
- assert response.action_required is False
- assert response.kind == TransactionKind.CAPTURE
- assert response.amount == payment_info.amount
- assert response.currency == payment_info.currency
- assert response.transaction_id == payment_intent_id
- assert response.error is None
- assert response.raw_response == dummy_response
- assert response.action_required_data == {
- "client_secret": client_secret,
- "id": payment_intent_id,
- }
-
- api_key = plugin.config.connection_params["secret_api_key"]
- mocked_payment_intent.assert_called_once_with(
- api_key=api_key,
- amount=price_to_minor_unit(payment_info.amount, payment_info.currency),
- currency=payment_info.currency,
- capture_method=AUTOMATIC_CAPTURE_METHOD,
- customer=customer,
- setup_future_usage="off_session",
- metadata={
- "channel": channel_USD.slug,
- "payment_id": payment_info.graphql_payment_id,
- },
- receipt_email=payment_stripe_for_checkout.checkout.email,
- stripe_version=STRIPE_API_VERSION,
- )
-
- mocked_customer_create.assert_called_once_with(
- api_key="secret_key",
- email=customer_user.email,
- stripe_version=STRIPE_API_VERSION,
- )
-
-
@pytest.mark.parametrize(
"store_payment_method",
[StorePaymentMethodEnum.OFF_SESSION, StorePaymentMethodEnum.ON_SESSION],
)
@patch("saleor.payment.gateways.stripe.stripe_api.stripe.Customer.create")
@patch("saleor.payment.gateways.stripe.stripe_api.stripe.PaymentIntent.create")
-def test_process_payment_with_customer_and_new_future_usage(
+def test_process_payment_with_customer_and_future_usage(
mocked_payment_intent,
mocked_customer_create,
stripe_plugin,
@@ -446,7 +371,7 @@ def test_process_payment_with_customer_and_new_future_usage(
@patch("saleor.payment.gateways.stripe.stripe_api.stripe.Customer.create")
@patch("saleor.payment.gateways.stripe.stripe_api.stripe.PaymentIntent.create")
-def test_process_payment_with_customer_and_new_future_usage_no_store(
+def test_process_payment_with_customer_and_future_usage_no_store(
mocked_payment_intent,
mocked_customer_create,
stripe_plugin,
@@ -1048,35 +973,30 @@ def test_confirm_payment(
assert response.error is None
+# todo: fix this
@pytest.mark.parametrize(
- ["setup_future_usage", "metadata", "expected_metadata"],
- [
- (None, {"key": "value"}, {}),
- ("off_session", {"key": "value"}, {"key": "value"}),
- ],
+ "metadata",
+ [{f"key{i}": f"value{i}" for i in range(5)}, {}, None],
)
@patch("saleor.payment.gateways.stripe.stripe_api.stripe.PaymentIntent.retrieve")
def test_confirm_payment_metadata(
mocked_intent_retrieve,
stripe_plugin,
payment_stripe_for_checkout,
- setup_future_usage,
metadata,
- expected_metadata,
):
# given
payment_intent_id = "payment-intent-id"
payment = payment_stripe_for_checkout
- payment.metadata = metadata
payment_intent = StripeObject(id=payment_intent_id)
payment_intent["amount"] = price_to_minor_unit(payment.total, payment.currency)
payment_intent["status"] = SUCCESS_STATUS
payment_intent["currency"] = payment.currency
payment_intent["charges"] = {"data": [{"payment_method_details": {"type": "card"}}]}
- if setup_future_usage:
- payment_intent["setup_future_usage"] = setup_future_usage
+ if metadata is not None:
+ payment_intent["payment_method"] = {"metadata": metadata}
mocked_intent_retrieve.return_value = payment_intent
payment_info = create_payment_information(payment, payment_token=payment_intent_id)
@@ -1086,7 +1006,7 @@ def test_confirm_payment_metadata(
response = plugin.confirm_payment(payment_info, None)
# then
- assert response.payment_method_info.payment_metadata == expected_metadata
+ assert response.payment_method_info.metadata == (metadata or {})
@patch("saleor.payment.gateways.stripe.stripe_api.stripe.PaymentIntent.retrieve")
diff --git a/saleor/payment/gateways/stripe/tests/test_stripe_api.py b/saleor/payment/gateways/stripe/tests/test_stripe_api.py
index 969773a1ea..c88a2c56a8 100644
--- a/saleor/payment/gateways/stripe/tests/test_stripe_api.py
+++ b/saleor/payment/gateways/stripe/tests/test_stripe_api.py
@@ -491,7 +491,7 @@ def test_get_payment_method_details():
}
]
}
- payment_intent.metadata = {"key": "value"}
+ payment_intent.payment_method = {"metadata": {"key": "value"}}
payment_method_info = get_payment_method_details(payment_intent)
@@ -501,7 +501,7 @@ def test_get_payment_method_details():
exp_month=12,
brand="visa",
type="card",
- payment_metadata={"key": "value"},
+ metadata={"key": "value"},
)
diff --git a/saleor/payment/gateways/stripe/tests/test_webhooks.py b/saleor/payment/gateways/stripe/tests/test_webhooks.py
index 3bc5ead54c..2fe3f4fd7e 100644
--- a/saleor/payment/gateways/stripe/tests/test_webhooks.py
+++ b/saleor/payment/gateways/stripe/tests/test_webhooks.py
@@ -20,6 +20,7 @@ from ..consts import (
WEBHOOK_SUCCESS_EVENT,
)
from ..webhooks import (
+ _update_payment_method_metadata_from_payment_intent,
handle_authorized_payment_intent,
handle_failed_payment_intent,
handle_processing_payment_intent,
@@ -28,6 +29,44 @@ from ..webhooks import (
)
+ ["metadata", "payment_method"],
+ [
+ ({"key": "value"}, {"metadata": {"key": "value"}}),
+ ({}, {}),
+ (None, {}),
+ ],
+)
+def test_update_payment_method_metadata_from_payment_intent_with_payment_method(
+ metadata, payment_method
+) -> None:
+ # given
+ payment_intent = StripeObject(id="token", last_response={})
+ payment_intent["metadata"] = metadata
+ payment_intent["payment_method"] = {}
+
+ # when
+ _update_payment_method_metadata_from_payment_intent(payment_intent)
+
+ # then
+ assert payment_intent.payment_method == payment_method
+
+
[email protected]("metadata", [{"key": "value"}, {}, None])
+def test_update_payment_method_metadata_from_payment_intent_without_payment_method(
+ metadata,
+) -> None:
+ # given
+ payment_intent = StripeObject(id="token", last_response={})
+ payment_intent["metadata"] = metadata
+
+ # when
+ _update_payment_method_metadata_from_payment_intent(payment_intent)
+
+ # then
+ assert payment_intent.get("payment_method") is None
+
+
@patch(
"saleor.payment.gateways.stripe.webhooks.complete_checkout", wraps=complete_checkout
)
@@ -266,6 +305,7 @@ def test_handle_authorized_payment_intent_for_processing_order_payment(
assert wrapped_checkout_complete.called is False
+# todo: fix this
@pytest.mark.parametrize(
"metadata", [{f"key{i}": f"value{i}" for i in range(5)}, {}, None]
)
diff --git a/saleor/payment/gateways/stripe/webhooks.py b/saleor/payment/gateways/stripe/webhooks.py
index 7ecc14929f..88db22245b 100644
--- a/saleor/payment/gateways/stripe/webhooks.py
+++ b/saleor/payment/gateways/stripe/webhooks.py
@@ -188,6 +188,15 @@ def _process_payment_with_checkout(
_finalize_checkout(checkout, payment, payment_intent, kind, amount, currency)
+def _update_payment_method_metadata_from_payment_intent(
+ payment_intent: StripeObject,
+) -> None:
+ payment_method = payment_intent.get("payment_method")
+ metadata = payment_intent.get("metadata")
+ if payment_method is not None and metadata is not None:
+ payment_method["metadata"] = metadata
+
+
def handle_authorized_payment_intent(
payment_intent: StripeObject, gateway_config: "GatewayConfig", _channel_slug: str
):
@@ -200,9 +209,11 @@ def handle_authorized_payment_intent(
)
return
+ _update_payment_method_metadata_from_payment_intent(payment_intent)
+
payment_method_info = get_payment_method_details(payment_intent)
- if payment_method_info and payment_method_info.payment_metadata:
- payment.metadata = payment_method_info.payment_metadata
+ if payment_method_info and payment_method_info.metadata:
+ payment.metadata = payment_method_info.metadata
payment.save(update_fields=["metadata"])
if payment.order_id:
@@ -286,6 +297,8 @@ def handle_successful_payment_intent(
)
return
+ _update_payment_method_metadata_from_payment_intent(payment_intent)
+
payment_method_info = get_payment_method_details(payment_intent)
if payment_method_info:
changed_fields: List[str] = []
@@ -293,6 +306,8 @@ def handle_successful_payment_intent(
if changed_fields:
payment.save(update_fields=changed_fields)
+ raise Exception(payment.metadata)
+
if payment.order_id:
if payment.charge_status in [ChargeStatus.PENDING, ChargeStatus.NOT_CHARGED]:
capture_transaction = _update_payment_with_new_transaction(
diff --git a/saleor/payment/interface.py b/saleor/payment/interface.py
index 02f06c4043..4d083afb23 100644
--- a/saleor/payment/interface.py
+++ b/saleor/payment/interface.py
@@ -18,7 +18,7 @@ class PaymentMethodInfo:
brand: Optional[str] = None
name: Optional[str] = None
type: Optional[str] = None
- payment_metadata: Dict[str, str] = field(default_factory=dict)
+ metadata: Dict[str, str] = field(default_factory=dict)
@dataclass
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 31905a790c..f8d2cb0239 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -407,8 +407,8 @@ def update_payment_method_details(
if payment_method_info.type:
payment.payment_method_type = payment_method_info.type
changed_fields.append("payment_method_type")
- if payment_method_info.payment_metadata:
- payment.metadata = payment_method_info.payment_metadata
+ if payment_method_info.metadata:
+ payment.metadata = payment_method_info.metadata
changed_fields.append("metadata")