Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Rebuild a stripe plugin (#7452)
Maciej Korycinski6836c651fc35
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b405f9a2a0..98a38cbdfd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -217,6 +217,10 @@ All notable, unreleased changes to this project will be documented in this file.- drop `productType` from `ProductFilter`- deprecate mutations' `<name>Errors`, typed `errors` fields and remove deprecation- Add channel data to Order webhook - #7299 by @krzysztofwolski+- Deprecated Stripe plugin - will be removed in Saleor 4.0+ - rename `StripeGatewayPlugin` to `DeprecatedStripeGatewayPlugin`.+ - introduce new `StripeGatewayPlugin` plugin.+- Always create new checkout in `checkoutCreate` mutation - #7318 by @IKarbowiak- deprecate `created` return field on `checkoutCreate` mutation- Return empty values list for attribute without choices - #7394 by @fowczarekdiff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex 23605b4d26..388d815efa 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -467,7 +467,7 @@ def _prepare_checkout(checkout.redirect_url = redirect_urlto_update.append("redirect_url")- if tracking_code and tracking_code != checkout.tracking_code:+ if tracking_code and str(tracking_code) != checkout.tracking_code:checkout.tracking_code = tracking_codeto_update.append("tracking_code")@@ -589,7 +589,7 @@ def complete_checkout(raise exccustomer_id = None- if store_source and payment:+ if payment and user.is_authenticated:customer_id = fetch_customer_id(user=user, gateway=payment.gateway)txn = _process_payment(diff --git a/saleor/core/tracing.py b/saleor/core/tracing.pyindex 12304c8eb1..b3de530c5a 100644--- a/saleor/core/tracing.py+++ b/saleor/core/tracing.py@@ -26,3 +26,12 @@ def traced_atomic_transaction():span = scope.spanspan.set_tag(opentracing.tags.COMPONENT, "orm")yield+++@contextmanager+def opentracing_trace(span_name, component_name, service_name):+ with opentracing.global_tracer().start_active_span(span_name) as scope:+ span = scope.span+ span.set_tag(opentracing.tags.COMPONENT, component_name)+ span.set_tag("service.name", service_name)+ yielddiff --git a/saleor/order/actions.py b/saleor/order/actions.pyindex aa5ba7edeb..552e2a8385 100644--- a/saleor/order/actions.py+++ b/saleor/order/actions.py@@ -169,7 +169,10 @@ def order_refunded(def order_voided(- order: "Order", user: "User", payment: "Payment", manager: "PluginsManager"+ order: "Order",+ user: Optional["User"],+ payment: "Payment",+ manager: "PluginsManager",):events.payment_voided_event(order=order, user=user, payment=payment)manager.order_updated(order)diff --git a/saleor/payment/gateways/adyen/tests/utils/test_common.py b/saleor/payment/gateways/adyen/tests/utils/test_common.pyindex 5314981362..2537e3343c 100644--- a/saleor/payment/gateways/adyen/tests/utils/test_common.py+++ b/saleor/payment/gateways/adyen/tests/utils/test_common.py@@ -9,15 +9,14 @@ from saleor.core.prices import quantize_pricefrom saleor.payment import PaymentErrorfrom saleor.payment.gateways.adyen.utils.common import (append_klarna_data,- from_adyen_price,get_payment_method_info,get_shopper_locale_value,request_data_for_gateway_config,request_data_for_payment,- to_adyen_price,update_payment_with_action_required_data,)from saleor.payment.interface import PaymentMethodInfo+from saleor.payment.utils import price_from_minor_unit, price_to_minor_unitfrom ......plugins.manager import get_plugins_manager@@ -52,7 +51,8 @@ def test_append_klarna_data(variant_channel_listing = line.variant.channel_listings.get(channel_id=channel_id)variant_price = variant_channel_listing.price_amountvariant_currency = variant_channel_listing.currency- price = to_adyen_price(variant_price, variant_currency)+ price = price_to_minor_unit(variant_price, variant_currency)+assert result == {"reference": "test","shopperLocale": get_shopper_locale_value(country_code),@@ -125,10 +125,10 @@ def test_append_klarna_data_tax_included("description": f"{line.variant.product.name}, {line.variant.name}","quantity": line.quantity,"id": line.variant.sku,- "taxAmount": to_adyen_price((gross - net).amount, "USD"),+ "taxAmount": price_to_minor_unit((gross - net).amount, "USD"),"taxPercentage": 2300,- "amountExcludingTax": to_adyen_price(net.amount, "USD"),- "amountIncludingTax": to_adyen_price(gross.amount, "USD"),+ "amountExcludingTax": price_to_minor_unit(net.amount, "USD"),+ "amountIncludingTax": price_to_minor_unit(gross.amount, "USD"),},{"amountExcludingTax": "1000",@@ -190,7 +190,7 @@ def test_request_data_for_payment(dummy_payment_data):# thenassert result == {"amount": {- "value": to_adyen_price(+ "value": price_to_minor_unit(dummy_payment_data.amount, dummy_payment_data.currency),"currency": dummy_payment_data.currency,@@ -233,7 +233,7 @@ def test_request_data_for_payment_native_3d_secure(dummy_payment_data):# thenassert result == {"amount": {- "value": to_adyen_price(+ "value": price_to_minor_unit(dummy_payment_data.amount, dummy_payment_data.currency),"currency": dummy_payment_data.currency,@@ -268,7 +268,7 @@ def test_request_data_for_payment_channel_different_than_web(dummy_payment_data)# thenassert result == {"amount": {- "value": to_adyen_price(+ "value": price_to_minor_unit(dummy_payment_data.amount, dummy_payment_data.currency),"currency": dummy_payment_data.currency,@@ -303,7 +303,7 @@ def test_request_data_for_payment_append_klarna_data(dummy_payment_data.data = dataklarna_result = {"amount": {- "value": to_adyen_price(+ "value": price_to_minor_unit(dummy_payment_data.amount, dummy_payment_data.currency),"currency": dummy_payment_data.currency,@@ -339,7 +339,7 @@ def test_request_data_for_payment_append_klarna_data()def test_from_adyen_price(value, currency, expected_result):# when- result = from_adyen_price(value, currency)+ result = price_from_minor_unit(value, currency)# thenassert result == expected_result@@ -355,7 +355,7 @@ def test_from_adyen_price(value, currency, expected_result):)def test_to_adyen_price(value, currency, expected_result):# when- result = to_adyen_price(value, currency)+ result = price_to_minor_unit(value, currency)# thenassert result == expected_resultdiff --git a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py b/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.pyindex 4cebb3795d..cb466905ff 100644--- a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py+++ b/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py@@ -10,7 +10,7 @@ from ......checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom ......order import OrderEvents, OrderStatusfrom ......plugins.manager import get_plugins_managerfrom ..... import ChargeStatus, TransactionKind-from ...utils.common import to_adyen_price+from .....utils import price_to_minor_unitfrom ...webhooks import (create_new_transaction,handle_authorization,@@ -35,7 +35,7 @@ def test_handle_authorization_for_order(payment_id = graphene.Node.to_global_id("Payment", payment.pk)notification = notification(merchant_reference=payment_id,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin().confighandle_authorization(notification, config)@@ -57,7 +57,7 @@ def test_handle_authorization_for_order_invalid_payment_id(invalid_reference = "test invalid reference"notification = notification(merchant_reference=invalid_reference,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin().configtransaction_count = payment.transactions.count()@@ -82,7 +82,7 @@ def test_handle_multiple_authorization_notification(merchant_reference=payment_id,success="false",psp_reference="wrong",- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin(adyen_auto_capture=True).confighandle_authorization(first_notification, config)@@ -98,7 +98,7 @@ def test_handle_multiple_authorization_notification(second_notification = notification(merchant_reference=payment_id,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)handle_authorization(second_notification, config)payment.refresh_from_db()@@ -123,7 +123,7 @@ def test_handle_authorization_for_pending_order(payment_id = graphene.Node.to_global_id("Payment", payment.pk)notification = notification(merchant_reference=payment_id,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin(adyen_auto_capture=True).confighandle_authorization(notification, config)@@ -171,7 +171,7 @@ def test_handle_authorization_for_checkout(payment_id = graphene.Node.to_global_id("Payment", payment.pk)notification = notification(merchant_reference=payment_id,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin().confighandle_authorization(notification, config)@@ -219,7 +219,7 @@ def test_handle_authorization_with_adyen_auto_capture(notification = notification(merchant_reference=payment_id,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)plugin = adyen_plugin(adyen_auto_capture=True)@@ -247,7 +247,7 @@ def test_handle_authorization_with_auto_capture(notification = notification(psp_reference="853596537720508F",merchant_reference=payment_id,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin(adyen_auto_capture=False, auto_capture=True).config@@ -273,7 +273,7 @@ def test_handle_authorization_with_adyen_auto_capture_and_payment_charged(payment_id = graphene.Node.to_global_id("Payment", payment.pk)notification = notification(merchant_reference=payment_id,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin().configconfig.connection_params["adyen_auto_capture"] = True@@ -299,7 +299,7 @@ def test_handle_cancel(payment_id = graphene.Node.to_global_id("Payment", payment.pk)notification = notification(merchant_reference=payment_id,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin().configmanager = get_plugins_manager()@@ -326,7 +326,7 @@ def test_handle_cancel_invalid_payment_id(invalid_reference = "test invalid reference"notification = notification(merchant_reference=invalid_reference,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin().configtransaction_count = payment.transactions.count()@@ -352,7 +352,7 @@ def test_handle_cancel_already_canceled(payment_id = graphene.Node.to_global_id("Payment", payment.pk)notification = notification(merchant_reference=payment_id,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin().configcreate_new_transaction(notification, payment, TransactionKind.CANCEL)@@ -368,7 +368,7 @@ def test_handle_capture_for_order(notification, adyen_plugin, payment_adyen_for_payment_id = graphene.Node.to_global_id("Payment", payment.pk)notification = notification(merchant_reference=payment_id,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin().confighandle_capture(notification, config)@@ -415,7 +415,7 @@ def test_handle_capture_for_checkout(payment_id = graphene.Node.to_global_id("Payment", payment.pk)notification = notification(merchant_reference=payment_id,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin().confighandle_capture(notification, config)@@ -443,7 +443,7 @@ def test_handle_capture_invalid_payment_id(invalid_reference = "test invalid reference"notification = notification(merchant_reference=invalid_reference,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin().configtransaction_count = payment.transactions.count()@@ -467,7 +467,7 @@ def test_handle_capture_with_payment_already_charged(payment_id = graphene.Node.to_global_id("Payment", payment.pk)notification = notification(merchant_reference=payment_id,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin().config@@ -495,7 +495,7 @@ def test_handle_failed_capture(payment_id = graphene.Node.to_global_id("Payment", payment.pk)notification = notification(merchant_reference=payment_id,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin().config@@ -522,7 +522,7 @@ def test_handle_failed_capture_invalid_payment_id(invalid_reference = "test invalid reference"notification = notification(merchant_reference=invalid_reference,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin().configtransaction_count = payment.transactions.count()@@ -546,7 +546,7 @@ def test_handle_failed_capture_partial_charge(payment_id = graphene.Node.to_global_id("Payment", payment.pk)notification = notification(merchant_reference=payment_id,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin().config@@ -568,7 +568,7 @@ def test_handle_pending(notification, adyen_plugin, payment_adyen_for_order):payment_id = graphene.Node.to_global_id("Payment", payment.pk)notification = notification(merchant_reference=payment_id,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin().config@@ -592,7 +592,7 @@ def test_handle_pending_invalid_payment_id(invalid_reference = "test invalid reference"notification = notification(merchant_reference=invalid_reference,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin().configtransaction_count = payment.transactions.count()@@ -613,7 +613,7 @@ def test_handle_pending_with_adyen_auto_capture(payment_id = graphene.Node.to_global_id("Payment", payment.pk)notification = notification(merchant_reference=payment_id,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin().configconfig.connection_params["adyen_auto_capture"] = True@@ -640,7 +640,7 @@ def test_handle_pending_already_pending(payment_id = graphene.Node.to_global_id("Payment", payment.pk)notification = notification(merchant_reference=payment_id,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin().configcreate_new_transaction(notification, payment, TransactionKind.PENDING)@@ -661,7 +661,7 @@ def test_handle_refund(payment_id = graphene.Node.to_global_id("Payment", payment.pk)notification = notification(merchant_reference=payment_id,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin().config@@ -693,7 +693,7 @@ def test_handle_refund_invalid_payment_id(invalid_reference = "test invalid reference"notification = notification(merchant_reference=invalid_reference,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin().configtransaction_count = payment.transactions.count()@@ -718,7 +718,7 @@ def test_handle_refund_already_refunded(payment_id = graphene.Node.to_global_id("Payment", payment.pk)notification = notification(merchant_reference=payment_id,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)create_new_transaction(notification, payment, TransactionKind.REFUND)config = adyen_plugin().config@@ -739,7 +739,7 @@ def test_handle_failed_refund_missing_transaction(payment_id = graphene.Node.to_global_id("Payment", payment.pk)notification = notification(merchant_reference=payment_id,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin().config@@ -762,7 +762,7 @@ def test_handle_failed_refund_invalid_payment_id(invalid_reference = "test invalid reference"notification = notification(merchant_reference=invalid_reference,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin().configtransaction_count = payment.transactions.count()@@ -786,7 +786,7 @@ def test_handle_failed_refund_with_transaction_refund_ongoing(payment_id = graphene.Node.to_global_id("Payment", payment.pk)notification = notification(merchant_reference=payment_id,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin().configcreate_new_transaction(notification, payment, TransactionKind.REFUND_ONGOING)@@ -812,7 +812,7 @@ def test_handle_failed_refund_with_transaction_refund(payment_id = graphene.Node.to_global_id("Payment", payment.pk)notification = notification(merchant_reference=payment_id,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin().configcreate_new_transaction(notification, payment, TransactionKind.REFUND)@@ -836,7 +836,7 @@ def test_handle_reversed_refund(notification, adyen_plugin, payment_adyen_for_orpayment_id = graphene.Node.to_global_id("Payment", payment.pk)notification = notification(merchant_reference=payment_id,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin().confighandle_reversed_refund(notification, config)@@ -861,7 +861,7 @@ def test_handle_reversed_refund_invalid_payment_id(invalid_reference = "test invalid reference"notification = notification(merchant_reference=invalid_reference,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin().configtransaction_count = payment.transactions.count()@@ -885,7 +885,7 @@ def test_handle_reversed_refund_already_processed(payment_id = graphene.Node.to_global_id("Payment", payment.pk)notification = notification(merchant_reference=payment_id,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin().configcreate_new_transaction(notification, payment, TransactionKind.REFUND_REVERSED)@@ -902,7 +902,7 @@ def test_webhook_not_implemented(notification, adyen_plugin, payment_adyen_for_opayment_id = graphene.Node.to_global_id("Payment", payment.pk)notification = notification(merchant_reference=payment_id,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin().config@@ -924,7 +924,7 @@ def test_webhook_not_implemented_invalid_payment_id(invalid_reference = "test invalid reference"notification = notification(merchant_reference=invalid_reference,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)config = adyen_plugin().configtransaction_count = payment.transactions.count()@@ -948,7 +948,7 @@ def test_handle_cancel_or_refund_action_refund(config = adyen_plugin().confignotification = notification(merchant_reference=payment_id,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)notification["additionalData"]["modification.action"] = "refund"@@ -966,7 +966,7 @@ def test_handle_cancel_or_refund_action_cancel(config = adyen_plugin().confignotification = notification(merchant_reference=payment_id,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)notification["additionalData"]["modification.action"] = "cancel"@@ -983,7 +983,7 @@ def test_handle_cancel_or_refund_action_cancel_invalid_payment_id(invalid_reference = "test invalid reference"notification = notification(merchant_reference=invalid_reference,- value=to_adyen_price(payment.total, payment.currency),+ value=price_to_minor_unit(payment.total, payment.currency),)notification["additionalData"]["modification.action"] = "cancel"diff --git a/saleor/payment/gateways/adyen/utils/common.py b/saleor/payment/gateways/adyen/utils/common.pyindex 9179e99040..8cfd7304a3 100644--- a/saleor/payment/gateways/adyen/utils/common.py+++ b/saleor/payment/gateways/adyen/utils/common.py@@ -6,7 +6,6 @@ from typing import TYPE_CHECKING, Any, Callable, Dict, Optionalimport Adyenimport opentracingimport opentracing.tags-from babel.numbers import get_currency_precisionfrom django.conf import settingsfrom django_countries.fields import Country@@ -18,12 +17,12 @@ from .....checkout.calculations import (from .....checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom .....checkout.models import Checkoutfrom .....checkout.utils import is_shipping_required-from .....core.prices import quantize_pricefrom .....discount.utils import fetch_active_discountsfrom .....payment.models import Paymentfrom .....plugins.manager import get_plugins_managerfrom .... import PaymentErrorfrom ....interface import PaymentMethodInfo+from ....utils import price_to_minor_unitif TYPE_CHECKING:from ....interface import PaymentData@@ -37,26 +36,6 @@ PENDING_STATUSES = ["pending", "received"]AUTH_STATUS = "authorised"-def from_adyen_price(value: str, currency: str):- value = Decimal(value)- precision = get_currency_precision(currency)- number_places = Decimal(10) ** -precision- return value * number_places---def to_adyen_price(value: Decimal, currency: str):- """Adyen doesn't use values with comma.-- Take the value, discover the precision of currency and multiply value by- Decimal('10.0'), then change quantization to remove the comma.- """- value = quantize_price(value, currency=currency)- precision = get_currency_precision(currency)- number_places = Decimal("10.0") ** precision- value_without_comma = value * number_places- return str(value_without_comma.quantize(Decimal("1")))--def get_tax_percentage_in_adyen_format(total_gross, total_net):tax_percentage_in_adyen_format = 0if total_gross and total_net:@@ -131,7 +110,7 @@ def request_data_for_payment(extra_request_params["shopperEmail"] = payment_information.customer_emailrequest_data = {"amount": {- "value": to_adyen_price(+ "value": price_to_minor_unit(payment_information.amount, payment_information.currency),"currency": payment_information.currency,@@ -166,12 +145,12 @@ def get_shipping_data(manager, checkout_info, lines, discounts):)return {"quantity": 1,- "amountExcludingTax": to_adyen_price(total_net, currency),+ "amountExcludingTax": price_to_minor_unit(total_net, currency),"taxPercentage": tax_percentage_in_adyen_format,"description": f"Shipping - {checkout_info.shipping_method.name}","id": f"Shipping:{checkout_info.shipping_method.id}",- "taxAmount": to_adyen_price(tax_amount, currency),- "amountIncludingTax": to_adyen_price(total_gross, currency),+ "taxAmount": price_to_minor_unit(tax_amount, currency),+ "amountIncludingTax": price_to_minor_unit(total_gross, currency),}@@ -225,14 +204,14 @@ def append_klarna_data(payment_information: "PaymentData", payment_data: dict):line_data = {"quantity": line_info.line.quantity,- "amountExcludingTax": to_adyen_price(unit_net, currency),+ "amountExcludingTax": price_to_minor_unit(unit_net, currency),"taxPercentage": tax_percentage_in_adyen_format,"description": (f"{line_info.variant.product.name}, {line_info.variant.name}"),"id": line_info.variant.sku,- "taxAmount": to_adyen_price(tax_amount, currency),- "amountIncludingTax": to_adyen_price(unit_gross, currency),+ "taxAmount": price_to_minor_unit(tax_amount, currency),+ "amountIncludingTax": price_to_minor_unit(unit_gross, currency),}line_items.append(line_data)@@ -295,7 +274,7 @@ def request_data_for_gateway_config("countryCode": country_code,"channel": channel,"amount": {- "value": to_adyen_price(total.gross.amount, checkout.currency),+ "value": price_to_minor_unit(total.gross.amount, checkout.currency),"currency": checkout.currency,},}@@ -307,7 +286,7 @@ def request_for_payment_refund(return {"merchantAccount": merchant_account,"modificationAmount": {- "value": to_adyen_price(+ "value": price_to_minor_unit(payment_information.amount, payment_information.currency),"currency": payment_information.currency,@@ -323,7 +302,7 @@ def request_for_payment_capture(return {"merchantAccount": merchant_account,"modificationAmount": {- "value": to_adyen_price(+ "value": price_to_minor_unit(payment_information.amount, payment_information.currency),"currency": payment_information.currency,diff --git a/saleor/payment/gateways/adyen/webhooks.py b/saleor/payment/gateways/adyen/webhooks.pyindex cedef66bd7..f7e95617e7 100644--- a/saleor/payment/gateways/adyen/webhooks.py+++ b/saleor/payment/gateways/adyen/webhooks.py@@ -42,8 +42,13 @@ from ....plugins.manager import get_plugins_managerfrom ... import ChargeStatus, PaymentError, TransactionKindfrom ...gateway import payment_refund_or_voidfrom ...interface import GatewayConfig, GatewayResponse-from ...utils import create_payment_information, create_transaction, gateway_postprocess-from .utils.common import FAILED_STATUSES, api_call, from_adyen_price+from ...utils import (+ create_payment_information,+ create_transaction,+ gateway_postprocess,+ price_from_minor_unit,+)+from .utils.common import FAILED_STATUSES, api_calllogger = logging.getLogger(__name__)@@ -115,7 +120,9 @@ def get_transaction(def create_new_transaction(notification, payment, kind):transaction_id = notification.get("pspReference")currency = notification.get("amount", {}).get("currency")- amount = from_adyen_price(notification.get("amount", {}).get("value"), currency)+ amount = price_from_minor_unit(+ notification.get("amount", {}).get("value"), currency+ )is_success = True if notification.get("success") == "true" else Falsegateway_response = GatewayResponse(diff --git a/saleor/payment/gateways/stripe/__init__.py b/saleor/payment/gateways/stripe/__init__.pyindex 01df5ea6a4..e69de29bb2 100644--- a/saleor/payment/gateways/stripe/__init__.py+++ b/saleor/payment/gateways/stripe/__init__.py@@ -1,289 +0,0 @@-from typing import List--import opentracing-import opentracing.tags-import stripe--from ... import TransactionKind-from ...interface import (- CustomerSource,- GatewayConfig,- GatewayResponse,- PaymentData,- PaymentMethodInfo,-)-from .utils import (- get_amount_for_stripe,- get_amount_from_stripe,- get_currency_for_stripe,- get_currency_from_stripe,- shipping_to_stripe_dict,-)---def get_client_token(**_):- """Not implemented for stripe gateway currently.-- The client token can be generated by stripe.js automatically.- """- return---def authorize(- payment_information: PaymentData, config: GatewayConfig-) -> GatewayResponse:- kind = TransactionKind.CAPTURE if config.auto_capture else TransactionKind.AUTH- client = _get_client(**config.connection_params)- capture_method = "automatic" if config.auto_capture else "manual"- currency = get_currency_for_stripe(payment_information.currency)- stripe_amount = get_amount_for_stripe(payment_information.amount, currency)- future_use = "off_session" if config.store_customer else "on_session"- customer_id = (- payment_information.customer_id if payment_information.reuse_source else None- )- shipping = (- shipping_to_stripe_dict(payment_information.shipping)- if payment_information.shipping- else None- )-- try:- with opentracing.global_tracer().start_active_span(- "stripe.PaymentIntent.create"- ) as scope:- span = scope.span- span.set_tag(opentracing.tags.COMPONENT, "payment")- span.set_tag("service.name", "stripe")- intent = client.PaymentIntent.create(- payment_method=payment_information.token,- amount=stripe_amount,- currency=currency,- confirmation_method="manual",- confirm=True,- capture_method=capture_method,- setup_future_usage=future_use,- customer=customer_id,- shipping=shipping,- )- if config.store_customer and not customer_id:- with opentracing.global_tracer().start_active_span(- "stripe.Customer.create"- ) as scope:- span = scope.span- span.set_tag(opentracing.tags.COMPONENT, "payment")- span.set_tag("service.name", "stripe")- customer = client.Customer.create(payment_method=intent.payment_method)- customer_id = customer.id-- except stripe.error.StripeError as exc:- response = _error_response(kind=kind, exc=exc, payment_info=payment_information)- else:- success = intent.status in ("succeeded", "requires_capture", "requires_action")- response = _success_response(- intent=intent, kind=kind, success=success, customer_id=customer_id- )- response = fill_card_details(intent, response)- return response---def capture(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:- client = _get_client(**config.connection_params)- intent = None- try:- with opentracing.global_tracer().start_active_span(- "stripe.PaymentIntent.retrieve"- ) as scope:- span = scope.span- span.set_tag(opentracing.tags.COMPONENT, "payment")- span.set_tag("service.name", "stripe")- intent = client.PaymentIntent.retrieve(id=payment_information.token)- capture = intent.capture()- except stripe.error.StripeError as exc:- action_required = intent.status == "requires_action" if intent else False- response = _error_response(- kind=TransactionKind.CAPTURE,- exc=exc,- payment_info=payment_information,- action_required=action_required,- )- else:- response = _success_response(- intent=intent,- kind=TransactionKind.CAPTURE,- success=capture.status in ("succeeded", "requires_action"),- )- response = fill_card_details(intent, response)- return response---def confirm(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:- client = _get_client(**config.connection_params)- try:- intent = client.PaymentIntent(id=payment_information.token)- with opentracing.global_tracer().start_active_span(- "stripe.PaymentIntent.confirm"- ) as scope:- span = scope.span- span.set_tag(opentracing.tags.COMPONENT, "payment")- span.set_tag("service.name", "stripe")- intent.confirm()- except stripe.error.StripeError as exc:- response = _error_response(- kind=TransactionKind.CONFIRM, exc=exc, payment_info=payment_information- )- else:- response = _success_response(- intent=intent,- kind=TransactionKind.CONFIRM,- success=intent.status == "succeeded",- )- response = fill_card_details(intent, response)- return response---def refund(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:- client = _get_client(**config.connection_params)- currency = get_currency_for_stripe(payment_information.currency)- stripe_amount = get_amount_for_stripe(payment_information.amount, currency)- try:- with opentracing.global_tracer().start_active_span(- "stripe.PaymentIntent.retrieve"- ) as scope:- span = scope.span- span.set_tag(opentracing.tags.COMPONENT, "payment")- span.set_tag("service.name", "stripe")- intent = client.PaymentIntent.retrieve(id=payment_information.token)- refund = intent["charges"]["data"][0].refund(amount=stripe_amount)- except stripe.error.StripeError as exc:- response = _error_response(- kind=TransactionKind.REFUND, exc=exc, payment_info=payment_information- )- else:- response = _success_response(- intent=intent,- kind=TransactionKind.REFUND,- success=refund.status == "succeeded",- amount=payment_information.amount,- currency=get_currency_from_stripe(refund.currency),- )- return response---def void(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:- client = _get_client(**config.connection_params)- try:- with opentracing.global_tracer().start_active_span(- "stripe.PaymentIntent.retrieve"- ) as scope:- span = scope.span- span.set_tag(opentracing.tags.COMPONENT, "payment")- span.set_tag("service.name", "stripe")- intent = client.PaymentIntent.retrieve(id=payment_information.token)- refund = intent["charges"]["data"][0].refund()- except stripe.error.StripeError as exc:- response = _error_response(- kind=TransactionKind.VOID, exc=exc, payment_info=payment_information- )- else:- response = _success_response(- intent=intent,- kind=TransactionKind.VOID,- currency=get_currency_from_stripe(refund.currency),- raw_response=refund,- )- return response---def list_client_sources(- config: GatewayConfig, customer_id: str-) -> List[CustomerSource]:- client = _get_client(**config.connection_params)- with opentracing.global_tracer().start_active_span(- "stripe.PaymentMethod.list"- ) as scope:- span = scope.span- span.set_tag(opentracing.tags.COMPONENT, "payment")- span.set_tag("service.name", "stripe")- cards = client.PaymentMethod.list(customer=customer_id, type="card")["data"]- return [- CustomerSource(- id=c.id,- gateway="stripe",- credit_card_info=PaymentMethodInfo(- exp_year=c.card.exp_year,- exp_month=c.card.exp_month,- last_4=c.card.last4,- name=None,- ),- )- for c in cards- ]---def process_payment(- payment_information: PaymentData, config: GatewayConfig-) -> GatewayResponse:- return authorize(payment_information, config)---def _get_client(**connection_params):- stripe.api_key = connection_params.get("private_key")- return stripe---def _error_response(- kind: str, # use TransactionKind class- exc: stripe.error.StripeError,- payment_info: PaymentData,- action_required: bool = False,-) -> GatewayResponse:- return GatewayResponse(- is_success=False,- action_required=action_required,- transaction_id=payment_info.token or "",- amount=payment_info.amount,- currency=payment_info.currency,- error=exc.user_message,- kind=kind,- raw_response=exc.json_body or {},- customer_id=payment_info.customer_id,- )---def _success_response(- intent: stripe.PaymentIntent,- kind: str, # use TransactionKind class- success: bool = True,- amount=None,- currency=None,- customer_id=None,- raw_response=None,-):- currency = currency or get_currency_from_stripe(intent.currency)- return GatewayResponse(- is_success=success,- action_required=intent.status == "requires_action",- transaction_id=intent.id,- amount=amount or get_amount_from_stripe(intent.amount, currency),- currency=currency,- error=None,- kind=kind,- raw_response=raw_response or intent,- customer_id=customer_id,- )---def fill_card_details(intent: stripe.PaymentIntent, response: GatewayResponse):- charges = intent.charges["data"]- if charges:- card = intent.charges["data"][-1]["payment_method_details"]["card"]- brand = card["brand"] or ""-- response.payment_method_info = PaymentMethodInfo(- last_4=card["last4"],- exp_year=card["exp_year"],- exp_month=card["exp_month"],- brand=brand.lower(),- type="card",- )- return responsediff --git a/saleor/payment/gateways/stripe/consts.py b/saleor/payment/gateways/stripe/consts.pynew file mode 100644index 0000000000..724fef1816--- /dev/null+++ b/saleor/payment/gateways/stripe/consts.py@@ -0,0 +1,41 @@+PLUGIN_ID = "saleor.payments.stripe"+PLUGIN_NAME = "Stripe"+WEBHOOK_PATH = "webhooks/"++WEBHOOK_SUCCESS_EVENT = "payment_intent.succeeded"+WEBHOOK_PROCESSING_EVENT = "payment_intent.processing"+WEBHOOK_FAILED_EVENT = "payment_intent.payment_failed"+WEBHOOK_AUTHORIZED_EVENT = "payment_intent.amount_capturable_updated"+WEBHOOK_CANCELED_EVENT = "payment_intent.canceled"++WEBHOOK_REFUND_EVENT = "charge.refunded"+++WEBHOOK_EVENTS = [+ WEBHOOK_SUCCESS_EVENT,+ WEBHOOK_PROCESSING_EVENT,+ WEBHOOK_FAILED_EVENT,+ WEBHOOK_AUTHORIZED_EVENT,+ WEBHOOK_CANCELED_EVENT,+ WEBHOOK_REFUND_EVENT,+]+METADATA_IDENTIFIER = "saleor-domain"++ACTION_REQUIRED_STATUSES = [+ "requires_payment_method",+ "requires_confirmation",+ "requires_action",+]++FAILED_STATUSES = ["requires_payment_method" "canceled"]++SUCCESS_STATUS = "succeeded"++PROCESSING_STATUS = "processing"++AUTHORIZED_STATUS = "requires_capture"++AUTOMATIC_CAPTURE_METHOD = "automatic"+MANUAL_CAPTURE_METHOD = "manual"++STRIPE_API_VERSION = "2020-08-27"diff --git a/saleor/payment/gateways/stripe/deprecated/__init__.py b/saleor/payment/gateways/stripe/deprecated/__init__.pynew file mode 100644index 0000000000..31c733d6ae--- /dev/null+++ b/saleor/payment/gateways/stripe/deprecated/__init__.py@@ -0,0 +1,287 @@+from typing import List++import opentracing+import opentracing.tags+import stripe++from .... import TransactionKind+from ....interface import (+ CustomerSource,+ GatewayConfig,+ GatewayResponse,+ PaymentData,+ PaymentMethodInfo,+)+from .utils import (+ get_amount_for_stripe,+ get_amount_from_stripe,+ get_currency_for_stripe,+ get_currency_from_stripe,+ shipping_to_stripe_dict,+)+++def get_client_token(**_):+ """Not implemented for stripe gateway currently.++ The client token can be generated by stripe.js automatically.+ """+ return+++def authorize(+ payment_information: PaymentData, config: GatewayConfig+) -> GatewayResponse:+ kind = TransactionKind.CAPTURE if config.auto_capture else TransactionKind.AUTH+ client = _get_client(**config.connection_params)+ capture_method = "automatic" if config.auto_capture else "manual"+ currency = get_currency_for_stripe(payment_information.currency)+ stripe_amount = get_amount_for_stripe(payment_information.amount, currency)+ future_use = "off_session" if config.store_customer else "on_session"+ customer_id = PaymentData.customer_id if payment_information.reuse_source else None+ shipping = (+ shipping_to_stripe_dict(payment_information.shipping)+ if payment_information.shipping+ else None+ )++ try:+ with opentracing.global_tracer().start_active_span(+ "stripe.PaymentIntent.create"+ ) as scope:+ span = scope.span+ span.set_tag(opentracing.tags.COMPONENT, "payment")+ span.set_tag("service.name", "stripe")+ intent = client.PaymentIntent.create(+ payment_method=payment_information.token,+ amount=stripe_amount,+ currency=currency,+ confirmation_method="manual",+ confirm=True,+ capture_method=capture_method,+ setup_future_usage=future_use,+ customer=customer_id,+ shipping=shipping,+ )+ if config.store_customer and not customer_id:+ with opentracing.global_tracer().start_active_span(+ "stripe.Customer.create"+ ) as scope:+ span = scope.span+ span.set_tag(opentracing.tags.COMPONENT, "payment")+ span.set_tag("service.name", "stripe")+ customer = client.Customer.create(payment_method=intent.payment_method)+ customer_id = customer.id++ except stripe.error.StripeError as exc:+ response = _error_response(kind=kind, exc=exc, payment_info=payment_information)+ else:+ success = intent.status in ("succeeded", "requires_capture", "requires_action")+ response = _success_response(+ intent=intent, kind=kind, success=success, customer_id=customer_id+ )+ response = fill_card_details(intent, response)+ return response+++def capture(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:+ client = _get_client(**config.connection_params)+ intent = None+ try:+ with opentracing.global_tracer().start_active_span(+ "stripe.PaymentIntent.retrieve"+ ) as scope:+ span = scope.span+ span.set_tag(opentracing.tags.COMPONENT, "payment")+ span.set_tag("service.name", "stripe")+ intent = client.PaymentIntent.retrieve(id=payment_information.token)+ capture = intent.capture()+ except stripe.error.StripeError as exc:+ action_required = intent.status == "requires_action" if intent else False+ response = _error_response(+ kind=TransactionKind.CAPTURE,+ exc=exc,+ payment_info=payment_information,+ action_required=action_required,+ )+ else:+ response = _success_response(+ intent=intent,+ kind=TransactionKind.CAPTURE,+ success=capture.status in ("succeeded", "requires_action"),+ )+ response = fill_card_details(intent, response)+ return response+++def confirm(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:+ client = _get_client(**config.connection_params)+ try:+ intent = client.PaymentIntent(id=payment_information.token)+ with opentracing.global_tracer().start_active_span(+ "stripe.PaymentIntent.confirm"+ ) as scope:+ span = scope.span+ span.set_tag(opentracing.tags.COMPONENT, "payment")+ span.set_tag("service.name", "stripe")+ intent.confirm()+ except stripe.error.StripeError as exc:+ response = _error_response(+ kind=TransactionKind.CONFIRM, exc=exc, payment_info=payment_information+ )+ else:+ response = _success_response(+ intent=intent,+ kind=TransactionKind.CONFIRM,+ success=intent.status == "succeeded",+ )+ response = fill_card_details(intent, response)+ return response+++def refund(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:+ client = _get_client(**config.connection_params)+ currency = get_currency_for_stripe(payment_information.currency)+ stripe_amount = get_amount_for_stripe(payment_information.amount, currency)+ try:+ with opentracing.global_tracer().start_active_span(+ "stripe.PaymentIntent.retrieve"+ ) as scope:+ span = scope.span+ span.set_tag(opentracing.tags.COMPONENT, "payment")+ span.set_tag("service.name", "stripe")+ intent = client.PaymentIntent.retrieve(id=payment_information.token)+ refund = intent["charges"]["data"][0].refund(amount=stripe_amount)+ except stripe.error.StripeError as exc:+ response = _error_response(+ kind=TransactionKind.REFUND, exc=exc, payment_info=payment_information+ )+ else:+ response = _success_response(+ intent=intent,+ kind=TransactionKind.REFUND,+ success=refund.status == "succeeded",+ amount=payment_information.amount,+ currency=get_currency_from_stripe(refund.currency),+ )+ return response+++def void(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:+ client = _get_client(**config.connection_params)+ try:+ with opentracing.global_tracer().start_active_span(+ "stripe.PaymentIntent.retrieve"+ ) as scope:+ span = scope.span+ span.set_tag(opentracing.tags.COMPONENT, "payment")+ span.set_tag("service.name", "stripe")+ intent = client.PaymentIntent.retrieve(id=payment_information.token)+ refund = intent["charges"]["data"][0].refund()+ except stripe.error.StripeError as exc:+ response = _error_response(+ kind=TransactionKind.VOID, exc=exc, payment_info=payment_information+ )+ else:+ response = _success_response(+ intent=intent,+ kind=TransactionKind.VOID,+ currency=get_currency_from_stripe(refund.currency),+ raw_response=refund,+ )+ return response+++def list_client_sources(+ config: GatewayConfig, customer_id: str+) -> List[CustomerSource]:+ client = _get_client(**config.connection_params)+ with opentracing.global_tracer().start_active_span(+ "stripe.PaymentMethod.list"+ ) as scope:+ span = scope.span+ span.set_tag(opentracing.tags.COMPONENT, "payment")+ span.set_tag("service.name", "stripe")+ cards = client.PaymentMethod.list(customer=customer_id, type="card")["data"]+ return [+ CustomerSource(+ id=c.id,+ gateway="stripe",+ credit_card_info=PaymentMethodInfo(+ exp_year=c.card.exp_year,+ exp_month=c.card.exp_month,+ last_4=c.card.last4,+ name=None,+ ),+ )+ for c in cards+ ]+++def process_payment(+ payment_information: PaymentData, config: GatewayConfig+) -> GatewayResponse:+ return authorize(payment_information, config)+++def _get_client(**connection_params):+ stripe.api_key = connection_params.get("private_key")+ return stripe+++def _error_response(+ kind: str, # use TransactionKind class+ exc: stripe.error.StripeError,+ payment_info: PaymentData,+ action_required: bool = False,+) -> GatewayResponse:+ return GatewayResponse(+ is_success=False,+ action_required=action_required,+ transaction_id=payment_info.token or "",+ amount=payment_info.amount,+ currency=payment_info.currency,+ error=exc.user_message,+ kind=kind,+ raw_response=exc.json_body or {},+ customer_id=payment_info.customer_id,+ )+++def _success_response(+ intent: stripe.PaymentIntent,+ kind: str, # use TransactionKind class+ success: bool = True,+ amount=None,+ currency=None,+ customer_id=None,+ raw_response=None,+):+ currency = currency or get_currency_from_stripe(intent.currency)+ return GatewayResponse(+ is_success=success,+ action_required=intent.status == "requires_action",+ transaction_id=intent.id,+ amount=amount or get_amount_from_stripe(intent.amount, currency),+ currency=currency,+ error=None,+ kind=kind,+ raw_response=raw_response or intent,+ customer_id=customer_id,+ )+++def fill_card_details(intent: stripe.PaymentIntent, response: GatewayResponse):+ charges = intent.charges["data"]+ if charges:+ card = intent.charges["data"][-1]["payment_method_details"]["card"]+ brand = card["brand"] or ""++ response.payment_method_info = PaymentMethodInfo(+ last_4=card["last4"],+ exp_year=card["exp_year"],+ exp_month=card["exp_month"],+ brand=brand.lower(),+ type="card",+ )+ return responsediff --git a/saleor/payment/gateways/stripe/deprecated/plugin.py b/saleor/payment/gateways/stripe/deprecated/plugin.pynew file mode 100644index 0000000000..d4565dd5a8--- /dev/null+++ b/saleor/payment/gateways/stripe/deprecated/plugin.py@@ -0,0 +1,136 @@+from typing import TYPE_CHECKING, List++from saleor.plugins.base_plugin import BasePlugin, ConfigurationTypeField++from ...utils import get_supported_currencies, require_active_plugin+from . import (+ GatewayConfig,+ authorize,+ capture,+ list_client_sources,+ process_payment,+ refund,+ void,+)++GATEWAY_NAME = "Stripe (Deprecated)"++if TYPE_CHECKING:+ # flake8: noqa+ from ....interface import CustomerSource+ from . import GatewayResponse, PaymentData+++class DeprecatedStripeGatewayPlugin(BasePlugin):+ PLUGIN_NAME = GATEWAY_NAME+ PLUGIN_ID = "mirumee.payments.stripe"+ PLUGIN_DESCRIPTION = """+ This plugin will be removed in Saleor 4.0. Use the new Stripe plugin which+ implements webhook support, 3D Secure and SCA.+ """++ DEFAULT_CONFIGURATION = [+ {"name": "Public API key", "value": None},+ {"name": "Secret API key", "value": None},+ {"name": "Store customers card", "value": False},+ {"name": "Automatic payment capture", "value": True},+ {"name": "Supported currencies", "value": ""},+ ]++ CONFIG_STRUCTURE = {+ "Public API key": {+ "type": ConfigurationTypeField.SECRET,+ "help_text": "Provide Stripe public API key.",+ "label": "Public API key",+ },+ "Secret API key": {+ "type": ConfigurationTypeField.SECRET,+ "help_text": "Provide Stripe secret API key.",+ "label": "Secret API key",+ },+ "Store customers card": {+ "type": ConfigurationTypeField.BOOLEAN,+ "help_text": "Determines if Saleor should store cards on payments "+ "in Stripe customer.",+ "label": "Store customers card",+ },+ "Automatic payment capture": {+ "type": ConfigurationTypeField.BOOLEAN,+ "help_text": "Determines if Saleor should automaticaly capture payments.",+ "label": "Automatic payment capture",+ },+ "Supported currencies": {+ "type": ConfigurationTypeField.STRING,+ "help_text": "Determines currencies supported by gateway."+ " Please enter currency codes separated by a comma.",+ "label": "Supported currencies",+ },+ }++ 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=configuration["Automatic payment capture"],+ supported_currencies=configuration["Supported currencies"],+ connection_params={+ "public_key": configuration["Public API key"],+ "private_key": configuration["Secret API key"],+ },+ store_customer=configuration["Store customers card"],+ )++ def _get_gateway_config(self):+ return self.config++ @require_active_plugin+ def authorize_payment(+ self, payment_information: "PaymentData", previous_value+ ) -> "GatewayResponse":+ return authorize(payment_information, self._get_gateway_config())++ @require_active_plugin+ def capture_payment(+ self, payment_information: "PaymentData", previous_value+ ) -> "GatewayResponse":+ return capture(payment_information, self._get_gateway_config())++ @require_active_plugin+ def refund_payment(+ self, payment_information: "PaymentData", previous_value+ ) -> "GatewayResponse":+ return refund(payment_information, self._get_gateway_config())++ @require_active_plugin+ def void_payment(+ self, payment_information: "PaymentData", previous_value+ ) -> "GatewayResponse":+ return void(payment_information, self._get_gateway_config())++ @require_active_plugin+ def process_payment(+ self, payment_information: "PaymentData", previous_value+ ) -> "GatewayResponse":+ return process_payment(payment_information, self._get_gateway_config())++ @require_active_plugin+ def list_payment_sources(+ self, customer_id: str, previous_value+ ) -> List["CustomerSource"]:+ sources = list_client_sources(self._get_gateway_config(), customer_id)+ previous_value.extend(sources)+ return previous_value++ @require_active_plugin+ def get_supported_currencies(self, previous_value):+ config = self._get_gateway_config()+ return get_supported_currencies(config, GATEWAY_NAME)++ @require_active_plugin+ def get_payment_config(self, previous_value):+ config = self._get_gateway_config()+ return [+ {"field": "api_key", "value": config.connection_params["public_key"]},+ {"field": "store_customer_card", "value": config.store_customer},+ ]diff --git a/saleor/payment/gateways/stripe/deprecated/tests/__init__.py b/saleor/payment/gateways/stripe/deprecated/tests/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/payment/gateways/stripe/tests/cassettes/test_authorize.yaml b/saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_authorize.yamlsimilarity index 100%rename from saleor/payment/gateways/stripe/tests/cassettes/test_authorize.yamlrename to saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_authorize.yamldiff --git a/saleor/payment/gateways/stripe/tests/cassettes/test_authorize_3d_secure.yaml b/saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_authorize_3d_secure.yamlsimilarity index 100%rename from saleor/payment/gateways/stripe/tests/cassettes/test_authorize_3d_secure.yamlrename to saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_authorize_3d_secure.yamldiff --git a/saleor/payment/gateways/stripe/tests/cassettes/test_authorize_and_save_customer_id.yaml b/saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_authorize_and_save_customer_id.yamlsimilarity index 100%rename from saleor/payment/gateways/stripe/tests/cassettes/test_authorize_and_save_customer_id.yamlrename to saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_authorize_and_save_customer_id.yamldiff --git a/saleor/payment/gateways/stripe/tests/cassettes/test_authorize_error_response.yaml b/saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_authorize_error_response.yamlsimilarity index 100%rename from saleor/payment/gateways/stripe/tests/cassettes/test_authorize_error_response.yamlrename to saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_authorize_error_response.yamldiff --git a/saleor/payment/gateways/stripe/tests/cassettes/test_authorize_with_customer_id.yaml b/saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_authorize_with_customer_id.yamlsimilarity index 100%rename from saleor/payment/gateways/stripe/tests/cassettes/test_authorize_with_customer_id.yamlrename to saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_authorize_with_customer_id.yamldiff --git a/saleor/payment/gateways/stripe/tests/cassettes/test_authorize_without_capture.yaml b/saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_authorize_without_capture.yamlsimilarity index 100%rename from saleor/payment/gateways/stripe/tests/cassettes/test_authorize_without_capture.yamlrename to saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_authorize_without_capture.yamldiff --git a/saleor/payment/gateways/stripe/tests/cassettes/test_capture.yaml b/saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_capture.yamlsimilarity index 100%rename from saleor/payment/gateways/stripe/tests/cassettes/test_capture.yamlrename to saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_capture.yamldiff --git a/saleor/payment/gateways/stripe/tests/cassettes/test_capture_3d_secure.yaml b/saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_capture_3d_secure.yamlsimilarity index 100%rename from saleor/payment/gateways/stripe/tests/cassettes/test_capture_3d_secure.yamlrename to saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_capture_3d_secure.yamldiff --git a/saleor/payment/gateways/stripe/tests/cassettes/test_capture_error_response.yaml b/saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_capture_error_response.yamlsimilarity index 100%rename from saleor/payment/gateways/stripe/tests/cassettes/test_capture_error_response.yamlrename to saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_capture_error_response.yamldiff --git a/saleor/payment/gateways/stripe/tests/cassettes/test_confirm__intent.yaml b/saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_confirm__intent.yamlsimilarity index 100%rename from saleor/payment/gateways/stripe/tests/cassettes/test_confirm__intent.yamlrename to saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_confirm__intent.yamldiff --git a/saleor/payment/gateways/stripe/tests/cassettes/test_confirm_error_response.yaml b/saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_confirm_error_response.yamlsimilarity index 100%rename from saleor/payment/gateways/stripe/tests/cassettes/test_confirm_error_response.yamlrename to saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_confirm_error_response.yamldiff --git a/saleor/payment/gateways/stripe/tests/cassettes/test_list_customer_sources.yaml b/saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_list_customer_sources.yamlsimilarity index 100%rename from saleor/payment/gateways/stripe/tests/cassettes/test_list_customer_sources.yamlrename to saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_list_customer_sources.yamldiff --git a/saleor/payment/gateways/stripe/tests/cassettes/test_refund.yaml b/saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_refund.yamlsimilarity index 100%rename from saleor/payment/gateways/stripe/tests/cassettes/test_refund.yamlrename to saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_refund.yamldiff --git a/saleor/payment/gateways/stripe/tests/cassettes/test_refund_error_response.yaml b/saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_refund_error_response.yamlsimilarity index 100%rename from saleor/payment/gateways/stripe/tests/cassettes/test_refund_error_response.yamlrename to saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_refund_error_response.yamldiff --git a/saleor/payment/gateways/stripe/tests/cassettes/test_void.yaml b/saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_void.yamlsimilarity index 100%rename from saleor/payment/gateways/stripe/tests/cassettes/test_void.yamlrename to saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_void.yamldiff --git a/saleor/payment/gateways/stripe/tests/cassettes/test_void_error_response.yaml b/saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_void_error_response.yamlsimilarity index 100%rename from saleor/payment/gateways/stripe/tests/cassettes/test_void_error_response.yamlrename to saleor/payment/gateways/stripe/deprecated/tests/cassettes/test_void_error_response.yamldiff --git a/saleor/payment/gateways/stripe/tests/test_stripe.py b/saleor/payment/gateways/stripe/deprecated/tests/test_stripe.pysimilarity index 98%rename from saleor/payment/gateways/stripe/tests/test_stripe.pyrename to saleor/payment/gateways/stripe/deprecated/tests/test_stripe.pyindex 9f937c310d..6251464ba8 100644--- a/saleor/payment/gateways/stripe/tests/test_stripe.py+++ b/saleor/payment/gateways/stripe/deprecated/tests/test_stripe.py@@ -4,9 +4,9 @@ from math import iscloseimport pytest-from .... import ChargeStatus-from ....interface import CustomerSource, GatewayConfig, PaymentMethodInfo-from ....utils import create_payment_information+from ..... import ChargeStatus+from .....interface import CustomerSource, GatewayConfig, PaymentMethodInfo+from .....utils import create_payment_informationfrom .. import (TransactionKind,_get_client,diff --git a/saleor/payment/gateways/stripe/tests/test_utils.py b/saleor/payment/gateways/stripe/deprecated/tests/test_utils.pysimilarity index 97%rename from saleor/payment/gateways/stripe/tests/test_utils.pyrename to saleor/payment/gateways/stripe/deprecated/tests/test_utils.pyindex 981eb54e93..88b5a56b39 100644--- a/saleor/payment/gateways/stripe/tests/test_utils.py+++ b/saleor/payment/gateways/stripe/deprecated/tests/test_utils.py@@ -3,8 +3,8 @@ from math import isclosefrom django_countries import countries-from ....interface import AddressData-from ....utils import create_payment_information+from .....interface import AddressData+from .....utils import create_payment_informationfrom ..utils import (get_amount_for_stripe,get_amount_from_stripe,diff --git a/saleor/payment/gateways/stripe/utils.py b/saleor/payment/gateways/stripe/deprecated/utils.pysimilarity index 98%rename from saleor/payment/gateways/stripe/utils.pyrename to saleor/payment/gateways/stripe/deprecated/utils.pyindex e55c2f3278..7ecd9825a8 100644--- a/saleor/payment/gateways/stripe/utils.py+++ b/saleor/payment/gateways/stripe/deprecated/utils.py@@ -7,7 +7,7 @@ from django_countries import countries# Since there is no public API in Stripe backend or helper function# in Stripe's Python library, this list is straight out of Stripe's docs# https://stripe.com/docs/currencies#zero-decimal-from ...interface import AddressData, PaymentData+from ....interface import AddressData, PaymentDataZERO_DECIMAL_CURRENCIES = ["BIF",diff --git a/saleor/payment/gateways/stripe/plugin.py b/saleor/payment/gateways/stripe/plugin.pyindex d44f9fd668..5757de59ac 100644--- a/saleor/payment/gateways/stripe/plugin.py+++ b/saleor/payment/gateways/stripe/plugin.py@@ -1,131 +1,548 @@-from typing import TYPE_CHECKING, List+import logging+from typing import TYPE_CHECKING, List, Optional, Tuple-from saleor.plugins.base_plugin import BasePlugin, ConfigurationTypeField+from django.contrib.sites.models import Site+from django.core.exceptions import ValidationError+from django.core.handlers.wsgi import WSGIRequest+from django.http import HttpResponse, HttpResponseNotFound+from django.http.request import split_domain_port+from stripe.stripe_object import StripeObject-from ..utils import get_supported_currencies, require_active_plugin-from . import (+from ....graphql.core.enums import PluginErrorCode+from ....plugins.base_plugin import BasePlugin, ConfigurationTypeField+from ... import TransactionKind+from ...interface import (+ CustomerSource,GatewayConfig,- authorize,- capture,- list_client_sources,- process_payment,- refund,- void,+ GatewayResponse,+ PaymentData,+ PaymentMethodInfo,)--GATEWAY_NAME = "Stripe"+from ...models import Transaction+from ...utils import price_from_minor_unit, price_to_minor_unit+from ..utils import get_supported_currencies, require_active_plugin+from .stripe_api import (+ cancel_payment_intent,+ capture_payment_intent,+ create_payment_intent,+ delete_webhook,+ get_or_create_customer,+ get_payment_method_details,+ is_secret_api_key_valid,+ list_customer_payment_methods,+ refund_payment_intent,+ retrieve_payment_intent,+ subscribe_webhook,+)+from .webhooks import handle_webhookif TYPE_CHECKING:# flake8: noqa- from ...interface import CustomerSource- from . import GatewayResponse, PaymentData+ from ....plugins.models import PluginConfiguration++from .consts import (+ ACTION_REQUIRED_STATUSES,+ AUTHORIZED_STATUS,+ PLUGIN_ID,+ PLUGIN_NAME,+ PROCESSING_STATUS,+ SUCCESS_STATUS,+ WEBHOOK_PATH,+)++logger = logging.getLogger(__name__)class StripeGatewayPlugin(BasePlugin):- PLUGIN_NAME = GATEWAY_NAME- PLUGIN_ID = "mirumee.payments.stripe"+ PLUGIN_NAME = PLUGIN_NAME+ PLUGIN_ID = PLUGIN_IDDEFAULT_CONFIGURATION = [- {"name": "Public API key", "value": None},- {"name": "Secret API key", "value": None},- {"name": "Store customers card", "value": False},- {"name": "Automatic payment capture", "value": True},- {"name": "Supported currencies", "value": ""},+ {"name": "public_api_key", "value": None},+ {"name": "secret_api_key", "value": None},+ {"name": "automatic_payment_capture", "value": True},+ {"name": "supported_currencies", "value": ""},+ {"name": "webhook_endpoint_id", "value": None},+ {"name": "webhook_secret_key", "value": None},]CONFIG_STRUCTURE = {- "Public API key": {- "type": ConfigurationTypeField.SECRET,+ "public_api_key": {+ "type": ConfigurationTypeField.STRING,"help_text": "Provide Stripe public API key.","label": "Public API key",},- "Secret API key": {+ "secret_api_key": {"type": ConfigurationTypeField.SECRET,"help_text": "Provide Stripe secret API key.","label": "Secret API key",},- "Store customers card": {- "type": ConfigurationTypeField.BOOLEAN,- "help_text": "Determines if Saleor should store cards on payments "- "in Stripe customer.",- "label": "Store customers card",- },- "Automatic payment capture": {+ "automatic_payment_capture": {"type": ConfigurationTypeField.BOOLEAN,"help_text": "Determines if Saleor should automaticaly capture payments.","label": "Automatic payment capture",},- "Supported currencies": {+ "supported_currencies": {"type": ConfigurationTypeField.STRING,"help_text": "Determines currencies supported by gateway."" Please enter currency codes separated by a comma.","label": "Supported currencies",},+ "webhook_endpoint_id": {+ "type": ConfigurationTypeField.OUTPUT,+ "help_text": "Unique identifier for the webhook endpoint object.",+ "label": "Webhook endpoint",+ },}def __init__(self, *args, **kwargs):++ # Webhook details are not listed in CONFIG_STRUCTURE as user input is not+ # required here+ plugin_configuration = kwargs.get("configuration")+ raw_configuration = {+ item["name"]: item["value"] for item in plugin_configuration+ }+ webhook_secret = raw_configuration.get("webhook_secret_key")+super().__init__(*args, **kwargs)configuration = {item["name"]: item["value"] for item in self.configuration}self.config = GatewayConfig(- gateway_name=GATEWAY_NAME,- auto_capture=configuration["Automatic payment capture"],- supported_currencies=configuration["Supported currencies"],+ gateway_name=PLUGIN_NAME,+ auto_capture=configuration["automatic_payment_capture"],+ supported_currencies=configuration["supported_currencies"],connection_params={- "public_key": configuration["Public API key"],- "private_key": configuration["Secret API key"],+ "public_api_key": configuration["public_api_key"],+ "secret_api_key": configuration["secret_api_key"],+ "webhook_id": configuration["webhook_endpoint_id"],+ "webhook_secret": webhook_secret,},- store_customer=configuration["Store customers card"],+ store_customer=True,)- def _get_gateway_config(self):- return self.config+ def webhook(self, request: WSGIRequest, path: str, previous_value) -> HttpResponse:+ config = self.config+ if path.startswith(WEBHOOK_PATH, 1): # 1 as we don't check the '/'+ return handle_webhook(request, config)+ logger.warning(+ "Received request to incorrect stripe path", extra={"path": path}+ )+ return HttpResponseNotFound()++ @require_active_plugin+ def token_is_required_as_payment_input(self, previous_value):+ return False++ @require_active_plugin+ def get_supported_currencies(self, previous_value):+ return get_supported_currencies(self.config, PLUGIN_NAME)++ @property+ def order_auto_confirmation(self):+ site_settings = Site.objects.get_current().settings+ return site_settings.automatically_confirm_all_new_orders++ def _get_transaction_details_for_stripe_status(+ self, status: str+ ) -> Tuple[str, bool]:+ kind = TransactionKind.AUTH+ action_required = True++ # payment still requires an action+ if status in ACTION_REQUIRED_STATUSES:+ kind = TransactionKind.ACTION_TO_CONFIRM+ elif status == PROCESSING_STATUS:+ kind = TransactionKind.PENDING+ action_required = False+ elif status == SUCCESS_STATUS:+ kind = TransactionKind.CAPTURE+ action_required = False+ elif status == AUTHORIZED_STATUS:+ kind = TransactionKind.AUTH+ action_required = False++ return kind, action_required@require_active_plugin- def authorize_payment(+ def process_payment(self, payment_information: "PaymentData", previous_value) -> "GatewayResponse":- return authorize(payment_information, self._get_gateway_config())++ api_key = self.config.connection_params["secret_api_key"]++ auto_capture = self.config.auto_capture+ if self.order_auto_confirmation is False:+ auto_capture = False++ data = payment_information.data++ payment_method_id = data.get("payment_method_id") if data else None++ setup_future_usage = None+ if payment_information.reuse_source:+ setup_future_usage = data.get("setup_future_usage") if data else None++ off_session = data.get("off_session") if data else None++ payment_method_types = data.get("payment_method_types") if data else None++ customer = None+ # confirm that we creates customer on stripe side only for log-in customers+ # Stripe doesn't allow to search users by email, so each create customer+ # call creates new customer on Stripe side.+ if payment_information.graphql_customer_id:+ customer = get_or_create_customer(+ api_key=api_key,+ customer_email=payment_information.customer_email,+ customer_id=payment_information.customer_id,+ )+ intent, error = create_payment_intent(+ api_key=api_key,+ amount=payment_information.amount,+ currency=payment_information.currency,+ auto_capture=auto_capture,+ customer=customer,+ payment_method_id=payment_method_id,+ metadata={+ "channel": self.channel.slug, # type: ignore+ "payment_id": payment_information.graphql_payment_id,+ },+ setup_future_usage=setup_future_usage,+ off_session=off_session,+ payment_method_types=payment_method_types,+ customer_email=payment_information.customer_email,+ )++ if error and payment_method_id and not intent:+ # we can receive an error which is caused by a required authentication+ # but stripe already created payment_intent.+ stripe_error = error.error+ intent = getattr(stripe_error, "payment_intent", None)+ error = None if intent else error++ raw_response = None+ client_secret = None+ intent_id = None+ kind = TransactionKind.ACTION_TO_CONFIRM+ action_required = True+ if intent:+ kind, action_required = self._get_transaction_details_for_stripe_status(+ intent.status+ )+ client_secret = intent.client_secret+ raw_response = intent.last_response.data+ intent_id = intent.id++ return GatewayResponse(+ is_success=True if not error else False,+ action_required=action_required,+ kind=kind,+ amount=payment_information.amount,+ currency=payment_information.currency,+ transaction_id=intent.id if intent else "",+ error=error.user_message if error else None,+ raw_response=raw_response,+ action_required_data={"client_secret": client_secret, "id": intent_id},+ customer_id=customer.id if customer else None,+ psp_reference=intent.id if intent else None,+ )@require_active_plugin- def capture_payment(+ def confirm_payment(self, payment_information: "PaymentData", previous_value) -> "GatewayResponse":- return capture(payment_information, self._get_gateway_config())+ payment_intent_id = payment_information.token+ api_key = self.config.connection_params["secret_api_key"]++ # before we will call stripe API, let's check if the transaction object hasn't+ # been created by webhook handler+ payment_transaction = Transaction.objects.filter(+ payment_id=payment_information.payment_id,+ is_success=True,+ action_required=False,+ kind__in=[+ TransactionKind.AUTH,+ TransactionKind.CAPTURE,+ TransactionKind.PENDING,+ ],+ ).first()++ if payment_transaction:+ return GatewayResponse(+ is_success=True,+ action_required=False,+ kind=payment_transaction.kind,+ amount=payment_transaction.amount,+ currency=payment_transaction.currency,+ transaction_id=payment_transaction.token,+ error=None,+ raw_response=payment_transaction.gateway_response,+ transaction_already_processed=True,+ )++ payment_intent = None+ error = None+ payment_method_info = None+ if payment_intent_id:+ payment_intent, error = retrieve_payment_intent(api_key, payment_intent_id)++ kind = TransactionKind.AUTH+ if payment_intent:+ amount = price_from_minor_unit(+ payment_intent.amount, payment_intent.currency+ )+ currency = payment_intent.currency++ kind, action_required = self._get_transaction_details_for_stripe_status(+ payment_intent.status+ )+ if kind == TransactionKind.CAPTURE:+ payment_method_info = get_payment_method_details(payment_intent)+ else:+ action_required = False+ amount = payment_information.amount+ currency = payment_information.currency++ raw_response = None+ if payment_intent and payment_intent.last_response:+ raw_response = payment_intent.last_response.data++ return GatewayResponse(+ is_success=True if payment_intent else False,+ action_required=action_required,+ kind=kind,+ amount=amount,+ currency=currency,+ transaction_id=payment_intent.id if payment_intent else "",+ error=error.user_message if error else None,+ raw_response=raw_response,+ psp_reference=payment_intent.id if payment_intent else None,+ payment_method_info=payment_method_info,+ )@require_active_plugin- def refund_payment(+ def capture_payment(self, payment_information: "PaymentData", previous_value) -> "GatewayResponse":- return refund(payment_information, self._get_gateway_config())+ payment_intent_id = payment_information.token+ capture_amount = price_to_minor_unit(+ payment_information.amount, payment_information.currency+ )+ payment_intent, error = capture_payment_intent(+ api_key=self.config.connection_params["secret_api_key"],+ payment_intent_id=payment_intent_id, # type: ignore+ amount_to_capture=capture_amount,+ )++ raw_response = None+ if payment_intent and payment_intent.last_response:+ raw_response = payment_intent.last_response.data++ payment_method_info = None+ if payment_intent and payment_intent.status == SUCCESS_STATUS:+ payment_method_info = get_payment_method_details(payment_intent)++ return GatewayResponse(+ is_success=True if payment_intent else False,+ action_required=False,+ kind=TransactionKind.CAPTURE,+ amount=payment_information.amount,+ currency=payment_information.currency,+ transaction_id=payment_intent.id if payment_intent else "",+ error=error.user_message if error else None,+ raw_response=raw_response,+ payment_method_info=payment_method_info,+ )@require_active_plugin- def void_payment(+ def refund_payment(self, payment_information: "PaymentData", previous_value) -> "GatewayResponse":- return void(payment_information, self._get_gateway_config())+ payment_intent_id = payment_information.token+ refund_amount = price_to_minor_unit(+ payment_information.amount, payment_information.currency+ )+ refund, error = refund_payment_intent(+ api_key=self.config.connection_params["secret_api_key"],+ payment_intent_id=payment_intent_id, # type: ignore+ amount_to_refund=refund_amount,+ )++ raw_response = None+ if refund and refund.last_response:+ raw_response = refund.last_response.data++ return GatewayResponse(+ is_success=True if refund else False,+ action_required=False,+ kind=TransactionKind.REFUND,+ amount=payment_information.amount,+ currency=payment_information.currency,+ transaction_id=refund.id if refund else "",+ error=error.user_message if error else None,+ raw_response=raw_response,+ )@require_active_plugin- def process_payment(+ def void_payment(self, payment_information: "PaymentData", previous_value) -> "GatewayResponse":- return process_payment(payment_information, self._get_gateway_config())+ payment_intent_id = payment_information.token++ payment_intent, error = cancel_payment_intent(+ api_key=self.config.connection_params["secret_api_key"],+ payment_intent_id=payment_intent_id, # type: ignore+ )++ raw_response = None+ if payment_intent and payment_intent.last_response:+ raw_response = payment_intent.last_response.data++ return GatewayResponse(+ is_success=True if payment_intent else False,+ action_required=False,+ kind=TransactionKind.VOID,+ amount=payment_information.amount,+ currency=payment_information.currency,+ transaction_id=payment_intent.id if payment_intent else "",+ error=error.user_message if error else None,+ raw_response=raw_response,+ )@require_active_plugindef list_payment_sources(self, customer_id: str, previous_value- ) -> List["CustomerSource"]:- sources = list_client_sources(self._get_gateway_config(), customer_id)- previous_value.extend(sources)+ ) -> List[CustomerSource]:+ payment_methods, error = list_customer_payment_methods(+ api_key=self.config.connection_params["secret_api_key"],+ customer_id=customer_id,+ )+ if payment_methods:+ customer_sources = [+ CustomerSource(+ id=c.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,+ name=None,+ brand=c.card.brand,+ ),+ )+ for c in payment_methods+ ]+ previous_value.extend(customer_sources)return previous_value- @require_active_plugin- def get_supported_currencies(self, previous_value):- config = self._get_gateway_config()- return get_supported_currencies(config, GATEWAY_NAME)+ @classmethod+ def pre_save_plugin_configuration(cls, plugin_configuration: "PluginConfiguration"):+ configuration = plugin_configuration.configuration+ flat_configuration = {item["name"]: item["value"] for item in configuration}++ api_key = flat_configuration["secret_api_key"]+ webhook_id = flat_configuration.get("webhook_endpoint_id")+ webhook_secret = flat_configuration.get("webhook_secret_key")++ if not plugin_configuration.active:+ if webhook_id:+ # delete all webhook details when we disable a stripe integration.+ webhook_id_field = [+ c_field+ for c_field in configuration+ if c_field["name"] == "webhook_endpoint_id"+ ][0]+ webhook_id_field["value"] = ""++ plugin_configuration.configuration.remove(+ {+ "name": "webhook_secret_key",+ "value": webhook_secret,+ }+ )+ delete_webhook(api_key, webhook_id)++ return++ # check saved domain. Make sure that it is not localhost domain. We are not able+ # to subscribe to stripe webhooks with localhost.+ domain = Site.objects.get_current().domain+ localhost_domains = ["localhost", "127.0.0.1"]+ domain, _ = split_domain_port(domain)+ if not domain:+ logger.warning(+ "Site doesn't have defined domain. Unable to subscribe Stripe webhooks"+ )+ return+ if domain in localhost_domains:+ logger.warning(+ "Unable to subscribe localhost domain - %s to Stripe webhooks. Stripe "+ "webhooks require domain which will be accessible from the network",+ domain,+ )+ return++ webhook = None+ if not webhook_id and not webhook_secret:+ webhook = subscribe_webhook(+ api_key, plugin_configuration.channel.slug # type: ignore+ )++ if not webhook:+ logger.warning(+ "Unable to subscribe to Stripe webhook", extra={"domain": domain}+ )+ return+ cls._update_or_create_config_field(+ plugin_configuration.configuration, "webhook_endpoint_id", webhook.id+ )+ cls._update_or_create_config_field(+ plugin_configuration.configuration, "webhook_secret_key", webhook.secret+ )++ @classmethod+ def _update_or_create_config_field(cls, configuration, field, value):+ for c_field in configuration:+ if c_field["name"] == field:+ c_field["value"] = value+ return+ configuration.append({"name": field, "value": value})++ @classmethod+ def validate_plugin_configuration(cls, plugin_configuration: "PluginConfiguration"):+ configuration = plugin_configuration.configuration+ configuration = {item["name"]: item["value"] for item in configuration}+ required_fields = ["secret_api_key", "public_api_key"]+ all_required_fields_provided = all(+ [configuration.get(field) for field in required_fields]+ )+ if plugin_configuration.active:+ if not all_required_fields_provided:+ raise ValidationError(+ {+ field: ValidationError(+ "The parameter is required.",+ code=PluginErrorCode.REQUIRED.value,+ )+ }+ for field in required_fields+ )++ api_key = configuration["secret_api_key"]+ if not is_secret_api_key_valid(api_key):+ raise ValidationError(+ {+ "secret_api_key": ValidationError(+ "Secret API key is incorrect",+ code=PluginErrorCode.INVALID.value,+ )+ }+ )@require_active_plugindef get_payment_config(self, previous_value):- config = self._get_gateway_config()return [- {"field": "api_key", "value": config.connection_params["public_key"]},- {"field": "store_customer_card", "value": config.store_customer},+ {+ "field": "api_key",+ "value": self.config.connection_params["public_api_key"],+ },]diff --git a/saleor/payment/gateways/stripe/stripe_api.py b/saleor/payment/gateways/stripe/stripe_api.pynew file mode 100644index 0000000000..f859be4494--- /dev/null+++ b/saleor/payment/gateways/stripe/stripe_api.py@@ -0,0 +1,308 @@+import logging+from contextlib import contextmanager+from decimal import Decimal+from typing import List, Optional, Tuple+from urllib.parse import urljoin++import stripe+from django.contrib.sites.models import Site+from django.urls import reverse+from stripe.error import AuthenticationError, InvalidRequestError, StripeError+from stripe.stripe_object import StripeObject++from ....core.tracing import opentracing_trace+from ....core.utils import build_absolute_uri+from ...interface import PaymentMethodInfo+from ...utils import price_to_minor_unit+from .consts import (+ AUTOMATIC_CAPTURE_METHOD,+ MANUAL_CAPTURE_METHOD,+ METADATA_IDENTIFIER,+ PLUGIN_ID,+ STRIPE_API_VERSION,+ WEBHOOK_EVENTS,+ WEBHOOK_PATH,+)++logger = logging.getLogger(__name__)+++@contextmanager+def stripe_opentracing_trace(span_name):+ with opentracing_trace(+ span_name=span_name, component_name="payment", service_name="stripe"+ ):+ yield+++def is_secret_api_key_valid(api_key: str):+ """Call api to check if api_key is a correct key."""+ try:+ with stripe_opentracing_trace("stripe.WebhookEndpoint.list"):+ stripe.WebhookEndpoint.list(api_key, stripe_version=STRIPE_API_VERSION)+ return True+ except AuthenticationError:+ return False+++def _extra_log_data(error: StripeError, payment_intent_id: Optional[str] = None):+ data = {+ "error_message": error.user_message,+ "http_status": error.http_status,+ "code": error.code,+ }+ if payment_intent_id is not None:+ data["payment_intent_id"] = payment_intent_id+ return data+++def subscribe_webhook(api_key: str, channel_slug: str) -> Optional[StripeObject]:+ domain = Site.objects.get_current().domain+ api_path = reverse(+ "plugins-per-channel",+ kwargs={"plugin_id": PLUGIN_ID, "channel_slug": channel_slug},+ )++ base_url = build_absolute_uri(api_path)+ webhook_url = urljoin(base_url, WEBHOOK_PATH) # type: ignore++ with stripe_opentracing_trace("stripe.WebhookEndpoint.create"):+ try:+ return stripe.WebhookEndpoint.create(+ api_key=api_key,+ url=webhook_url,+ enabled_events=WEBHOOK_EVENTS,+ metadata={METADATA_IDENTIFIER: domain},+ stripe_version=STRIPE_API_VERSION,+ )+ except StripeError as error:+ logger.warning(+ "Failed to create Stripe webhook",+ extra=_extra_log_data(error),+ )+ return None+++def delete_webhook(api_key: str, webhook_id: str):+ try:+ with stripe_opentracing_trace("stripe.WebhookEndpoint.delete"):+ stripe.WebhookEndpoint.delete(+ webhook_id,+ api_key=api_key,+ stripe_version=STRIPE_API_VERSION,+ )+ except InvalidRequestError:+ # webhook doesn't exist+ pass+++def get_or_create_customer(+ api_key: str,+ customer_id: Optional[str] = None,+ customer_email: Optional[str] = None,+) -> Optional[StripeObject]:+ try:+ if customer_id:+ with stripe_opentracing_trace("stripe.Customer.retrieve"):+ return stripe.Customer.retrieve(+ customer_id,+ api_key=api_key,+ stripe_version=STRIPE_API_VERSION,+ )+ with stripe_opentracing_trace("stripe.Customer.create"):+ return stripe.Customer.create(+ api_key=api_key, email=customer_email, stripe_version=STRIPE_API_VERSION+ )+ except StripeError as error:+ logger.warning(+ "Failed to get/create Stripe customer",+ extra=_extra_log_data(error),+ )+ return None+++def create_payment_intent(+ api_key: str,+ amount: Decimal,+ currency: str,+ auto_capture: bool = True,+ customer: Optional[StripeObject] = None,+ payment_method_id: Optional[str] = None,+ metadata: Optional[dict] = None,+ setup_future_usage: Optional[str] = None,+ off_session: Optional[bool] = None,+ payment_method_types: Optional[List[str]] = None,+ customer_email: Optional[str] = None,+) -> Tuple[Optional[StripeObject], Optional[StripeError]]:++ capture_method = AUTOMATIC_CAPTURE_METHOD if auto_capture else MANUAL_CAPTURE_METHOD+ additional_params = {} # type: ignore++ if customer:+ additional_params["customer"] = customer++ if payment_method_id and customer:+ additional_params["payment_method"] = payment_method_id++ additional_params["off_session"] = off_session if off_session else False+ if off_session:+ additional_params["confirm"] = True++ if setup_future_usage in ["on_session", "off_session"] and not payment_method_id:+ additional_params["setup_future_usage"] = setup_future_usage++ if metadata:+ additional_params["metadata"] = metadata++ if payment_method_types and isinstance(payment_method_types, list):+ additional_params["payment_method_types"] = payment_method_types++ if customer_email:+ additional_params["receipt_email"] = customer_email++ try:+ with stripe_opentracing_trace("stripe.PaymentIntent.create"):+ intent = stripe.PaymentIntent.create(+ api_key=api_key,+ amount=price_to_minor_unit(amount, currency),+ currency=currency,+ capture_method=capture_method,+ stripe_version=STRIPE_API_VERSION,+ **additional_params,+ )+ return intent, None+ except StripeError as error:+ logger.warning(+ "Failed to create Stripe payment intent", extra=_extra_log_data(error)+ )+ return None, error+++def list_customer_payment_methods(+ api_key: str, customer_id: str+) -> Tuple[Optional[StripeObject], Optional[StripeError]]:+ try:+ with stripe_opentracing_trace("stripe.PaymentMethod.list"):+ payment_methods = stripe.PaymentMethod.list(+ api_key=api_key,+ customer=customer_id,+ stripe_version=STRIPE_API_VERSION,+ type="card", # we support only cards for now+ )+ return payment_methods, None+ except StripeError as error:+ return None, error+++def retrieve_payment_intent(+ api_key: str, payment_intent_id: str+) -> Tuple[Optional[StripeObject], Optional[StripeError]]:+ try:+ with stripe_opentracing_trace("stripe.PaymentIntent.retrieve"):+ payment_intent = stripe.PaymentIntent.retrieve(+ payment_intent_id,+ api_key=api_key,+ stripe_version=STRIPE_API_VERSION,+ )+ return payment_intent, None+ except StripeError as error:+ logger.warning(+ "Unable to retrieve a payment intent",+ extra=_extra_log_data(error),+ )+ return None, error+++def capture_payment_intent(+ api_key: str, payment_intent_id: str, amount_to_capture: int+) -> Tuple[Optional[StripeObject], Optional[StripeError]]:+ try:+ with stripe_opentracing_trace("stripe.PaymentIntent.capture"):+ payment_intent = stripe.PaymentIntent.capture(+ payment_intent_id,+ amount_to_capture=amount_to_capture,+ api_key=api_key,+ stripe_version=STRIPE_API_VERSION,+ )+ return payment_intent, None+ except StripeError as error:+ logger.warning(+ "Unable to capture a payment intent",+ extra=_extra_log_data(error),+ )+ return None, error+++def refund_payment_intent(+ api_key: str, payment_intent_id: str, amount_to_refund: int+) -> Tuple[Optional[StripeObject], Optional[StripeError]]:+ try:+ with stripe_opentracing_trace("stripe.Refund.create"):+ refund = stripe.Refund.create(+ payment_intent=payment_intent_id,+ amount=amount_to_refund,+ api_key=api_key,+ stripe_version=STRIPE_API_VERSION,+ )+ return refund, None+ except StripeError as error:+ logger.warning(+ "Unable to refund a payment intent",+ extra=_extra_log_data(error),+ )+ return None, error+++def cancel_payment_intent(+ api_key: str, payment_intent_id: str+) -> Tuple[Optional[StripeObject], Optional[StripeError]]:+ try:+ with stripe_opentracing_trace("stripe.PaymentIntent.cancel"):+ payment_intent = stripe.PaymentIntent.cancel(+ payment_intent_id,+ api_key=api_key,+ stripe_version=STRIPE_API_VERSION,+ )+ return payment_intent, None+ except StripeError as error:+ logger.warning(+ "Unable to cancel a payment intent",+ extra=_extra_log_data(error),+ )++ return None, error+++def construct_stripe_event(+ api_key: str, payload: bytes, sig_header: str, endpoint_secret: str+) -> StripeObject:+ with stripe_opentracing_trace("stripe.Webhook.construct_event"):+ return stripe.Webhook.construct_event(+ payload, sig_header, endpoint_secret, api_key=api_key+ )+++def get_payment_method_details(+ payment_intent: StripeObject,+) -> Optional[PaymentMethodInfo]:+ charges = payment_intent.get("charges", None)+ payment_method_info = None+ if charges:+ charges_data = charges.get("data", [])+ if not charges_data:+ return None+ payment_method_details = charges_data[-1]+ if payment_method_details.get("type") == "card":+ card_details = payment_method_details.get("card", {})+ exp_year = card_details.get("exp_year", "")+ 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_info = PaymentMethodInfo(+ last_4=card_details.get("last4", ""),+ exp_year=exp_year,+ exp_month=exp_month,+ brand=card_details.get("brand", ""),+ type="card",+ )+ return payment_method_infodiff --git a/saleor/payment/gateways/stripe/tests/conftest.py b/saleor/payment/gateways/stripe/tests/conftest.pynew file mode 100644index 0000000000..fa047a36a2--- /dev/null+++ b/saleor/payment/gateways/stripe/tests/conftest.py@@ -0,0 +1,101 @@+import pytest++from .....checkout import calculations+from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines+from .....plugins.manager import get_plugins_manager+from .....plugins.models import PluginConfiguration+from .... import TransactionKind+from ....models import Transaction+from ....utils import create_payment+from ..plugin import StripeGatewayPlugin+++def payment_stripe_for_checkout(checkout_with_items, address, shipping_method):+ checkout_with_items.billing_address = address+ checkout_with_items.shipping_address = address+ checkout_with_items.shipping_method = shipping_method+ checkout_with_items.email = "[email protected]"+ checkout_with_items.save()+ manager = get_plugins_manager()+ lines = fetch_checkout_lines(checkout_with_items)+ checkout_info = fetch_checkout_info(checkout_with_items, lines, [], manager)+ total = calculations.calculate_checkout_total_with_gift_cards(+ manager, checkout_info, lines, address+ )+ payment = create_payment(+ gateway=StripeGatewayPlugin.PLUGIN_ID,+ payment_token="ABC",+ total=total.gross.amount,+ currency=checkout_with_items.currency,+ email=checkout_with_items.email,+ customer_ip_address="",+ checkout=checkout_with_items,+ )+ return payment+++def payment_stripe_for_order(payment_stripe_for_checkout, order_with_lines):+ payment_stripe_for_checkout.checkout = None+ payment_stripe_for_checkout.order = order_with_lines+ payment_stripe_for_checkout.total = order_with_lines.total_gross_amount+ payment_stripe_for_checkout.save()++ Transaction.objects.create(+ payment=payment_stripe_for_checkout,+ action_required=False,+ kind=TransactionKind.AUTH,+ token="token",+ is_success=True,+ amount=order_with_lines.total_gross_amount,+ currency=order_with_lines.currency,+ error="",+ gateway_response={},+ action_required_data={},+ )+ return payment_stripe_for_checkout+++def stripe_plugin(settings, monkeypatch, channel_USD):+ def fun(+ public_api_key=None,+ secret_api_key=None,+ webhook_endpoint_id="12345",+ webhook_secret_key="ABCD",+ active=True,+ auto_capture=True,+ ):+ public_api_key = public_api_key or "test_key"+ secret_api_key = secret_api_key or "secret_key"++ settings.PLUGINS = ["saleor.payment.gateways.stripe.plugin.StripeGatewayPlugin"]++ configuration = [+ {"name": "public_api_key", "value": public_api_key},+ {"name": "secret_api_key", "value": secret_api_key},+ {"name": "automatic_payment_capture", "value": auto_capture},+ {"name": "supported_currencies", "value": "USD"},+ ]+ if webhook_endpoint_id:+ configuration.append(+ {"name": "webhook_endpoint_id", "value": webhook_endpoint_id}+ )+ if webhook_secret_key:+ configuration.append(+ {"name": "webhook_secret_key", "value": webhook_secret_key}+ )+ PluginConfiguration.objects.create(+ identifier=StripeGatewayPlugin.PLUGIN_ID,+ name=StripeGatewayPlugin.PLUGIN_NAME,+ description="",+ active=active,+ channel=channel_USD,+ configuration=configuration,+ )++ manager = get_plugins_manager()+ return manager.plugins_per_channel[channel_USD.slug][0]++ return fundiff --git a/saleor/payment/gateways/stripe/tests/test_plugin.py b/saleor/payment/gateways/stripe/tests/test_plugin.pynew file mode 100644index 0000000000..2229e3c6fb--- /dev/null+++ b/saleor/payment/gateways/stripe/tests/test_plugin.py@@ -0,0 +1,1174 @@+import warnings+from unittest.mock import Mock, patch++import pytest+from django.core.exceptions import ValidationError+from stripe.error import AuthenticationError, StripeError+from stripe.stripe_object import StripeObject++from .....plugins.models import PluginConfiguration+from .... import TransactionKind+from ....interface import GatewayResponse+from ....utils import (+ create_payment_information,+ create_transaction,+ price_to_minor_unit,+)+from ..consts import (+ ACTION_REQUIRED_STATUSES,+ AUTHORIZED_STATUS,+ AUTOMATIC_CAPTURE_METHOD,+ MANUAL_CAPTURE_METHOD,+ PROCESSING_STATUS,+ STRIPE_API_VERSION,+ SUCCESS_STATUS,+)+++@patch("saleor.payment.gateways.stripe.stripe_api.stripe.WebhookEndpoint.list")+def test_validate_plugin_configuration_correct_configuration(+ mocked_stripe, stripe_plugin+):+ plugin = stripe_plugin(+ public_api_key="public",+ secret_api_key="ABC",+ active=True,+ )+ configuration = PluginConfiguration.objects.get()+ plugin.validate_plugin_configuration(configuration)++ assert mocked_stripe.called+++@patch("saleor.payment.gateways.stripe.stripe_api.stripe.WebhookEndpoint.list")+def test_validate_plugin_configuration_incorrect_configuration(+ mocked_stripe, stripe_plugin+):+ mocked_stripe.side_effect = AuthenticationError()+ plugin = stripe_plugin(+ public_api_key="public",+ secret_api_key="wrong",+ active=True,+ )+ configuration = PluginConfiguration.objects.get()+ with pytest.raises(ValidationError):+ plugin.validate_plugin_configuration(configuration)++ assert mocked_stripe.called+++@patch("saleor.payment.gateways.stripe.stripe_api.stripe.WebhookEndpoint.list")+def test_validate_plugin_configuration_missing_required_fields(+ mocked_stripe, stripe_plugin+):+ plugin = stripe_plugin(+ secret_api_key="wrong",+ active=True,+ )+ configuration = PluginConfiguration.objects.get()++ for config_field in configuration.configuration:+ if config_field["name"] == "public_api_key":+ config_field["value"] = None+ break+ with pytest.raises(ValidationError):+ plugin.validate_plugin_configuration(configuration)++ assert not mocked_stripe.called+++@patch("saleor.payment.gateways.stripe.stripe_api.stripe.WebhookEndpoint.list")+def test_validate_plugin_configuration_validate_only_when_active(+ mocked_stripe, stripe_plugin+):+ plugin = stripe_plugin(+ secret_api_key="wrong",+ active=False,+ )+ configuration = PluginConfiguration.objects.get()++ for config_field in configuration.configuration:+ if config_field["name"] == "public_api_key":+ config_field["value"] = None+ break++ plugin.validate_plugin_configuration(configuration)++ assert not mocked_stripe.called+++@patch("saleor.payment.gateways.stripe.stripe_api.stripe.WebhookEndpoint.delete")+def test_pre_save_plugin_configuration_removes_webhook_when_disabled(+ mocked_stripe, stripe_plugin+):+ plugin = stripe_plugin(+ active=False, webhook_secret_key="secret", webhook_endpoint_id="endpoint"+ )+ configuration = PluginConfiguration.objects.get()+ plugin.pre_save_plugin_configuration(configuration)++ assert all(+ [+ c_field["value"] != "endpoint"+ for c_field in configuration.configuration+ if c_field["name"] == "webhook_endpoint_id"+ ]+ )+ assert all(+ [+ c_field["name"] != "webhook_secret_key"+ for c_field in configuration.configuration+ ]+ )+ assert mocked_stripe.called+++def get_field_from_plugin_configuration(+ plugin_configuration: PluginConfiguration, field_name: str+):+ configuration = plugin_configuration.configuration+ for config_field in configuration:+ if config_field["name"] == field_name:+ return config_field+ return None+++@patch("saleor.payment.gateways.stripe.stripe_api.stripe.WebhookEndpoint.create")+def test_pre_save_plugin_configuration(mocked_stripe, stripe_plugin):+ webhook_object = StripeObject(id="stripe_webhook_id", last_response={})+ webhook_object.secret = "stripe_webhook_secret"+ mocked_stripe.return_value = webhook_object++ plugin = stripe_plugin(+ active=True, webhook_endpoint_id=None, webhook_secret_key=None+ )+ configuration = PluginConfiguration.objects.get()+ plugin.pre_save_plugin_configuration(configuration)++ webhook_id = get_field_from_plugin_configuration(+ configuration, "webhook_endpoint_id"+ )+ webhook_secret = get_field_from_plugin_configuration(+ configuration, "webhook_secret_key"+ )++ assert webhook_id["value"] == "stripe_webhook_id"+ assert webhook_secret["value"] == "stripe_webhook_secret"++ assert mocked_stripe.called+++@patch("saleor.payment.gateways.stripe.stripe_api.stripe.Customer.create")+@patch("saleor.payment.gateways.stripe.stripe_api.stripe.PaymentIntent.create")+def test_process_payment(+ mocked_payment_intent,+ mocked_customer,+ stripe_plugin,+ payment_stripe_for_checkout,+ channel_USD,+):+ 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 = "requires_payment_method"++ plugin = stripe_plugin(auto_capture=True)++ payment_info = create_payment_information(+ payment_stripe_for_checkout,+ )++ response = plugin.process_payment(payment_info, None)++ assert response.is_success is True+ assert response.action_required is True+ assert response.kind == TransactionKind.ACTION_TO_CONFIRM+ 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,+ 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,+ )+ assert not mocked_customer.called+++@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(+ mocked_payment_intent,+ mocked_customer_create,+ stripe_plugin,+ payment_stripe_for_checkout,+ channel_USD,+ customer_user,+):+ customer = StripeObject(id="cus_id")+ 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 = "requires_payment_method"++ 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,+ )++ response = plugin.process_payment(payment_info, None)++ assert response.is_success is True+ assert response.action_required is True+ assert response.kind == TransactionKind.ACTION_TO_CONFIRM+ 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,+ metadata={+ "channel": channel_USD.slug,+ "payment_id": payment_info.graphql_payment_id,+ },+ receipt_email=customer_user.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,+ )+++@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,+ )+++@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_payment_method(+ 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={"payment_method_id": "pm_ID"},+ )++ 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,+ payment_method="pm_ID",+ off_session=False,+ 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,+ )+++@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_payment_method_types(+ 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_stripe_for_checkout.save()+ payment_info = create_payment_information(+ payment_stripe_for_checkout,+ customer_id=None,+ store_source=True,+ additional_data={"payment_method_types": ["p24", "card"]},+ )++ 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,+ metadata={+ "channel": channel_USD.slug,+ "payment_id": payment_info.graphql_payment_id,+ },+ payment_method_types=["p24", "card"],+ 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,+ )+++@patch("saleor.payment.gateways.stripe.stripe_api.stripe.Customer.create")+@patch("saleor.payment.gateways.stripe.stripe_api.stripe.PaymentIntent.create")+def test_process_payment_offline(+ 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={"payment_method_id": "pm_ID", "off_session": True},+ )++ 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,+ payment_method="pm_ID",+ confirm=True,+ off_session=True,+ 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,+ )+++@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_payment_method_raises_card_error(+ 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()+ stripe_error_object = StripeError()+ stripe_error_object.error = StripeError()+ stripe_error_object.error.payment_intent = payment_intent+ mocked_payment_intent.side_effect = stripe_error_object++ 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={"payment_method_id": "pm_ID", "off_session": True},+ )++ 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,+ payment_method="pm_ID",+ confirm=True,+ off_session=True,+ 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,+ )+++@patch("saleor.payment.gateways.stripe.stripe_api.stripe.PaymentIntent.create")+def test_process_payment_with_disabled_order_auto_confirmation(+ mocked_payment_intent,+ stripe_plugin,+ payment_stripe_for_checkout,+ site_settings,+ channel_USD,+):+ 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 = "requires_payment_method"++ plugin = stripe_plugin(auto_capture=True)++ payment_info = create_payment_information(+ payment_stripe_for_checkout,+ )+ site_settings.automatically_confirm_all_new_orders = False+ site_settings.save()+ response = plugin.process_payment(payment_info, None)++ assert response.is_success is True+ assert response.action_required is True+ assert response.kind == TransactionKind.ACTION_TO_CONFIRM+ 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=MANUAL_CAPTURE_METHOD,+ 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,+ )+++@patch("saleor.payment.gateways.stripe.stripe_api.stripe.PaymentIntent.create")+def test_process_payment_with_manual_capture(+ mocked_payment_intent, stripe_plugin, payment_stripe_for_checkout, channel_USD+):+ 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++ plugin = stripe_plugin(auto_capture=False)++ payment_info = create_payment_information(+ payment_stripe_for_checkout,+ )++ plugin.process_payment(payment_info, None)++ 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=MANUAL_CAPTURE_METHOD,+ 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,+ )+++@patch("saleor.payment.gateways.stripe.stripe_api.stripe.PaymentIntent.create")+def test_process_payment_with_error(+ mocked_payment_intent, stripe_plugin, payment_stripe_for_checkout, channel_USD+):+ mocked_payment_intent.side_effect = StripeError(message="stripe-error")++ plugin = stripe_plugin()++ payment_info = create_payment_information(+ payment_stripe_for_checkout,+ )++ response = plugin.process_payment(payment_info, None)++ assert response.is_success is False+ assert response.action_required is True+ assert response.kind == TransactionKind.ACTION_TO_CONFIRM+ assert response.amount == payment_info.amount+ assert response.currency == payment_info.currency+ assert response.transaction_id == ""+ assert response.error == "stripe-error"+ assert response.raw_response is None+ assert response.action_required_data == {"client_secret": None, "id": None}++ 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,+ 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,+ )++[email protected]("kind", [TransactionKind.AUTH, TransactionKind.CAPTURE])+def test_confirm_payment_for_webhook(kind, stripe_plugin, payment_stripe_for_checkout):+ payment_intent_id = "payment-intent-id"+ gateway_response = {+ "id": "evt_1Ip9ANH1Vac4G4dbE9ch7zGS",+ }+ payment = payment_stripe_for_checkout+ payment.transactions.create(+ is_success=True,+ action_required=False,+ kind=kind,+ token=payment_intent_id,+ gateway_response=gateway_response,+ amount=payment.total,+ currency=payment.currency,+ )++ payment_info = create_payment_information(+ payment_stripe_for_checkout,+ )++ plugin = stripe_plugin()+ response = plugin.confirm_payment(payment_info, None)++ assert response.is_success is True+ assert response.action_required is False+ assert response.kind == kind+ 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 == gateway_response+ assert response.action_required_data is None+ assert response.transaction_already_processed is True+++ "kind, status",+ [+ (TransactionKind.AUTH, AUTHORIZED_STATUS),+ (TransactionKind.CAPTURE, SUCCESS_STATUS),+ ],+)+@patch("saleor.payment.gateways.stripe.stripe_api.stripe.PaymentIntent.retrieve")+def test_confirm_payment(+ mocked_intent_retrieve, kind, status, stripe_plugin, payment_stripe_for_checkout+):+ gateway_response = {+ "id": "evt_1Ip9ANH1Vac4G4dbE9ch7zGS",+ }++ payment_intent_id = "payment-intent-id"++ payment = payment_stripe_for_checkout+ payment.transactions.create(+ is_success=True,+ action_required=False,+ kind=TransactionKind.ACTION_TO_CONFIRM,+ token=payment_intent_id,+ gateway_response=gateway_response,+ amount=payment.total,+ currency=payment.currency,+ )++ payment_intent = StripeObject(id=payment_intent_id)+ payment_intent["amount"] = price_to_minor_unit(payment.total, payment.currency)+ payment_intent["status"] = status+ payment_intent["currency"] = payment.currency+ mocked_intent_retrieve.return_value = payment_intent++ payment_info = create_payment_information(+ payment_stripe_for_checkout, payment_token=payment_intent_id+ )++ plugin = stripe_plugin()+ response = plugin.confirm_payment(payment_info, None)++ assert response.is_success is True+ assert response.action_required is False+ assert response.kind == kind+ assert response.amount == payment.total+ assert response.currency == payment.currency+ assert response.transaction_id == payment_intent_id+ assert response.error is None+++@patch("saleor.payment.gateways.stripe.stripe_api.stripe.PaymentIntent.retrieve")+def test_confirm_payment_incorrect_payment_intent(+ mocked_intent_retrieve, stripe_plugin, payment_stripe_for_checkout+):++ gateway_response = {+ "id": "evt_1Ip9ANH1Vac4G4dbE9ch7zGS",+ }++ payment_intent_id = "payment-intent-id"++ payment = payment_stripe_for_checkout+ payment.transactions.create(+ is_success=True,+ action_required=False,+ kind=TransactionKind.ACTION_TO_CONFIRM,+ token=payment_intent_id,+ gateway_response=gateway_response,+ amount=payment.total,+ currency=payment.currency,+ )++ mocked_intent_retrieve.side_effect = StripeError(message="stripe-error")++ payment_info = create_payment_information(+ payment_stripe_for_checkout, payment_token=payment_intent_id+ )++ plugin = stripe_plugin()+ with warnings.catch_warnings(record=True):+ response = plugin.confirm_payment(payment_info, None)++ assert response.is_success is False+ assert response.action_required is False+ assert response.kind == TransactionKind.AUTH+ assert response.amount == payment.total+ assert response.currency == payment.currency+ assert response.transaction_id == ""+ assert response.error == "stripe-error"++[email protected]("status", ACTION_REQUIRED_STATUSES)+@patch("saleor.payment.gateways.stripe.stripe_api.stripe.PaymentIntent.retrieve")+def test_confirm_payment_action_required_status(+ mocked_intent_retrieve, status, stripe_plugin, payment_stripe_for_checkout+):+ gateway_response = {+ "id": "evt_1Ip9ANH1Vac4G4dbE9ch7zGS",+ }++ payment_intent_id = "payment-intent-id"++ payment = payment_stripe_for_checkout+ payment.transactions.create(+ is_success=True,+ action_required=False,+ kind=TransactionKind.ACTION_TO_CONFIRM,+ token=payment_intent_id,+ gateway_response=gateway_response,+ amount=payment.total,+ currency=payment.currency,+ )++ payment_intent = StripeObject(id=payment_intent_id)+ payment_intent["capture_method"] = "automatic"+ payment_intent["amount"] = price_to_minor_unit(payment.total, payment.currency)+ payment_intent["status"] = status+ payment_intent["currency"] = payment.currency+ mocked_intent_retrieve.return_value = payment_intent++ payment_info = create_payment_information(+ payment_stripe_for_checkout, payment_token=payment_intent_id+ )++ plugin = stripe_plugin()+ response = plugin.confirm_payment(payment_info, None)++ assert response.is_success is True+ assert response.action_required is True+ assert response.kind == TransactionKind.ACTION_TO_CONFIRM+ assert response.amount == payment.total+ assert response.currency == payment.currency+ assert response.transaction_id == payment_intent_id+ assert response.error is None+++@patch("saleor.payment.gateways.stripe.stripe_api.stripe.PaymentIntent.retrieve")+def test_confirm_payment_processing_status(+ mocked_intent_retrieve, stripe_plugin, payment_stripe_for_checkout+):+ gateway_response = {+ "id": "evt_1Ip9ANH1Vac4G4dbE9ch7zGS",+ }++ payment_intent_id = "payment-intent-id"++ payment = payment_stripe_for_checkout+ payment.transactions.create(+ is_success=True,+ action_required=False,+ kind=TransactionKind.ACTION_TO_CONFIRM,+ token=payment_intent_id,+ gateway_response=gateway_response,+ amount=payment.total,+ currency=payment.currency,+ )++ payment_intent = StripeObject(id=payment_intent_id)+ payment_intent["capture_method"] = "automatic"+ payment_intent["amount"] = price_to_minor_unit(payment.total, payment.currency)+ payment_intent["status"] = PROCESSING_STATUS+ payment_intent["currency"] = payment.currency+ mocked_intent_retrieve.return_value = payment_intent++ payment_info = create_payment_information(+ payment_stripe_for_checkout, payment_token=payment_intent_id+ )++ plugin = stripe_plugin()+ response = plugin.confirm_payment(payment_info, None)++ assert response.is_success is True+ assert response.action_required is False+ assert response.kind == TransactionKind.PENDING+ assert response.amount == payment.total+ assert response.currency == payment.currency+ assert response.transaction_id == payment_intent_id+ assert response.error is None+++@patch("saleor.payment.gateways.stripe.stripe_api.stripe.PaymentIntent.capture")+def test_capture_payment(+ mocked_capture, payment_stripe_for_order, order_with_lines, stripe_plugin+):+ payment = payment_stripe_for_order++ payment_intent_id = "ABC"+ 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["last_response"] = StripeObject()+ payment_intent["last_response"]["data"] = {"response": "json"}++ mocked_capture.return_value = payment_intent++ payment_info = create_payment_information(+ payment,+ payment_token=payment_intent_id,+ )+ gateway_response = GatewayResponse(+ kind=TransactionKind.AUTH,+ action_required=False,+ transaction_id=payment_intent_id,+ is_success=True,+ amount=payment_info.amount,+ currency=payment_info.currency,+ error="",+ raw_response={},+ )++ create_transaction(+ payment=payment,+ payment_information=payment_info,+ kind=TransactionKind.AUTH,+ gateway_response=gateway_response,+ )++ plugin = stripe_plugin()++ response = plugin.capture_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.total+ assert response.currency == order_with_lines.currency+ assert response.transaction_id == payment_intent_id+++@patch("saleor.payment.gateways.stripe.stripe_api.stripe.Refund.create")+def test_refund_payment(+ mocked_refund, payment_stripe_for_order, order_with_lines, stripe_plugin+):+ payment = payment_stripe_for_order++ payment_intent_id = "ABC"+ refund_object = StripeObject(id=payment_intent_id)+ refund_object["amount"] = price_to_minor_unit(payment.total, payment.currency)+ refund_object["status"] = SUCCESS_STATUS+ refund_object["currency"] = payment.currency+ refund_object["last_response"] = StripeObject()+ refund_object["last_response"]["data"] = {"response": "json"}++ mocked_refund.return_value = refund_object++ payment_info = create_payment_information(+ payment,+ payment_token=payment_intent_id,+ )+ gateway_response = GatewayResponse(+ kind=TransactionKind.CAPTURE,+ action_required=False,+ transaction_id=payment_intent_id,+ is_success=True,+ amount=payment_info.amount,+ currency=payment_info.currency,+ error="",+ raw_response={},+ )++ create_transaction(+ payment=payment,+ payment_information=payment_info,+ kind=TransactionKind.CAPTURE,+ gateway_response=gateway_response,+ )++ plugin = stripe_plugin()++ response = plugin.refund_payment(payment_info, None)++ assert response.is_success is True+ assert response.action_required is False+ assert response.kind == TransactionKind.REFUND+ assert response.amount == payment.total+ assert response.currency == order_with_lines.currency+ assert response.transaction_id == payment_intent_id+++@patch("saleor.payment.gateways.stripe.stripe_api.stripe.PaymentIntent.cancel")+def test_void_payment(+ mocked_cancel, payment_stripe_for_order, order_with_lines, stripe_plugin+):+ payment = payment_stripe_for_order++ payment_intent_id = "ABC"+ 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["last_response"] = StripeObject()+ payment_intent["last_response"]["data"] = {"response": "json"}++ mocked_cancel.return_value = payment_intent++ payment_info = create_payment_information(+ payment,+ payment_token=payment_intent_id,+ )+ gateway_response = GatewayResponse(+ kind=TransactionKind.AUTH,+ action_required=False,+ transaction_id=payment_intent_id,+ is_success=True,+ amount=payment_info.amount,+ currency=payment_info.currency,+ error="",+ raw_response={},+ )++ create_transaction(+ payment=payment,+ payment_information=payment_info,+ kind=TransactionKind.AUTH,+ gateway_response=gateway_response,+ )++ plugin = stripe_plugin()++ response = plugin.void_payment(payment_info, None)++ assert response.is_success is True+ assert response.action_required is False+ assert response.kind == TransactionKind.VOID+ assert response.amount == payment.total+ assert response.currency == order_with_lines.currency+ assert response.transaction_id == payment_intent_iddiff --git a/saleor/payment/gateways/stripe/tests/test_stripe_api.py b/saleor/payment/gateways/stripe/tests/test_stripe_api.pynew file mode 100644index 0000000000..481506cb34--- /dev/null+++ b/saleor/payment/gateways/stripe/tests/test_stripe_api.py@@ -0,0 +1,515 @@+from decimal import Decimal+from unittest.mock import patch++from stripe.error import AuthenticationError, StripeError+from stripe.stripe_object import StripeObject++from saleor.payment.interface import PaymentMethodInfo+from saleor.payment.utils import price_to_minor_unit++from ..consts import (+ AUTOMATIC_CAPTURE_METHOD,+ MANUAL_CAPTURE_METHOD,+ METADATA_IDENTIFIER,+ STRIPE_API_VERSION,+ WEBHOOK_EVENTS,+)+from ..stripe_api import (+ cancel_payment_intent,+ capture_payment_intent,+ create_payment_intent,+ delete_webhook,+ get_or_create_customer,+ get_payment_method_details,+ is_secret_api_key_valid,+ list_customer_payment_methods,+ refund_payment_intent,+ retrieve_payment_intent,+ subscribe_webhook,+)+++@patch(+ "saleor.payment.gateways.stripe.stripe_api.stripe.WebhookEndpoint",+)+def test_is_secret_api_key_valid_incorrect_key(mocked_webhook):+ api_key = "incorrect"+ mocked_webhook.list.side_effect = AuthenticationError()+ assert is_secret_api_key_valid(api_key) is False+++@patch(+ "saleor.payment.gateways.stripe.stripe_api.stripe.WebhookEndpoint",+)+def test_is_secret_api_key_valid_correct_key(mocked_webhook):+ api_key = "correct_key"+ assert is_secret_api_key_valid(api_key) is True++ mocked_webhook.list.assert_called_with(api_key, stripe_version=STRIPE_API_VERSION)+++@patch(+ "saleor.payment.gateways.stripe.stripe_api.stripe.WebhookEndpoint",+)+def test_subscribe_webhook_returns_webhook_object(mocked_webhook, channel_USD):+ api_key = "api_key"+ expected_url = (+ "http://mirumee.com/plugins/channel/main/saleor.payments.stripe/webhooks/"+ )++ subscribe_webhook(api_key, channel_slug=channel_USD.slug)++ mocked_webhook.create.assert_called_with(+ api_key=api_key,+ url=expected_url,+ enabled_events=WEBHOOK_EVENTS,+ metadata={METADATA_IDENTIFIER: "mirumee.com"},+ stripe_version=STRIPE_API_VERSION,+ )+++@patch(+ "saleor.payment.gateways.stripe.stripe_api.stripe.WebhookEndpoint",+)+def test_delete_webhook(mocked_webhook):+ api_key = "api_key"++ delete_webhook(api_key, "webhook_id")++ mocked_webhook.delete.assert_called_with(+ "webhook_id", api_key=api_key, stripe_version=STRIPE_API_VERSION+ )+++@patch(+ "saleor.payment.gateways.stripe.stripe_api.stripe.PaymentIntent",+)+def test_create_payment_intent_returns_intent_object(mocked_payment_intent):+ api_key = "api_key"+ mocked_payment_intent.create.return_value = StripeObject()++ intent, error = create_payment_intent(+ api_key, Decimal(10), "USD", auto_capture=True+ )++ mocked_payment_intent.create.assert_called_with(+ api_key=api_key,+ amount="1000",+ currency="USD",+ capture_method=AUTOMATIC_CAPTURE_METHOD,+ stripe_version=STRIPE_API_VERSION,+ )++ assert isinstance(intent, StripeObject)+ assert error is None+++@patch(+ "saleor.payment.gateways.stripe.stripe_api.stripe.PaymentIntent",+)+def test_create_payment_intent_with_customer(mocked_payment_intent):+ customer = StripeObject(id="c_ABC")+ api_key = "api_key"+ mocked_payment_intent.create.return_value = StripeObject()++ intent, error = create_payment_intent(+ api_key, Decimal(10), "USD", auto_capture=True, customer=customer+ )++ mocked_payment_intent.create.assert_called_with(+ api_key=api_key,+ amount="1000",+ currency="USD",+ capture_method=AUTOMATIC_CAPTURE_METHOD,+ customer=customer,+ stripe_version=STRIPE_API_VERSION,+ )++ assert isinstance(intent, StripeObject)+ assert error is None+++@patch(+ "saleor.payment.gateways.stripe.stripe_api.stripe.PaymentIntent",+)+def test_create_payment_intent_manual_auto_capture(mocked_payment_intent):+ api_key = "api_key"+ mocked_payment_intent.create.return_value = StripeObject()++ _intent, _error = create_payment_intent(+ api_key, Decimal(10), "USD", auto_capture=False+ )++ mocked_payment_intent.create.assert_called_with(+ api_key=api_key,+ amount="1000",+ currency="USD",+ capture_method=MANUAL_CAPTURE_METHOD,+ stripe_version=STRIPE_API_VERSION,+ )+++@patch(+ "saleor.payment.gateways.stripe.stripe_api.stripe.PaymentIntent",+)+def test_create_payment_intent_returns_error(mocked_payment_intent):+ api_key = "api_key"+ mocked_payment_intent.create.side_effect = StripeError(+ json_body={"error": "stripe-error"}+ )++ intent, error = create_payment_intent(api_key, Decimal(10), "USD")++ mocked_payment_intent.create.assert_called_with(+ api_key=api_key,+ amount="1000",+ currency="USD",+ capture_method=AUTOMATIC_CAPTURE_METHOD,+ stripe_version=STRIPE_API_VERSION,+ )+ assert intent is None+ assert error+++@patch(+ "saleor.payment.gateways.stripe.stripe_api.stripe.PaymentIntent",+)+def test_retrieve_payment_intent(mocked_payment_intent):+ api_key = "api_key"+ payment_intent_id = "id1234"++ mocked_payment_intent.retrieve.return_value = StripeObject()++ intent, _ = retrieve_payment_intent(api_key, payment_intent_id)++ mocked_payment_intent.retrieve.assert_called_with(+ payment_intent_id, api_key=api_key, stripe_version=STRIPE_API_VERSION+ )+ assert isinstance(intent, StripeObject)+++@patch(+ "saleor.payment.gateways.stripe.stripe_api.stripe.PaymentIntent",+)+def test_retrieve_payment_intent_stripe_returns_error(mocked_payment_intent):+ api_key = "api_key"+ payment_intent_id = "id1234"++ expected_error = StripeError(message="stripe-error")+ mocked_payment_intent.retrieve.side_effect = expected_error++ _, error = retrieve_payment_intent(api_key, payment_intent_id)++ mocked_payment_intent.retrieve.assert_called_with(+ payment_intent_id, api_key=api_key, stripe_version=STRIPE_API_VERSION+ )++ assert error == expected_error+++@patch(+ "saleor.payment.gateways.stripe.stripe_api.stripe.PaymentIntent",+)+def test_capture_payment_intent(mocked_payment_intent):+ api_key = "api_key"+ payment_intent_id = "id1234"+ amount = price_to_minor_unit(Decimal("10.0"), "USD")++ mocked_payment_intent.capture.return_value = StripeObject()++ intent, _ = capture_payment_intent(+ api_key=api_key, payment_intent_id=payment_intent_id, amount_to_capture=amount+ )++ mocked_payment_intent.capture.assert_called_with(+ payment_intent_id,+ amount_to_capture=amount,+ api_key=api_key,+ stripe_version=STRIPE_API_VERSION,+ )+ assert isinstance(intent, StripeObject)+++@patch(+ "saleor.payment.gateways.stripe.stripe_api.stripe.PaymentIntent",+)+def test_capture_payment_intent_stripe_returns_error(mocked_payment_intent):+ api_key = "api_key"+ payment_intent_id = "id1234"+ amount = price_to_minor_unit(Decimal("10.0"), "USD")++ expected_error = StripeError(message="stripe-error")+ mocked_payment_intent.capture.side_effect = expected_error++ _, error = capture_payment_intent(+ api_key=api_key, payment_intent_id=payment_intent_id, amount_to_capture=amount+ )++ mocked_payment_intent.capture.assert_called_with(+ payment_intent_id,+ amount_to_capture=amount,+ api_key=api_key,+ stripe_version=STRIPE_API_VERSION,+ )++ assert error == expected_error+++@patch(+ "saleor.payment.gateways.stripe.stripe_api.stripe.Refund",+)+def test_refund_payment_intent(mocked_refund):+ api_key = "api_key"+ payment_intent_id = "id1234"+ amount = price_to_minor_unit(Decimal("10.0"), "USD")++ mocked_refund.create.return_value = StripeObject()++ intent, _ = refund_payment_intent(+ api_key=api_key, payment_intent_id=payment_intent_id, amount_to_refund=amount+ )++ mocked_refund.create.assert_called_with(+ payment_intent=payment_intent_id,+ amount=amount,+ api_key=api_key,+ stripe_version=STRIPE_API_VERSION,+ )+ assert isinstance(intent, StripeObject)+++@patch(+ "saleor.payment.gateways.stripe.stripe_api.stripe.Refund",+)+def test_refund_payment_intent_returns_error(mocked_refund):+ api_key = "api_key"+ payment_intent_id = "id1234"+ amount = price_to_minor_unit(Decimal("10.0"), "USD")++ expected_error = StripeError(message="stripe-error")+ mocked_refund.create.side_effect = expected_error++ _, error = refund_payment_intent(+ api_key=api_key, payment_intent_id=payment_intent_id, amount_to_refund=amount+ )++ mocked_refund.create.assert_called_with(+ payment_intent=payment_intent_id,+ amount=amount,+ api_key=api_key,+ stripe_version=STRIPE_API_VERSION,+ )+ assert error == expected_error+++@patch(+ "saleor.payment.gateways.stripe.stripe_api.stripe.PaymentIntent",+)+def test_cancel_payment_intent(mocked_payment_intent):+ api_key = "api_key"+ payment_intent_id = "id1234"++ mocked_payment_intent.cancel.return_value = StripeObject()++ intent, _ = cancel_payment_intent(+ api_key=api_key, payment_intent_id=payment_intent_id+ )++ mocked_payment_intent.cancel.assert_called_with(+ payment_intent_id, api_key=api_key, stripe_version=STRIPE_API_VERSION+ )+ assert isinstance(intent, StripeObject)+++@patch(+ "saleor.payment.gateways.stripe.stripe_api.stripe.PaymentIntent",+)+def test_cancel_payment_intent_stripe_returns_error(mocked_payment_intent):+ api_key = "api_key"+ payment_intent_id = "id1234"++ expected_error = StripeError(message="stripe-error")+ mocked_payment_intent.cancel.side_effect = expected_error++ _, error = cancel_payment_intent(+ api_key=api_key, payment_intent_id=payment_intent_id+ )++ mocked_payment_intent.cancel.assert_called_with(+ payment_intent_id, api_key=api_key, stripe_version=STRIPE_API_VERSION+ )++ assert error == expected_error+++@patch(+ "saleor.payment.gateways.stripe.stripe_api.stripe.Customer",+)+def test_get_or_create_customer_retrieve(mocked_customer):+ mocked_customer.retrieve.return_value = StripeObject()+ api_key = "123"+ customer_email = "[email protected]"+ customer_id = "c_12345"++ customer = get_or_create_customer(+ api_key=api_key,+ customer_email=customer_email,+ customer_id=customer_id,+ )++ assert isinstance(customer, StripeObject)+ mocked_customer.retrieve.assert_called_with(+ customer_id, api_key=api_key, stripe_version=STRIPE_API_VERSION+ )+++@patch(+ "saleor.payment.gateways.stripe.stripe_api.stripe.Customer",+)+def test_get_or_create_customer_failed_retrieve(mocked_customer):++ expected_error = StripeError(message="stripe-error")+ mocked_customer.retrieve.side_effect = expected_error++ api_key = "123"+ customer_email = "[email protected]"+ customer_id = "c_12345"++ customer = get_or_create_customer(+ api_key=api_key,+ customer_email=customer_email,+ customer_id=customer_id,+ )++ assert customer is None+ mocked_customer.retrieve.assert_called_with(+ customer_id, api_key=api_key, stripe_version=STRIPE_API_VERSION+ )+++@patch(+ "saleor.payment.gateways.stripe.stripe_api.stripe.Customer",+)+def test_get_or_create_customer_create(mocked_customer):+ mocked_customer.create.return_value = StripeObject()+ api_key = "123"+ customer_email = "[email protected]"+ customer = get_or_create_customer(+ api_key=api_key,+ customer_email=customer_email,+ customer_id=None,+ )++ assert isinstance(customer, StripeObject)+ mocked_customer.create.assert_called_with(+ email=customer_email, api_key=api_key, stripe_version=STRIPE_API_VERSION+ )+++@patch(+ "saleor.payment.gateways.stripe.stripe_api.stripe.Customer",+)+def test_get_or_create_customer_failed_create(mocked_customer):+ expected_error = StripeError(message="stripe-error")+ mocked_customer.create.side_effect = expected_error++ api_key = "123"+ customer_email = "[email protected]"+ customer = get_or_create_customer(+ api_key=api_key,+ customer_email=customer_email,+ customer_id=None,+ )++ assert customer is None+ mocked_customer.create.assert_called_with(+ email=customer_email, api_key=api_key, stripe_version=STRIPE_API_VERSION+ )+++@patch(+ "saleor.payment.gateways.stripe.stripe_api.stripe.PaymentMethod",+)+def test_list_customer_payment_methods(mocked_payment_method):+ api_key = "123"+ customer_id = "c_customer_id"+ mocked_payment_method.list.return_value = StripeObject()++ payment_method, error = list_customer_payment_methods(+ api_key=api_key, customer_id=customer_id+ )++ assert error is None+ assert isinstance(payment_method, StripeObject)+ mocked_payment_method.list.assert_called_with(+ api_key=api_key,+ customer=customer_id,+ type="card",+ stripe_version=STRIPE_API_VERSION,+ )+++@patch(+ "saleor.payment.gateways.stripe.stripe_api.stripe.PaymentMethod",+)+def test_list_customer_payment_methods_failed_to_fetch(mocked_payment_method):+ api_key = "123"+ customer_id = "c_customer_id"++ expected_error = StripeError(message="stripe-error")+ mocked_payment_method.list.side_effect = expected_error++ payment_method, error = list_customer_payment_methods(+ api_key=api_key, customer_id=customer_id+ )++ assert payment_method is None+ assert isinstance(error, StripeError)++ mocked_payment_method.list.assert_called_with(+ api_key=api_key,+ customer=customer_id,+ type="card",+ stripe_version=STRIPE_API_VERSION,+ )+++def test_get_payment_method_details():+ payment_intent = StripeObject()+ payment_intent.charges = {+ "data": [+ {+ "type": "card",+ "card": {+ "last4": "1234",+ "exp_year": "2222",+ "exp_month": "12",+ "brand": "visa",+ },+ }+ ]+ }++ payment_method_info = get_payment_method_details(payment_intent)++ assert payment_method_info == PaymentMethodInfo(+ last_4="1234", exp_year=2222, exp_month=12, brand="visa", type="card"+ )+++def test_get_payment_method_details_missing_charges():+ payment_intent = StripeObject()+ payment_intent.charges = None++ payment_method_info = get_payment_method_details(payment_intent)++ assert payment_method_info is None+++def test_get_payment_method_details_missing_charges_data():+ payment_intent = StripeObject()+ payment_intent.charges = {"data": None}++ payment_method_info = get_payment_method_details(payment_intent)++ assert payment_method_info is Nonediff --git a/saleor/payment/gateways/stripe/tests/test_webhooks.py b/saleor/payment/gateways/stripe/tests/test_webhooks.pynew file mode 100644index 0000000000..1e2acc0948--- /dev/null+++ b/saleor/payment/gateways/stripe/tests/test_webhooks.py@@ -0,0 +1,505 @@+import json+from decimal import Decimal+from unittest.mock import Mock, patch++import pytest+from stripe.stripe_object import StripeObject++from .....checkout.complete_checkout import complete_checkout+from .... import ChargeStatus, TransactionKind+from ....utils import price_to_minor_unit+from ..consts import (+ AUTHORIZED_STATUS,+ FAILED_STATUSES,+ PROCESSING_STATUS,+ SUCCESS_STATUS,+ WEBHOOK_AUTHORIZED_EVENT,+ WEBHOOK_CANCELED_EVENT,+ WEBHOOK_FAILED_EVENT,+ WEBHOOK_PROCESSING_EVENT,+ WEBHOOK_SUCCESS_EVENT,+)+from ..webhooks import (+ handle_authorized_payment_intent,+ handle_failed_payment_intent,+ handle_processing_payment_intent,+ handle_refund,+ handle_successful_payment_intent,+)+++@patch(+ "saleor.payment.gateways.stripe.webhooks.complete_checkout", wraps=complete_checkout+)+def test_handle_successful_payment_intent_for_checkout(+ wrapped_checkout_complete,+ payment_stripe_for_checkout,+ checkout_with_items,+ stripe_plugin,+):+ 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["currency"] = payment.currency+ payment_intent["status"] = SUCCESS_STATUS+ handle_successful_payment_intent(payment_intent, plugin.config)++ payment.refresh_from_db()++ assert wrapped_checkout_complete.called+ assert payment.checkout_id is None+ assert payment.order+ assert payment.order.checkout_token == str(checkout_with_items.token)+ transaction = payment.transactions.get(kind=TransactionKind.CAPTURE)+ assert transaction.token == payment_intent.id+++@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,+):++ payment = payment_stripe_for_order+ plugin = stripe_plugin()+ payment_intent = StripeObject(id="ABC", last_response={})+ payment_intent["amount"] = payment.total+ payment_intent["currency"] = payment.currency+ payment_intent["capture_method"] = "automatic"+ handle_successful_payment_intent(payment_intent, plugin.config)++ assert wrapped_checkout_complete.called is False+++@patch(+ "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,+):+ payment = payment_stripe_for_order++ plugin = stripe_plugin()++ payment_intent = StripeObject(id="token", last_response={})+ payment_intent["amount_received"] = price_to_minor_unit(+ payment.total, payment.currency+ )+ payment_intent["currency"] = payment.currency+ payment_intent["status"] = SUCCESS_STATUS++ handle_successful_payment_intent(payment_intent, plugin.config)++ payment.refresh_from_db()++ assert payment.is_active+ assert payment.charge_status == ChargeStatus.FULLY_CHARGED+ assert payment.captured_amount == payment.total+ assert payment.transactions.filter(kind=TransactionKind.CAPTURE).exists()+ assert wrapped_checkout_complete.called is False+++@patch(+ "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,+):+ payment = payment_stripe_for_order+ transaction = payment.transactions.first()+ transaction.kind = TransactionKind.PENDING+ transaction.save()++ plugin = stripe_plugin()++ payment_intent = StripeObject(id="token", last_response={})+ payment_intent["amount_received"] = price_to_minor_unit(+ payment.total, payment.currency+ )+ payment_intent["currency"] = payment.currency+ payment_intent["status"] = SUCCESS_STATUS++ handle_successful_payment_intent(payment_intent, plugin.config)++ payment.refresh_from_db()++ assert payment.is_active+ assert payment.charge_status == ChargeStatus.FULLY_CHARGED+ assert payment.captured_amount == payment.total+ assert payment.transactions.filter(kind=TransactionKind.CAPTURE).exists()+ assert wrapped_checkout_complete.called is False+++@patch(+ "saleor.payment.gateways.stripe.webhooks.complete_checkout", wraps=complete_checkout+)+def test_handle_authorized_payment_intent_for_checkout(+ wrapped_checkout_complete,+ payment_stripe_for_checkout,+ checkout_with_items,+ stripe_plugin,+):+ 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"] = price_to_minor_unit(payment.total, payment.currency)+ payment_intent["currency"] = payment.currency+ payment_intent["status"] = AUTHORIZED_STATUS+ handle_authorized_payment_intent(payment_intent, plugin.config)++ payment.refresh_from_db()++ assert wrapped_checkout_complete.called+ assert payment.checkout_id is None+ assert payment.order+ assert payment.order.checkout_token == str(checkout_with_items.token)+ transaction = payment.transactions.get(kind=TransactionKind.AUTH)+ assert transaction.token == payment_intent.id+++@patch(+ "saleor.payment.gateways.stripe.webhooks.complete_checkout", wraps=complete_checkout+)+def test_handle_authorized_payment_intent_for_order(+ wrapped_checkout_complete,+ payment_stripe_for_order,+ checkout_with_items,+ stripe_plugin,+):++ payment = payment_stripe_for_order+ plugin = stripe_plugin()+ payment_intent = StripeObject(id="ABC", last_response={})+ payment_intent["amount"] = payment.total+ payment_intent["currency"] = payment.currency+ payment_intent["status"] = AUTHORIZED_STATUS+ handle_authorized_payment_intent(payment_intent, plugin.config)++ assert wrapped_checkout_complete.called is False+++@patch(+ "saleor.payment.gateways.stripe.webhooks.complete_checkout", wraps=complete_checkout+)+def test_handle_authorized_payment_intent_for_processing_order_payment(+ wrapped_checkout_complete,+ payment_stripe_for_order,+ checkout_with_items,+ stripe_plugin,+):++ payment = payment_stripe_for_order+ payment.charge_status = ChargeStatus.PENDING+ plugin = stripe_plugin()+ payment_intent = StripeObject(id="ABC", last_response={})+ payment_intent["amount"] = payment.total+ payment_intent["currency"] = payment.currency+ payment_intent["status"] = AUTHORIZED_STATUS+ handle_authorized_payment_intent(payment_intent, plugin.config)++ assert wrapped_checkout_complete.called is False+++@patch(+ "saleor.payment.gateways.stripe.webhooks.complete_checkout", wraps=complete_checkout+)+def test_handle_processing_payment_intent_for_order(+ wrapped_checkout_complete,+ payment_stripe_for_order,+ checkout_with_items,+ stripe_plugin,+):++ payment = payment_stripe_for_order+ plugin = stripe_plugin()+ payment_intent = StripeObject(id="ABC", last_response={})+ payment_intent["amount"] = payment.total+ payment_intent["currency"] = payment.currency+ payment_intent["status"] = PROCESSING_STATUS+ handle_processing_payment_intent(payment_intent, plugin.config)++ assert wrapped_checkout_complete.called is False+++@patch(+ "saleor.payment.gateways.stripe.webhooks.complete_checkout", wraps=complete_checkout+)+def test_handle_processing_payment_intent_for_checkout(+ wrapped_checkout_complete,+ payment_stripe_for_checkout,+ checkout_with_items,+ stripe_plugin,+):+ 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"] = price_to_minor_unit(payment.total, payment.currency)+ payment_intent["currency"] = payment.currency+ payment_intent["status"] = PROCESSING_STATUS+ handle_processing_payment_intent(payment_intent, plugin.config)++ payment.refresh_from_db()++ assert wrapped_checkout_complete.called+ assert payment.checkout_id is None+ assert payment.order+ assert payment.order.checkout_token == str(checkout_with_items.token)+ transaction = payment.transactions.get(kind=TransactionKind.PENDING)+ assert transaction.token == payment_intent.id+++def test_handle_failed_payment_intent_for_checkout(+ stripe_plugin, payment_stripe_for_checkout+):+ payment = payment_stripe_for_checkout+ 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"] = payment.total+ payment_intent["currency"] = payment.currency+ payment_intent["status"] = FAILED_STATUSES[0]++ handle_failed_payment_intent(payment_intent, plugin.config)++ payment.refresh_from_db()++ assert not payment.order_id+ assert not payment.is_active+ assert payment.charge_status == ChargeStatus.CANCELLED+ assert payment.transactions.filter(kind=TransactionKind.CANCEL).exists()+++def test_handle_failed_payment_intent_for_order(+ stripe_plugin, payment_stripe_for_order+):+ payment = payment_stripe_for_order+ 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"] = payment.total+ payment_intent["currency"] = payment.currency+ payment_intent["status"] = FAILED_STATUSES[0]++ handle_failed_payment_intent(payment_intent, plugin.config)++ payment.refresh_from_db()++ assert not payment.is_active+ assert payment.charge_status == ChargeStatus.CANCELLED+ assert payment.transactions.filter(kind=TransactionKind.CANCEL).exists()+++def test_handle_fully_refund(stripe_plugin, payment_stripe_for_order):+ payment = payment_stripe_for_order+ payment.captured_amount = payment.total+ payment.save()+ payment.transactions.create(+ is_success=True,+ action_required=True,+ kind=TransactionKind.CAPTURE,+ amount=payment.total,+ currency=payment.currency,+ token="ABC",+ gateway_response={},+ )+ plugin = stripe_plugin()++ refund = StripeObject(id="refund_id")+ refund["amount"] = price_to_minor_unit(payment.total, payment.currency)+ refund["currency"] = payment.currency+ refund["last_response"] = None++ charge = StripeObject()+ charge["payment_intent"] = "ABC"+ charge["refunds"] = StripeObject()+ charge["refunds"]["data"] = [refund]++ handle_refund(charge, plugin.config)++ payment.refresh_from_db()++ assert payment.charge_status == ChargeStatus.FULLY_REFUNDED+ assert payment.is_active is False+ assert payment.captured_amount == Decimal("0")+++def test_handle_partial_refund(stripe_plugin, payment_stripe_for_order):+ payment = payment_stripe_for_order+ payment.captured_amount = payment.total+ payment.save()+ payment.transactions.create(+ is_success=True,+ action_required=True,+ kind=TransactionKind.CAPTURE,+ amount=payment.total,+ currency=payment.currency,+ token="ABC",+ gateway_response={},+ )+ plugin = stripe_plugin()++ refund = StripeObject(id="refund_id")+ refund["amount"] = price_to_minor_unit(Decimal("10"), payment.currency)+ refund["currency"] = payment.currency+ refund["last_response"] = None++ charge = StripeObject()+ charge["payment_intent"] = "ABC"+ charge["refunds"] = StripeObject()+ charge["refunds"]["data"] = [refund]++ handle_refund(charge, plugin.config)++ payment.refresh_from_db()++ assert payment.charge_status == ChargeStatus.PARTIALLY_REFUNDED+ assert payment.is_active is True+ assert payment.captured_amount == payment.total - Decimal("10")+++def test_handle_refund_already_processed(stripe_plugin, payment_stripe_for_order):+ payment = payment_stripe_for_order+ payment.charge_status = ChargeStatus.PARTIALLY_REFUNDED+ payment.captured_amount = payment.total - Decimal("10")+ payment.save()++ refund_id = "refund_abc"+ payment.transactions.create(+ is_success=True,+ action_required=True,+ kind=TransactionKind.REFUND,+ amount=payment.total,+ currency=payment.currency,+ token=refund_id,+ gateway_response={},+ )+ plugin = stripe_plugin()++ refund = StripeObject(id=refund_id)+ refund["amount"] = price_to_minor_unit(Decimal("10"), payment.currency)+ refund["currency"] = payment.currency+ refund["last_response"] = None++ charge = StripeObject()+ charge["payment_intent"] = "ABC"+ charge["refunds"] = StripeObject()+ charge["refunds"]["data"] = [refund]++ handle_refund(charge, plugin.config)++ payment.refresh_from_db()++ assert payment.charge_status == ChargeStatus.PARTIALLY_REFUNDED+ assert payment.is_active is True+ assert payment.captured_amount == payment.total - Decimal("10")+++ "webhook_type, fun_to_mock",+ [+ (WEBHOOK_SUCCESS_EVENT, "handle_successful_payment_intent"),+ (WEBHOOK_PROCESSING_EVENT, "handle_processing_payment_intent"),+ (WEBHOOK_FAILED_EVENT, "handle_failed_payment_intent"),+ (WEBHOOK_AUTHORIZED_EVENT, "handle_authorized_payment_intent"),+ (WEBHOOK_CANCELED_EVENT, "handle_failed_payment_intent"),+ ],+)+@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+):+ dummy_payload = {+ "id": "evt_1Ip9ANH1Vac4G4dbE9ch7zGS",+ }++ request = rf.post(+ path="/webhooks/", data=dummy_payload, content_type="application/json"+ )++ stripe_signature = "1234"+ request.META["HTTP_STRIPE_SIGNATURE"] = stripe_signature++ event = Mock()+ event.type = webhook_type+ event.data.object = StripeObject()++ mocked_webhook_event.return_value = event++ plugin = stripe_plugin()++ 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)++ api_key = plugin.config.connection_params["secret_api_key"]+ endpoint_secret = plugin.config.connection_params["webhook_secret"]++ mocked_webhook_event.assert_called_once_with(+ json.dumps(dummy_payload).encode("utf-8"),+ stripe_signature,+ endpoint_secret,+ api_key=api_key,+ )diff --git a/saleor/payment/gateways/stripe/webhooks.py b/saleor/payment/gateways/stripe/webhooks.pynew file mode 100644index 0000000000..4a9ad05b34--- /dev/null+++ b/saleor/payment/gateways/stripe/webhooks.py@@ -0,0 +1,343 @@+import logging+from typing import Optional++from django.contrib.auth.models import AnonymousUser+from django.core.handlers.wsgi import WSGIRequest+from django.http import HttpResponse+from stripe.error import SignatureVerificationError+from stripe.stripe_object import StripeObject++from ....checkout.complete_checkout import complete_checkout+from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines+from ....checkout.models import Checkout+from ....core.transactions import transaction_with_commit_on_errors+from ....discount.utils import fetch_active_discounts+from ....order.actions import order_captured, order_refunded, order_voided+from ....plugins.manager import get_plugins_manager+from ... import ChargeStatus, TransactionKind+from ...interface import GatewayConfig, GatewayResponse+from ...models import Payment+from ...utils import create_transaction, gateway_postprocess, price_from_minor_unit+from .consts import (+ WEBHOOK_AUTHORIZED_EVENT,+ WEBHOOK_CANCELED_EVENT,+ WEBHOOK_FAILED_EVENT,+ WEBHOOK_PROCESSING_EVENT,+ WEBHOOK_REFUND_EVENT,+ WEBHOOK_SUCCESS_EVENT,+)+from .stripe_api import construct_stripe_event++logger = logging.getLogger(__name__)+++@transaction_with_commit_on_errors()+def handle_webhook(request: WSGIRequest, gateway_config: "GatewayConfig"):+ payload = request.body+ sig_header = request.META["HTTP_STRIPE_SIGNATURE"]+ endpoint_secret = gateway_config.connection_params["webhook_secret"]+ api_key = gateway_config.connection_params["secret_api_key"]+ try:+ event = construct_stripe_event(+ api_key=api_key,+ payload=payload,+ sig_header=sig_header,+ endpoint_secret=endpoint_secret,+ )+ except ValueError as e:+ # Invalid payload+ logger.warning(+ "Received invalid payload for Stripe webhook", extra={"error": e}+ )+ return HttpResponse(status=400)+ except SignatureVerificationError as e:+ # Invalid signature+ logger.warning("Invalid signature for Stripe webhook", extra={"error": e})+ return HttpResponse(status=400)++ webhook_handlers = {+ WEBHOOK_SUCCESS_EVENT: handle_successful_payment_intent,+ WEBHOOK_AUTHORIZED_EVENT: handle_authorized_payment_intent,+ WEBHOOK_PROCESSING_EVENT: handle_processing_payment_intent,+ WEBHOOK_FAILED_EVENT: handle_failed_payment_intent,+ WEBHOOK_CANCELED_EVENT: handle_failed_payment_intent,+ WEBHOOK_REFUND_EVENT: handle_refund,+ }+ if event.type in webhook_handlers:+ logger.debug(+ "Processing new Stripe webhook",+ extra={"event_type": event.type, "event_id": event.id},+ )+ webhook_handlers[event.type](event.data.object, gateway_config)+ else:+ logger.warning(+ "Received unhandled webhook events", extra={"event_type": event.type}+ )+ return HttpResponse(status=200)+++def _get_payment(payment_intent_id: str) -> Optional[Payment]:+ return (+ Payment.objects.prefetch_related(+ "checkout",+ )+ .select_for_update(of=("self",))+ .filter(transactions__token=payment_intent_id, is_active=True)+ .first()+ )+++def _get_checkout(payment_id: int) -> Optional[Checkout]:+ return (+ Checkout.objects.prefetch_related("payments")+ .select_for_update(of=("self",))+ .filter(payments__id=payment_id, payments__is_active=True)+ .first()+ )+++def _finalize_checkout(+ checkout: Checkout,+ payment: Payment,+ payment_intent: StripeObject,+ kind: str,+ amount: str,+ currency: str,+):+ gateway_response = GatewayResponse(+ kind=kind,+ action_required=False,+ transaction_id=payment_intent.id,+ is_success=True,+ amount=price_from_minor_unit(amount, currency),+ currency=payment_intent.currency,+ error=None,+ raw_response=payment_intent.last_response,+ psp_reference=payment_intent.id,+ )++ create_transaction(+ payment,+ kind=kind,+ payment_information=None, # type: ignore+ action_required=False,+ gateway_response=gateway_response,+ )++ manager = get_plugins_manager()+ discounts = fetch_active_discounts()+ lines = fetch_checkout_lines(checkout) # type: ignore+ checkout_info = fetch_checkout_info(+ checkout, lines, discounts, manager # type: ignore+ )+ order, _, _ = complete_checkout(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ payment_data={},+ store_source=False,+ discounts=discounts,+ user=checkout.user or AnonymousUser(), # type: ignore+ )+++def _update_payment_with_new_transaction(+ payment: Payment, stripe_object: StripeObject, kind: str, amount: str, currency: str+):+ gateway_response = GatewayResponse(+ kind=kind,+ action_required=False,+ transaction_id=stripe_object.id,+ is_success=True,+ amount=price_from_minor_unit(amount, currency),+ currency=currency,+ error=None,+ raw_response=stripe_object.last_response,+ psp_reference=stripe_object.id,+ )+ transaction = create_transaction(+ payment,+ kind=kind,+ payment_information=None, # type: ignore+ action_required=False,+ gateway_response=gateway_response,+ )+ gateway_postprocess(transaction, payment)++ return transaction+++def _process_payment_with_checkout(+ payment: Payment,+ payment_intent: StripeObject,+ kind: str,+ amount: str,+ currency: str,+):+ checkout = _get_checkout(payment.id)++ if checkout:+ _finalize_checkout(checkout, payment, payment_intent, kind, amount, currency)+++def handle_authorized_payment_intent(+ payment_intent: StripeObject, gateway_config: "GatewayConfig"+):+ payment = _get_payment(payment_intent.id)++ if not payment:+ logger.warning(+ "Payment for PaymentIntent was not found",+ extra={"payment_intent": payment_intent.id},+ )+ return+ if payment.order_id:+ if payment.charge_status == ChargeStatus.PENDING:+ _update_payment_with_new_transaction(+ payment,+ payment_intent,+ TransactionKind.AUTH,+ payment_intent.amount,+ payment_intent.currency,+ )+ # Order already created+ return++ if payment.checkout_id:+ _process_payment_with_checkout(+ payment,+ payment_intent,+ kind=TransactionKind.AUTH,+ amount=payment_intent.amount,+ currency=payment_intent.currency,+ )+++def handle_failed_payment_intent(+ payment_intent: StripeObject, gateway_config: "GatewayConfig"+):+ payment = _get_payment(payment_intent.id)++ if not payment:+ logger.warning(+ "Payment for PaymentIntent was not found",+ extra={"payment_intent": payment_intent.id},+ )+ return+ _update_payment_with_new_transaction(+ payment,+ payment_intent,+ TransactionKind.CANCEL,+ payment_intent.amount,+ payment_intent.currency,+ )+ if payment.order:+ order_voided(payment.order, None, payment, get_plugins_manager())+++def handle_processing_payment_intent(+ payment_intent: StripeObject, gateway_config: "GatewayConfig"+):+ payment = _get_payment(payment_intent.id)++ if not payment:+ logger.warning(+ "Payment for PaymentIntent was not found",+ extra={"payment_intent": payment_intent.id},+ )+ return+ if payment.order_id:+ # Order already created+ return++ if payment.checkout_id:+ _process_payment_with_checkout(+ payment,+ payment_intent,+ TransactionKind.PENDING,+ amount=payment_intent.amount,+ currency=payment_intent.currency,+ )+++def handle_successful_payment_intent(+ payment_intent: StripeObject, gateway_config: "GatewayConfig"+):+ payment = _get_payment(payment_intent.id)++ if not payment:+ logger.warning(+ "Payment for PaymentIntent was not found",+ extra={"payment_intent": payment_intent.id},+ )+ return+ if payment.order_id:+ if payment.charge_status in [ChargeStatus.PENDING, ChargeStatus.NOT_CHARGED]:+ capture_transaction = _update_payment_with_new_transaction(+ payment,+ payment_intent,+ TransactionKind.CAPTURE,+ payment_intent.amount_received,+ payment_intent.currency,+ )+ order_captured(+ payment.order, # type: ignore+ None,+ capture_transaction.amount,+ payment,+ get_plugins_manager(),+ )+ return++ if payment.checkout_id:+ _process_payment_with_checkout(+ payment,+ payment_intent,+ TransactionKind.CAPTURE,+ amount=payment_intent.amount_received,+ currency=payment_intent.currency,+ )+++def handle_refund(charge: StripeObject, gateway_config: "GatewayConfig"):+ payment_intent_id = charge.payment_intent+ payment = _get_payment(payment_intent_id)++ refund = charge.refunds.data[0]+ if not payment:+ logger.warning(+ "Payment for PaymentIntent was not found",+ extra={"payment_intent": payment_intent_id},+ )+ return++ already_processed = payment.transactions.filter(token=refund.id).exists()++ if already_processed:+ logger.debug(+ "Refund already processed",+ extra={+ "refund": refund.id,+ "payment": payment.id,+ "payment_intent_id": payment_intent_id,+ },+ )+ return++ if payment.charge_status in ChargeStatus.FULLY_REFUNDED:+ logger.info(+ "Order already fully refunded", extra={"order_id": payment.order_id}+ )+ return++ refund_transaction = _update_payment_with_new_transaction(+ payment, refund, TransactionKind.REFUND, refund.amount, refund.currency+ )+ if payment.order:+ order_refunded(+ payment.order,+ None,+ refund_transaction.amount,+ payment,+ get_plugins_manager(),+ )diff --git a/saleor/payment/interface.py b/saleor/payment/interface.pyindex dff6f001d6..4860ead03e 100644--- a/saleor/payment/interface.py+++ b/saleor/payment/interface.py@@ -77,9 +77,10 @@ class PaymentData:customer_ip_address: Optional[str]customer_email: strtoken: Optional[str] = None- customer_id: Optional[str] = None+ customer_id: Optional[str] = None # stores payment gateway customer IDreuse_source: bool = Falsedata: Optional[dict] = None+ graphql_customer_id: Optional[str] = None@dataclassdiff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex fb163ac411..9085f1fc7f 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -4,10 +4,12 @@ from decimal import Decimalfrom typing import TYPE_CHECKING, Dict, List, Optionalimport graphene+from babel.numbers import get_currency_precisionfrom django.core.serializers.json import DjangoJSONEncoderfrom ..account.models import Userfrom ..checkout.models import Checkout+from ..core.prices import quantize_pricefrom ..core.tracing import traced_atomic_transactionfrom ..order.models import Orderfrom . import ChargeStatus, GatewayError, PaymentError, TransactionKind@@ -42,12 +44,14 @@ def create_payment_information(billing = checkout.billing_addressshipping = checkout.shipping_addressemail = checkout.get_customer_email()+ user_id = checkout.user_idelif payment.order:billing = payment.order.billing_addressshipping = payment.order.shipping_addressemail = payment.order.user_email+ user_id = payment.order.user_idelse:- billing, shipping, email = None, None, payment.billing_email+ billing, shipping, email, user_id = None, None, payment.billing_email, Nonebilling_address = AddressData(**billing.as_data()) if billing else Noneshipping_address = AddressData(**shipping.as_data()) if shipping else None@@ -55,6 +59,10 @@ def create_payment_information(order_id = payment.order.pk if payment.order else Nonegraphql_payment_id = graphene.Node.to_global_id("Payment", payment.pk)+ graphql_customer_id = None+ if user_id:+ graphql_customer_id = graphene.Node.to_global_id("User", user_id)+return PaymentData(gateway=payment.gateway,token=payment_token,@@ -70,6 +78,7 @@ def create_payment_information(customer_email=email,reuse_source=store_source,data=additional_data or {},+ graphql_customer_id=graphql_customer_id,)@@ -294,6 +303,7 @@ def gateway_postprocess(transaction, payment):payment.captured_amount -= transaction.amountpayment.charge_status = ChargeStatus.PARTIALLY_REFUNDEDif payment.captured_amount <= 0:+ payment.captured_amount = Decimal("0.0")payment.charge_status = ChargeStatus.FULLY_REFUNDEDpayment.is_active = Falsechanged_fields += ["charge_status", "is_active"]@@ -302,7 +312,8 @@ def gateway_postprocess(transaction, payment):changed_fields += ["charge_status"]elif transaction_kind == TransactionKind.CANCEL:payment.charge_status = ChargeStatus.CANCELLED- changed_fields += ["charge_status"]+ payment.is_active = False+ changed_fields += ["charge_status", "is_active"]elif transaction_kind == TransactionKind.CAPTURE_FAILED:if payment.charge_status in {ChargeStatus.PARTIALLY_CHARGED,@@ -386,3 +397,29 @@ def is_currency_supported(currency: str, gateway_id: str, manager: "PluginsManag"""Return true if the given gateway supports given currency."""available_gateways = manager.list_payment_gateways(currency=currency)return any([gateway.id == gateway_id for gateway in available_gateways])+++def price_from_minor_unit(value: str, currency: str):+ """Convert minor unit (smallest unit of currency) to decimal value.++ (value: 1000, currency: USD) will be converted to 10.00+ """++ value = Decimal(value)+ precision = get_currency_precision(currency)+ number_places = Decimal(10) ** -precision+ return value * number_places+++def price_to_minor_unit(value: Decimal, currency: str):+ """Convert decimal value to the smallest unit of currency.++ Take the value, discover the precision of currency and multiply value by+ Decimal('10.0'), then change quantization to remove the comma.+ Decimal(10.0) -> str(1000)+ """+ value = quantize_price(value, currency=currency)+ precision = get_currency_precision(currency)+ number_places = Decimal("10.0") ** precision+ value_without_comma = value * number_places+ return str(value_without_comma.quantize(Decimal("1")))diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.pyindex 520f2e62c5..ed1eac3bf7 100644--- a/saleor/plugins/base_plugin.py+++ b/saleor/plugins/base_plugin.py@@ -703,6 +703,14 @@ class BasePlugin:"""return+ @classmethod+ def pre_save_plugin_configuration(cls, plugin_configuration: "PluginConfiguration"):+ """Trigger before plugin configuration will be saved.++ Overwrite this method if you need to trigger specific logic before saving a+ plugin configuration.+ """+@classmethoddef save_plugin_configuration(cls, plugin_configuration: "PluginConfiguration", cleaned_data@@ -714,6 +722,7 @@ class BasePlugin:if "active" in cleaned_data:plugin_configuration.active = cleaned_data["active"]cls.validate_plugin_configuration(plugin_configuration)+ cls.pre_save_plugin_configuration(plugin_configuration)plugin_configuration.save()if plugin_configuration.configuration:# Let's add a translated descriptions and labels@@ -729,11 +738,20 @@ class BasePlugin:configuration with current values and provide access to it via API."""config_structure = getattr(cls, "CONFIG_STRUCTURE") or {}+ fields_without_structure = []for configuration_field in configuration:structure_to_add = config_structure.get(configuration_field.get("name"))if structure_to_add:configuration_field.update(structure_to_add)+ else:+ fields_without_structure.append(configuration_field)++ if fields_without_structure:+ [+ configuration.remove(field) # type: ignore+ for field in fields_without_structure+ ]@classmethoddef _update_configuration_structure(cls, configuration: PluginConfigurationType):diff --git a/saleor/settings.py b/saleor/settings.pyindex 6d68dd4ce1..1175c990a4 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -564,6 +564,7 @@ PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin","saleor.payment.gateways.dummy.plugin.DummyGatewayPlugin","saleor.payment.gateways.dummy_credit_card.plugin.DummyCreditCardGatewayPlugin",+ "saleor.payment.gateways.stripe.deprecated.plugin.DeprecatedStripeGatewayPlugin","saleor.payment.gateways.stripe.plugin.StripeGatewayPlugin","saleor.payment.gateways.braintree.plugin.BraintreeGatewayPlugin","saleor.payment.gateways.razorpay.plugin.RazorpayGatewayPlugin",