Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Use separate services for external integrations
Patryk Zawadzki9abf7176cfdc
diff --git a/saleor/payment/gateways/adyen/plugin.py b/saleor/payment/gateways/adyen/plugin.pyindex 41e077dccd..e0d5189c82 100644--- a/saleor/payment/gateways/adyen/plugin.py+++ b/saleor/payment/gateways/adyen/plugin.py@@ -3,6 +3,8 @@ from typing import List, Optionalfrom urllib.parse import urlencodeimport Adyen+import opentracing+import opentracing.tagsfrom django.contrib.auth.hashers import make_passwordfrom django.contrib.sites.models import Sitefrom django.core.exceptions import ObjectDoesNotExist, ValidationError@@ -226,10 +228,16 @@ class AdyenGatewayPlugin(BasePlugin):if path.startswith(WEBHOOK_PATH):return handle_webhook(request, config)elif path.startswith(ADDITIONAL_ACTION_PATH):- return handle_additional_actions(- request,- self.adyen.checkout.payments_details,- )+ with opentracing.global_tracer().start_active_span(+ "adyen.checkout.payment_details"+ ) as scope:+ span = scope.span+ span.set_tag(opentracing.tags.COMPONENT, "payment")+ span.set_tag("service.name", "adyen")+ return handle_additional_actions(+ request,+ self.adyen.checkout.payments_details,+ )return HttpResponseNotFound()def _get_gateway_config(self) -> GatewayConfig:@@ -265,7 +273,13 @@ class AdyenGatewayPlugin(BasePlugin):request = request_data_for_gateway_config(checkout, config.connection_params["merchant_account"])- response = api_call(request, self.adyen.checkout.payment_methods)+ with opentracing.global_tracer().start_active_span(+ "adyen.checkout.payment_methods"+ ) as scope:+ span = scope.span+ span.set_tag(opentracing.tags.COMPONENT, "payment")+ span.set_tag("service.name", "adyen")+ response = api_call(request, self.adyen.checkout.payment_methods)return PaymentGateway(id=self.PLUGIN_ID,name=self.PLUGIN_NAME,@@ -314,7 +328,13 @@ class AdyenGatewayPlugin(BasePlugin):merchant_account=self.config.connection_params["merchant_account"],native_3d_secure=self.config.connection_params["enable_native_3d_secure"],)- result = api_call(request_data, self.adyen.checkout.payments)+ with opentracing.global_tracer().start_active_span(+ "adyen.checkout.payments"+ ) as scope:+ span = scope.span+ span.set_tag(opentracing.tags.COMPONENT, "payment")+ span.set_tag("service.name", "adyen")+ result = api_call(request_data, self.adyen.checkout.payments)result_code = result.message["resultCode"].strip().lower()is_success = result_code not in FAILED_STATUSESadyen_auto_capture = self.config.connection_params["adyen_auto_capture"]@@ -384,7 +404,13 @@ class AdyenGatewayPlugin(BasePlugin):if not additional_data:raise PaymentError("Unable to finish the payment.")- result = api_call(additional_data, self.adyen.checkout.payments_details)+ with opentracing.global_tracer().start_active_span(+ "adyen.checkout.payment_details"+ ) as scope:+ span = scope.span+ span.set_tag(opentracing.tags.COMPONENT, "payment")+ span.set_tag("service.name", "adyen")+ result = api_call(additional_data, self.adyen.checkout.payments_details)result_code = result.message["resultCode"].strip().lower()is_success = result_code not in FAILED_STATUSESaction_required = "action" in result.message@@ -530,7 +556,13 @@ class AdyenGatewayPlugin(BasePlugin):merchant_account=self.config.connection_params["merchant_account"],token=transaction.token,)- result = api_call(request, self.adyen.payment.refund)+ with opentracing.global_tracer().start_active_span(+ "adyen.payment.refund"+ ) as scope:+ span = scope.span+ span.set_tag(opentracing.tags.COMPONENT, "payment")+ span.set_tag("service.name", "adyen")+ result = api_call(request, self.adyen.payment.refund)amount = payment_information.amountcurrency = payment_information.currency@@ -596,7 +628,13 @@ class AdyenGatewayPlugin(BasePlugin):merchant_account=self.config.connection_params["merchant_account"],token=payment_information.token, # type: ignore)- result = api_call(request, self.adyen.payment.cancel)+ with opentracing.global_tracer().start_active_span(+ "adyen.payment.cancel"+ ) as scope:+ span = scope.span+ span.set_tag(opentracing.tags.COMPONENT, "payment")+ span.set_tag("service.name", "adyen")+ result = api_call(request, self.adyen.payment.cancel)return GatewayResponse(is_success=True,diff --git a/saleor/payment/gateways/adyen/utils/common.py b/saleor/payment/gateways/adyen/utils/common.pyindex 0ff83735e6..70066664fb 100644--- a/saleor/payment/gateways/adyen/utils/common.py+++ b/saleor/payment/gateways/adyen/utils/common.py@@ -4,6 +4,8 @@ from decimal import Decimalfrom typing import TYPE_CHECKING, Any, Callable, Dict, Optionalimport Adyen+import opentracing+import opentracing.tagsfrom babel.numbers import get_currency_precisionfrom django.conf import settingsfrom django_countries.fields import Country@@ -360,7 +362,13 @@ def call_capture(merchant_account=merchant_account,token=token,)- return api_call(request, adyen_client.payment.capture)+ with opentracing.global_tracer().start_active_span(+ "adyen.payment.capture"+ ) as scope:+ span = scope.span+ span.set_tag(opentracing.tags.COMPONENT, "payment")+ span.set_tag("service.name", "adyen")+ return api_call(request, adyen_client.payment.capture)def request_for_payment_cancel(diff --git a/saleor/payment/gateways/braintree/__init__.py b/saleor/payment/gateways/braintree/__init__.pyindex f0cd61eefb..50988c8178 100644--- a/saleor/payment/gateways/braintree/__init__.py+++ b/saleor/payment/gateways/braintree/__init__.py@@ -1,6 +1,8 @@from typing import Dict, List, Optionalimport braintree as braintree_sdk+import opentracing+import opentracing.tagsfrom django.core.exceptions import ImproperlyConfiguredfrom ... import TransactionKind@@ -107,10 +109,16 @@ def get_client_token(config: GatewayConfig, token_config: Optional[TokenConfig] = None) -> str:gateway = get_braintree_gateway(**config.connection_params)- if not token_config:- return gateway.client_token.generate()- parameters = create_token_params(config, token_config)- return gateway.client_token.generate(parameters)+ with opentracing.global_tracer().start_active_span(+ "braintree.client_token.generate"+ ) as scope:+ span = scope.span+ span.set_tag(opentracing.tags.COMPONENT, "payment")+ span.set_tag("service.name", "braintree")+ if not token_config:+ return gateway.client_token.generate()+ parameters = create_token_params(config, token_config)+ return gateway.client_token.generate(parameters)def create_token_params(config: GatewayConfig, token_config: TokenConfig) -> dict:@@ -163,42 +171,61 @@ def transaction_for_new_customer(payment_information: PaymentData, config: GatewayConfig):gateway = get_braintree_gateway(**config.connection_params)- return gateway.transaction.sale(- {- "amount": str(payment_information.amount),- "payment_method_nonce": payment_information.token,- "options": {- "submit_for_settlement": config.auto_capture,- "store_in_vault_on_success": payment_information.reuse_source,- "three_d_secure": {"required": config.require_3d_secure},- },- **get_customer_data(payment_information),- }- )++ with opentracing.global_tracer().start_active_span(+ "braintree.transaction.sale"+ ) as scope:+ span = scope.span+ span.set_tag(opentracing.tags.COMPONENT, "payment")+ span.set_tag("service.name", "braintree")+ return gateway.transaction.sale(+ {+ "amount": str(payment_information.amount),+ "payment_method_nonce": payment_information.token,+ "options": {+ "submit_for_settlement": config.auto_capture,+ "store_in_vault_on_success": payment_information.reuse_source,+ "three_d_secure": {"required": config.require_3d_secure},+ },+ **get_customer_data(payment_information),+ }+ )def transaction_for_existing_customer(payment_information: PaymentData, config: GatewayConfig):gateway = get_braintree_gateway(**config.connection_params)- return gateway.transaction.sale(- {- "amount": str(payment_information.amount),- "customer_id": payment_information.customer_id,- "options": {"submit_for_settlement": config.auto_capture},- **get_customer_data(payment_information),- }- )+ with opentracing.global_tracer().start_active_span(+ "braintree.transaction.sale"+ ) as scope:+ span = scope.span+ span.set_tag(opentracing.tags.COMPONENT, "payment")+ span.set_tag("service.name", "braintree")+ return gateway.transaction.sale(+ {+ "amount": str(payment_information.amount),+ "customer_id": payment_information.customer_id,+ "options": {"submit_for_settlement": config.auto_capture},+ **get_customer_data(payment_information),+ }+ )def capture(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:gateway = get_braintree_gateway(**config.connection_params)try:- result = gateway.transaction.submit_for_settlement(- transaction_id=payment_information.token,- amount=str(payment_information.amount),- )+ with opentracing.global_tracer().start_active_span(+ "braintree.transaction.submit_for_settlement"+ ) as scope:+ span = scope.span+ span.set_tag(opentracing.tags.COMPONENT, "payment")+ span.set_tag("service.name", "braintree")+ result = gateway.transaction.submit_for_settlement(+ transaction_id=payment_information.token,+ amount=str(payment_information.amount),+ )except braintree_sdk.exceptions.NotFoundError:raise BraintreeException(DEFAULT_ERROR_MESSAGE)@@ -223,7 +250,13 @@ def void(payment_information: PaymentData, config: GatewayConfig) -> GatewayRespgateway = get_braintree_gateway(**config.connection_params)try:- result = gateway.transaction.void(transaction_id=payment_information.token)+ with opentracing.global_tracer().start_active_span(+ "braintree.transaction.void"+ ) as scope:+ span = scope.span+ span.set_tag(opentracing.tags.COMPONENT, "payment")+ span.set_tag("service.name", "braintree")+ result = gateway.transaction.void(transaction_id=payment_information.token)except braintree_sdk.exceptions.NotFoundError:raise BraintreeException(DEFAULT_ERROR_MESSAGE)@@ -248,10 +281,16 @@ def refund(payment_information: PaymentData, config: GatewayConfig) -> GatewayRegateway = get_braintree_gateway(**config.connection_params)try:- result = gateway.transaction.refund(- transaction_id=payment_information.token,- amount_or_options=str(payment_information.amount),- )+ with opentracing.global_tracer().start_active_span(+ "braintree.transaction.refund"+ ) as scope:+ span = scope.span+ span.set_tag(opentracing.tags.COMPONENT, "payment")+ span.set_tag("service.name", "braintree")+ result = gateway.transaction.refund(+ transaction_id=payment_information.token,+ amount_or_options=str(payment_information.amount),+ )except braintree_sdk.exceptions.NotFoundError:raise BraintreeException(DEFAULT_ERROR_MESSAGE)@@ -283,7 +322,13 @@ def list_client_sources(config: GatewayConfig, customer_id: str) -> List[CustomerSource]:gateway = get_braintree_gateway(**config.connection_params)- customer = gateway.customer.find(customer_id)+ with opentracing.global_tracer().start_active_span(+ "braintree.customer.find"+ ) as scope:+ span = scope.span+ span.set_tag(opentracing.tags.COMPONENT, "payment")+ span.set_tag("service.name", "braintree")+ customer = gateway.customer.find(customer_id)if not customer:return []return [diff --git a/saleor/payment/gateways/razorpay/__init__.py b/saleor/payment/gateways/razorpay/__init__.pyindex e6e3e6ea9b..7f87ed78a7 100644--- a/saleor/payment/gateways/razorpay/__init__.py+++ b/saleor/payment/gateways/razorpay/__init__.py@@ -3,6 +3,8 @@ import uuidfrom decimal import Decimalfrom typing import Dict+import opentracing+import opentracing.tagsimport razorpayimport razorpay.errors@@ -96,9 +98,15 @@ def capture(payment_information: PaymentData, config: GatewayConfig) -> GatewayRif not error:try:- response = razorpay_client.payment.capture(- payment_information.token, razorpay_amount- )+ with opentracing.global_tracer().start_active_span(+ "razorpay.payment.capture"+ ) as scope:+ span = scope.span+ span.set_tag(opentracing.tags.COMPONENT, "payment")+ span.set_tag("service.name", "razorpay")+ response = razorpay_client.payment.capture(+ payment_information.token, razorpay_amount+ )clean_razorpay_response(response)except RAZORPAY_EXCEPTIONS as exc:error = get_error_message_from_razorpay_error(exc)@@ -136,9 +144,15 @@ def refund(payment_information: PaymentData, config: GatewayConfig) -> GatewayRerazorpay_client = get_client(**config.connection_params)razorpay_amount = get_amount_for_razorpay(payment_information.amount)try:- response = razorpay_client.payment.refund(- payment_information.token, razorpay_amount- )+ with opentracing.global_tracer().start_active_span(+ "razorpay.payment.refund"+ ) as scope:+ span = scope.span+ span.set_tag(opentracing.tags.COMPONENT, "payment")+ span.set_tag("service.name", "razorpay")+ response = razorpay_client.payment.refund(+ payment_information.token, razorpay_amount+ )clean_razorpay_response(response)except RAZORPAY_EXCEPTIONS as exc:error = get_error_message_from_razorpay_error(exc)diff --git a/saleor/payment/gateways/stripe/__init__.py b/saleor/payment/gateways/stripe/__init__.pyindex 76253932ab..0fa70070c8 100644--- a/saleor/payment/gateways/stripe/__init__.py+++ b/saleor/payment/gateways/stripe/__init__.py@@ -1,5 +1,7 @@from typing import List+import opentracing+import opentracing.tagsimport stripefrom ... import TransactionKind@@ -44,19 +46,31 @@ def authorize()try:- 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,- )+ 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:- customer = client.Customer.create(payment_method=intent.payment_method)+ 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.idexcept stripe.error.StripeError as exc:@@ -74,7 +88,13 @@ def capture(payment_information: PaymentData, config: GatewayConfig) -> GatewayRclient = _get_client(**config.connection_params)intent = Nonetry:- intent = client.PaymentIntent.retrieve(id=payment_information.token)+ 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@@ -98,7 +118,13 @@ def confirm(payment_information: PaymentData, config: GatewayConfig) -> GatewayRclient = _get_client(**config.connection_params)try:intent = client.PaymentIntent(id=payment_information.token)- intent.confirm()+ 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@@ -118,7 +144,13 @@ def refund(payment_information: PaymentData, config: GatewayConfig) -> GatewayRecurrency = get_currency_for_stripe(payment_information.currency)stripe_amount = get_amount_for_stripe(payment_information.amount, currency)try:- intent = client.PaymentIntent.retrieve(id=payment_information.token)+ 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(@@ -138,7 +170,13 @@ def refund(payment_information: PaymentData, config: GatewayConfig) -> GatewayRedef void(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:client = _get_client(**config.connection_params)try:- intent = client.PaymentIntent.retrieve(id=payment_information.token)+ 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(@@ -158,7 +196,13 @@ def list_client_sources(config: GatewayConfig, customer_id: str) -> List[CustomerSource]:client = _get_client(**config.connection_params)- cards = client.PaymentMethod.list(customer=customer_id, type="card")["data"]+ 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,diff --git a/saleor/plugins/avatax/__init__.py b/saleor/plugins/avatax/__init__.pyindex a01480011d..9f5548a96e 100644--- a/saleor/plugins/avatax/__init__.py+++ b/saleor/plugins/avatax/__init__.py@@ -6,6 +6,8 @@ from decimal import Decimalfrom typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Unionfrom urllib.parse import urljoin+import opentracing+import opentracing.tagsimport requestsfrom django.conf import settingsfrom django.contrib.sites.models import Site@@ -394,7 +396,13 @@ def _fetch_new_taxes_data(transaction_url = urljoin(get_api_url(config.use_sandbox), "transactions/createoradjust")- response = api_post_request(transaction_url, data, config)+ with opentracing.global_tracer().start_active_span(+ "avatax.transactions.crateoradjust"+ ) as scope:+ span = scope.span+ span.set_tag(opentracing.tags.COMPONENT, "tax")+ span.set_tag("service.name", "avatax")+ response = api_post_request(transaction_url, data, config)if response and "error" not in response:cache.set(data_cache_key, (data, response), CACHE_TIME)else:@@ -478,9 +486,15 @@ def get_cached_tax_codes_or_fetch(tax_codes = cache.get(TAX_CODES_CACHE_KEY, {})if not tax_codes:tax_codes_url = urljoin(get_api_url(config.use_sandbox), "definitions/taxcodes")- response = api_get_request(- tax_codes_url, config.username_or_account, config.password_or_license- )+ with opentracing.global_tracer().start_active_span(+ "avatax.definitions.taxcodes"+ ) as scope:+ span = scope.span+ span.set_tag(opentracing.tags.COMPONENT, "tax")+ span.set_tag("service.name", "avatax")+ response = api_get_request(+ tax_codes_url, config.username_or_account, config.password_or_license+ )if response and "error" not in response:tax_codes = generate_tax_codes_dict(response)cache.set(TAX_CODES_CACHE_KEY, tax_codes, cache_time)diff --git a/saleor/plugins/avatax/plugin.py b/saleor/plugins/avatax/plugin.pyindex 54d2eb46b5..cc72518b37 100644--- a/saleor/plugins/avatax/plugin.py+++ b/saleor/plugins/avatax/plugin.py@@ -4,6 +4,8 @@ from decimal import Decimalfrom typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Unionfrom urllib.parse import urljoin+import opentracing+import opentracing.tagsfrom django.core.exceptions import ValidationErrorfrom prices import Money, TaxedMoney, TaxedMoneyRange@@ -299,7 +301,13 @@ class AvataxPlugin(BasePlugin):transaction_url = urljoin(get_api_url(self.config.use_sandbox), "transactions/createoradjust")- response = api_post_request(transaction_url, data, self.config)+ with opentracing.global_tracer().start_active_span(+ "avatax.transactions.crateoradjust"+ ) as scope:+ span = scope.span+ span.set_tag(opentracing.tags.COMPONENT, "tax")+ span.set_tag("service.name", "avatax")+ response = api_post_request(transaction_url, data, self.config)if not response or "error" in response:msg = response.get("error", {}).get("message", "")error_code = response.get("error", {}).get("code", "")@@ -596,11 +604,17 @@ class AvataxPlugin(BasePlugin):data["name"]: data["value"] for data in plugin_configuration.configuration}url = urljoin(get_api_url(conf["Use sandbox"]), "utilities/ping")- response = api_get_request(- url,- username_or_account=conf["Username or account"],- password_or_license=conf["Password or license"],- )+ with opentracing.global_tracer().start_active_span(+ "avatax.utilities.ping"+ ) as scope:+ span = scope.span+ span.set_tag(opentracing.tags.COMPONENT, "tax")+ span.set_tag("service.name", "avatax")+ response = api_get_request(+ url,+ username_or_account=conf["Username or account"],+ password_or_license=conf["Password or license"],+ )if not response.get("authenticated"):raise ValidationError(diff --git a/saleor/plugins/avatax/tasks.py b/saleor/plugins/avatax/tasks.pyindex 8fecf5eef0..97f8fde05b 100644--- a/saleor/plugins/avatax/tasks.py+++ b/saleor/plugins/avatax/tasks.py@@ -1,5 +1,8 @@import logging+import opentracing+import opentracing.tags+from ...celeryconf import appfrom ...core.taxes import TaxErrorfrom ...order.events import external_notification_event@@ -29,7 +32,13 @@ def api_post_request_task(transaction_url, data, config, order_id):)return- response = api_post_request(transaction_url, data, config)+ with opentracing.global_tracer().start_active_span(+ "avatax.transactions.crateoradjust"+ ) as scope:+ span = scope.span+ span.set_tag(opentracing.tags.COMPONENT, "tax")+ span.set_tag("service.name", "avatax")+ response = api_post_request(transaction_url, data, config)msg = f"Order sent to Avatax. Order ID: {order.token}"if not response or "error" in response:avatax_msg = response.get("error", {}).get("message", "")