Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Stripe - return stored payment method based on channel slug (#7757)
Maciej Korycinski06a1877543ba
diff --git a/saleor/payment/gateways/stripe/plugin.py b/saleor/payment/gateways/stripe/plugin.pyindex 63344b0d2f..7538b185f0 100644--- a/saleor/payment/gateways/stripe/plugin.py+++ b/saleor/payment/gateways/stripe/plugin.py@@ -1,12 +1,11 @@import logging-from typing import TYPE_CHECKING, List, Optional, Tuple+from typing import TYPE_CHECKING, List, Tuplefrom django.contrib.sites.models import Sitefrom django.core.exceptions import ValidationErrorfrom django.core.handlers.wsgi import WSGIRequestfrom django.http import HttpResponse, HttpResponseNotFoundfrom django.http.request import split_domain_port-from stripe.stripe_object import StripeObjectfrom ....graphql.core.enums import PluginErrorCodefrom ....plugins.base_plugin import BasePlugin, ConfigurationTypeField@@ -122,7 +121,7 @@ class StripeGatewayPlugin(BasePlugin):def webhook(self, request: WSGIRequest, path: str, previous_value) -> HttpResponse:config = self.configif path.startswith(WEBHOOK_PATH, 1): # 1 as we don't check the '/'- return handle_webhook(request, config)+ return handle_webhook(request, config, self.channel.slug) # type: ignorelogger.warning("Received request to incorrect stripe path", extra={"path": path})@@ -417,19 +416,21 @@ class StripeGatewayPlugin(BasePlugin):customer_id=customer_id,)if payment_methods:+ channel_slug: str = self.channel.slug # type: ignorecustomer_sources = [CustomerSource(- id=c.id,+ id=payment_method.id,gateway=PLUGIN_ID,credit_card_info=PaymentMethodInfo(- exp_year=c.card.exp_year,- exp_month=c.card.exp_month,- last_4=c.card.last4,+ exp_year=payment_method.card.exp_year,+ exp_month=payment_method.card.exp_month,+ last_4=payment_method.card.last4,name=None,- brand=c.card.brand,+ brand=payment_method.card.brand,),)- for c in payment_methods+ for payment_method in payment_methods+ if payment_method.metadata.get("channel") == channel_slug]previous_value.extend(customer_sources)return previous_valuediff --git a/saleor/payment/gateways/stripe/stripe_api.py b/saleor/payment/gateways/stripe/stripe_api.pyindex b0b5a83d55..0f2390446d 100644--- a/saleor/payment/gateways/stripe/stripe_api.py+++ b/saleor/payment/gateways/stripe/stripe_api.py@@ -178,6 +178,19 @@ def create_payment_intent(return None, error+def update_payment_method(api_key: str, payment_method_id: str, channel_slug: str):+ with stripe_opentracing_trace("stripe.PaymentMethod.modify"):+ try:+ stripe.PaymentMethod.modify(+ payment_method_id, api_key=api_key, metadata={"channel": channel_slug}+ )+ except StripeError as error:+ logger.warning(+ "Failed to assign channel slug to payment method",+ extra=_extra_log_data(error),+ )++def list_customer_payment_methods(api_key: str, customer_id: str) -> Tuple[Optional[StripeObject], Optional[StripeError]]:diff --git a/saleor/payment/gateways/stripe/tests/test_webhooks.py b/saleor/payment/gateways/stripe/tests/test_webhooks.pyindex 1e2acc0948..7c5d9e8881 100644--- a/saleor/payment/gateways/stripe/tests/test_webhooks.py+++ b/saleor/payment/gateways/stripe/tests/test_webhooks.py@@ -36,6 +36,7 @@ def test_handle_successful_payment_intent_for_checkout(payment_stripe_for_checkout,checkout_with_items,stripe_plugin,+ channel_USD,):payment = payment_stripe_for_checkoutpayment.to_confirm = True@@ -54,9 +55,11 @@ def test_handle_successful_payment_intent_for_checkout(payment_intent["amount_received"] = price_to_minor_unit(payment.total, payment.currency)+ payment_intent["setup_future_usage"] = Nonepayment_intent["currency"] = payment.currencypayment_intent["status"] = SUCCESS_STATUS- handle_successful_payment_intent(payment_intent, plugin.config)++ handle_successful_payment_intent(payment_intent, plugin.config, channel_USD.slug)payment.refresh_from_db()@@ -68,13 +71,54 @@ def test_handle_successful_payment_intent_for_checkout(assert transaction.token == payment_intent.id+@patch("saleor.payment.gateways.stripe.stripe_api.stripe.PaymentMethod.modify")@patch("saleor.payment.gateways.stripe.webhooks.complete_checkout", wraps=complete_checkout)-def test_handle_successful_payment_intent_for_order(- wrapped_checkout_complete,- payment_stripe_for_order,+def test_handle_successful_payment_intent_with_future_usage(+ _wrapped_checkout_complete,+ mocked_payment_method_modify,+ payment_stripe_for_checkout,+ checkout_with_items,stripe_plugin,+ channel_USD,+):+ payment = payment_stripe_for_checkout+ payment.to_confirm = True+ payment.save()+ payment.transactions.create(+ is_success=True,+ action_required=True,+ kind=TransactionKind.ACTION_TO_CONFIRM,+ amount=payment.total,+ currency=payment.currency,+ token="ABC",+ gateway_response={},+ )+ plugin = stripe_plugin()+ payment_intent = StripeObject(id="ABC", last_response={})+ payment_intent["amount_received"] = price_to_minor_unit(+ payment.total, payment.currency+ )+ payment_intent["payment_method"] = "payment_method_id"+ payment_intent["setup_future_usage"] = "off_line"+ payment_intent["currency"] = payment.currency+ payment_intent["status"] = SUCCESS_STATUS++ handle_successful_payment_intent(payment_intent, plugin.config, channel_USD.slug)++ mocked_payment_method_modify.assert_called_once_with(+ "payment_method_id",+ api_key="secret_key",+ metadata={"channel": channel_USD.slug},+ )+++@patch(+ "saleor.payment.gateways.stripe.webhooks.complete_checkout", wraps=complete_checkout+)+def test_handle_successful_payment_intent_for_order(+ wrapped_checkout_complete, payment_stripe_for_order, stripe_plugin, channel_USD):payment = payment_stripe_for_order@@ -83,7 +127,7 @@ def test_handle_successful_payment_intent_for_order(payment_intent["amount"] = payment.totalpayment_intent["currency"] = payment.currencypayment_intent["capture_method"] = "automatic"- handle_successful_payment_intent(payment_intent, plugin.config)+ handle_successful_payment_intent(payment_intent, plugin.config, channel_USD.slug)assert wrapped_checkout_complete.called is False@@ -92,9 +136,7 @@ def test_handle_successful_payment_intent_for_order("saleor.payment.gateways.stripe.webhooks.complete_checkout", wraps=complete_checkout)def test_handle_successful_payment_intent_for_order_with_auth_payment(- wrapped_checkout_complete,- payment_stripe_for_order,- stripe_plugin,+ wrapped_checkout_complete, payment_stripe_for_order, stripe_plugin, channel_USD):payment = payment_stripe_for_order@@ -105,9 +147,10 @@ def test_handle_successful_payment_intent_for_order_with_auth_payment(payment.total, payment.currency)payment_intent["currency"] = payment.currency+ payment_intent["setup_future_usage"] = Nonepayment_intent["status"] = SUCCESS_STATUS- handle_successful_payment_intent(payment_intent, plugin.config)+ handle_successful_payment_intent(payment_intent, plugin.config, channel_USD.slug)payment.refresh_from_db()@@ -122,9 +165,7 @@ def test_handle_successful_payment_intent_for_order_with_auth_payment("saleor.payment.gateways.stripe.webhooks.complete_checkout", wraps=complete_checkout)def test_handle_successful_payment_intent_for_order_with_pending_payment(- wrapped_checkout_complete,- payment_stripe_for_order,- stripe_plugin,+ wrapped_checkout_complete, payment_stripe_for_order, stripe_plugin, channel_USD):payment = payment_stripe_for_ordertransaction = payment.transactions.first()@@ -138,9 +179,10 @@ def test_handle_successful_payment_intent_for_order_with_pending_payment(payment.total, payment.currency)payment_intent["currency"] = payment.currency+ payment_intent["setup_future_usage"] = Nonepayment_intent["status"] = SUCCESS_STATUS- handle_successful_payment_intent(payment_intent, plugin.config)+ handle_successful_payment_intent(payment_intent, plugin.config, channel_USD.slug)payment.refresh_from_db()@@ -159,6 +201,7 @@ def test_handle_authorized_payment_intent_for_checkout(payment_stripe_for_checkout,checkout_with_items,stripe_plugin,+ channel_USD,):payment = payment_stripe_for_checkoutpayment.to_confirm = True@@ -177,7 +220,7 @@ def test_handle_authorized_payment_intent_for_checkout(payment_intent["amount"] = price_to_minor_unit(payment.total, payment.currency)payment_intent["currency"] = payment.currencypayment_intent["status"] = AUTHORIZED_STATUS- handle_authorized_payment_intent(payment_intent, plugin.config)+ handle_authorized_payment_intent(payment_intent, plugin.config, channel_USD.slug)payment.refresh_from_db()@@ -197,6 +240,7 @@ def test_handle_authorized_payment_intent_for_order(payment_stripe_for_order,checkout_with_items,stripe_plugin,+ channel_USD,):payment = payment_stripe_for_order@@ -205,7 +249,7 @@ def test_handle_authorized_payment_intent_for_order(payment_intent["amount"] = payment.totalpayment_intent["currency"] = payment.currencypayment_intent["status"] = AUTHORIZED_STATUS- handle_authorized_payment_intent(payment_intent, plugin.config)+ handle_authorized_payment_intent(payment_intent, plugin.config, channel_USD.slug)assert wrapped_checkout_complete.called is False@@ -218,6 +262,7 @@ def test_handle_authorized_payment_intent_for_processing_order_payment(payment_stripe_for_order,checkout_with_items,stripe_plugin,+ channel_USD,):payment = payment_stripe_for_order@@ -227,7 +272,7 @@ def test_handle_authorized_payment_intent_for_processing_order_payment(payment_intent["amount"] = payment.totalpayment_intent["currency"] = payment.currencypayment_intent["status"] = AUTHORIZED_STATUS- handle_authorized_payment_intent(payment_intent, plugin.config)+ handle_authorized_payment_intent(payment_intent, plugin.config, channel_USD.slug)assert wrapped_checkout_complete.called is False@@ -240,6 +285,7 @@ def test_handle_processing_payment_intent_for_order(payment_stripe_for_order,checkout_with_items,stripe_plugin,+ channel_USD,):payment = payment_stripe_for_order@@ -248,7 +294,7 @@ def test_handle_processing_payment_intent_for_order(payment_intent["amount"] = payment.totalpayment_intent["currency"] = payment.currencypayment_intent["status"] = PROCESSING_STATUS- handle_processing_payment_intent(payment_intent, plugin.config)+ handle_processing_payment_intent(payment_intent, plugin.config, channel_USD.slug)assert wrapped_checkout_complete.called is False@@ -261,6 +307,7 @@ def test_handle_processing_payment_intent_for_checkout(payment_stripe_for_checkout,checkout_with_items,stripe_plugin,+ channel_USD,):payment = payment_stripe_for_checkoutpayment.to_confirm = True@@ -279,7 +326,7 @@ def test_handle_processing_payment_intent_for_checkout(payment_intent["amount"] = price_to_minor_unit(payment.total, payment.currency)payment_intent["currency"] = payment.currencypayment_intent["status"] = PROCESSING_STATUS- handle_processing_payment_intent(payment_intent, plugin.config)+ handle_processing_payment_intent(payment_intent, plugin.config, channel_USD.slug)payment.refresh_from_db()@@ -292,7 +339,7 @@ def test_handle_processing_payment_intent_for_checkout(def test_handle_failed_payment_intent_for_checkout(- stripe_plugin, payment_stripe_for_checkout+ stripe_plugin, payment_stripe_for_checkout, channel_USD):payment = payment_stripe_for_checkoutpayment.transactions.create(@@ -312,7 +359,7 @@ def test_handle_failed_payment_intent_for_checkout(payment_intent["currency"] = payment.currencypayment_intent["status"] = FAILED_STATUSES[0]- handle_failed_payment_intent(payment_intent, plugin.config)+ handle_failed_payment_intent(payment_intent, plugin.config, channel_USD.slug)payment.refresh_from_db()@@ -323,7 +370,7 @@ def test_handle_failed_payment_intent_for_checkout(def test_handle_failed_payment_intent_for_order(- stripe_plugin, payment_stripe_for_order+ stripe_plugin, payment_stripe_for_order, channel_USD):payment = payment_stripe_for_orderpayment.transactions.create(@@ -343,7 +390,7 @@ def test_handle_failed_payment_intent_for_order(payment_intent["currency"] = payment.currencypayment_intent["status"] = FAILED_STATUSES[0]- handle_failed_payment_intent(payment_intent, plugin.config)+ handle_failed_payment_intent(payment_intent, plugin.config, channel_USD.slug)payment.refresh_from_db()@@ -352,7 +399,7 @@ def test_handle_failed_payment_intent_for_order(assert payment.transactions.filter(kind=TransactionKind.CANCEL).exists()-def test_handle_fully_refund(stripe_plugin, payment_stripe_for_order):+def test_handle_fully_refund(stripe_plugin, payment_stripe_for_order, channel_USD):payment = payment_stripe_for_orderpayment.captured_amount = payment.totalpayment.save()@@ -377,7 +424,7 @@ def test_handle_fully_refund(stripe_plugin, payment_stripe_for_order):charge["refunds"] = StripeObject()charge["refunds"]["data"] = [refund]- handle_refund(charge, plugin.config)+ handle_refund(charge, plugin.config, channel_USD.slug)payment.refresh_from_db()@@ -386,7 +433,7 @@ def test_handle_fully_refund(stripe_plugin, payment_stripe_for_order):assert payment.captured_amount == Decimal("0")-def test_handle_partial_refund(stripe_plugin, payment_stripe_for_order):+def test_handle_partial_refund(stripe_plugin, payment_stripe_for_order, channel_USD):payment = payment_stripe_for_orderpayment.captured_amount = payment.totalpayment.save()@@ -411,7 +458,7 @@ def test_handle_partial_refund(stripe_plugin, payment_stripe_for_order):charge["refunds"] = StripeObject()charge["refunds"]["data"] = [refund]- handle_refund(charge, plugin.config)+ handle_refund(charge, plugin.config, channel_USD.slug)payment.refresh_from_db()@@ -420,7 +467,9 @@ def test_handle_partial_refund(stripe_plugin, payment_stripe_for_order):assert payment.captured_amount == payment.total - Decimal("10")-def test_handle_refund_already_processed(stripe_plugin, payment_stripe_for_order):+def test_handle_refund_already_processed(+ stripe_plugin, payment_stripe_for_order, channel_USD+):payment = payment_stripe_for_orderpayment.charge_status = ChargeStatus.PARTIALLY_REFUNDEDpayment.captured_amount = payment.total - Decimal("10")@@ -448,7 +497,7 @@ def test_handle_refund_already_processed(stripe_plugin, payment_stripe_for_ordercharge["refunds"] = StripeObject()charge["refunds"]["data"] = [refund]- handle_refund(charge, plugin.config)+ handle_refund(charge, plugin.config, channel_USD.slug)payment.refresh_from_db()@@ -469,7 +518,7 @@ def test_handle_refund_already_processed(stripe_plugin, payment_stripe_for_order)@patch("saleor.payment.gateways.stripe.stripe_api.stripe.Webhook.construct_event")def test_handle_webhook_events(- mocked_webhook_event, webhook_type, fun_to_mock, stripe_plugin, rf+ mocked_webhook_event, webhook_type, fun_to_mock, stripe_plugin, rf, channel_USD):dummy_payload = {"id": "evt_1Ip9ANH1Vac4G4dbE9ch7zGS",@@ -492,7 +541,9 @@ def test_handle_webhook_events(with patch(f"saleor.payment.gateways.stripe.webhooks.{fun_to_mock}") as mocked_fun:plugin.webhook(request, "/webhooks/", None)- mocked_fun.assert_called_once_with(event.data.object, plugin.config)+ mocked_fun.assert_called_once_with(+ event.data.object, plugin.config, channel_USD.slug+ )api_key = plugin.config.connection_params["secret_api_key"]endpoint_secret = plugin.config.connection_params["webhook_secret"]diff --git a/saleor/payment/gateways/stripe/webhooks.py b/saleor/payment/gateways/stripe/webhooks.pyindex c5b05d5e81..81610da814 100644--- a/saleor/payment/gateways/stripe/webhooks.py+++ b/saleor/payment/gateways/stripe/webhooks.py@@ -31,13 +31,19 @@ from .consts import (WEBHOOK_REFUND_EVENT,WEBHOOK_SUCCESS_EVENT,)-from .stripe_api import construct_stripe_event, get_payment_method_details+from .stripe_api import (+ construct_stripe_event,+ get_payment_method_details,+ update_payment_method,+)logger = logging.getLogger(__name__)@transaction_with_commit_on_errors()-def handle_webhook(request: WSGIRequest, gateway_config: "GatewayConfig"):+def handle_webhook(+ request: WSGIRequest, gateway_config: "GatewayConfig", channel_slug: str+):payload = request.bodysig_header = request.META["HTTP_STRIPE_SIGNATURE"]endpoint_secret = gateway_config.connection_params["webhook_secret"]@@ -73,7 +79,7 @@ def handle_webhook(request: WSGIRequest, gateway_config: "GatewayConfig"):"Processing new Stripe webhook",extra={"event_type": event.type, "event_id": event.id},)- webhook_handlers[event.type](event.data.object, gateway_config)+ webhook_handlers[event.type](event.data.object, gateway_config, channel_slug)else:logger.warning("Received unhandled webhook events", extra={"event_type": event.type}@@ -187,7 +193,7 @@ def _process_payment_with_checkout(def handle_authorized_payment_intent(- payment_intent: StripeObject, gateway_config: "GatewayConfig"+ payment_intent: StripeObject, gateway_config: "GatewayConfig", _channel_slug: str):payment = _get_payment(payment_intent.id)@@ -220,7 +226,7 @@ def handle_authorized_payment_intent(def handle_failed_payment_intent(- payment_intent: StripeObject, gateway_config: "GatewayConfig"+ payment_intent: StripeObject, gateway_config: "GatewayConfig", _channel_slug: str):payment = _get_payment(payment_intent.id)@@ -242,7 +248,7 @@ def handle_failed_payment_intent(def handle_processing_payment_intent(- payment_intent: StripeObject, gateway_config: "GatewayConfig"+ payment_intent: StripeObject, gateway_config: "GatewayConfig", _channel_slug: str):payment = _get_payment(payment_intent.id)@@ -267,7 +273,7 @@ def handle_processing_payment_intent(def handle_successful_payment_intent(- payment_intent: StripeObject, gateway_config: "GatewayConfig"+ payment_intent: StripeObject, gateway_config: "GatewayConfig", channel_slug: str):payment = _get_payment(payment_intent.id)@@ -278,6 +284,11 @@ def handle_successful_payment_intent()return+ api_key = gateway_config.connection_params["secret_api_key"]++ if payment_intent.setup_future_usage:+ update_payment_method(api_key, payment_intent.payment_method, channel_slug)+payment_method_info = get_payment_method_details(payment_intent)if payment_method_info:changed_fields: List[str] = []@@ -314,7 +325,9 @@ def handle_successful_payment_intent()-def handle_refund(charge: StripeObject, gateway_config: "GatewayConfig"):+def handle_refund(+ charge: StripeObject, gateway_config: "GatewayConfig", _channel_slug: str+):payment_intent_id = charge.payment_intentpayment = _get_payment(payment_intent_id)