Skip to content

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

Add auto_capture setting to payment configs

Maciej Korycinskid2e83909e760
diff --git a/saleor/order/views.py b/saleor/order/views.py
index 5dc25b5b62..6306ff5c90 100644
--- a/saleor/order/views.py
+++ b/saleor/order/views.py
@@ -15,45 +15,46 @@ from ..account.models import User
from ..core.utils import get_client_ip
from ..payment import ChargeStatus, TransactionKind, get_payment_gateway
from ..payment.utils import (
- create_payment, create_payment_information, gateway_process_payment)
+ create_payment,
+ create_payment_information,
+ gateway_process_payment,
+)
from . import FulfillmentStatus
-from .forms import (
- CustomerNoteForm, PasswordForm, PaymentDeleteForm, PaymentsForm)
+from .forms import CustomerNoteForm, PasswordForm, PaymentDeleteForm, PaymentsForm
from .models import Order
from .utils import attach_order_to_user, check_order_status
logger = logging.getLogger(__name__)
-PAYMENT_TEMPLATE = 'order/payment/%s.html'
+PAYMENT_TEMPLATE = "order/payment/%s.html"
def details(request, token):
note_form = None
orders = Order.objects.confirmed().prefetch_related(
- 'lines__variant__images', 'lines__variant__product__images',
- 'fulfillments__lines__order_line')
- orders = orders.select_related(
- 'billing_address', 'shipping_address', 'user')
+ "lines__variant__images",
+ "lines__variant__product__images",
+ "fulfillments__lines__order_line",
+ )
+ orders = orders.select_related("billing_address", "shipping_address", "user")
order = get_object_or_404(orders, token=token)
if order.is_open() and not order.customer_note:
note_form = CustomerNoteForm(request.POST or None, instance=order)
- if request.method == 'POST':
+ if request.method == "POST":
if note_form.is_valid():
note_form.save()
- return redirect('order:details', token=order.token)
- fulfillments = order.fulfillments.exclude(
- status=FulfillmentStatus.CANCELED)
- ctx = {
- 'order': order, 'fulfillments': fulfillments, 'note_form': note_form}
- return TemplateResponse(request, 'order/details.html', ctx)
+ return redirect("order:details", token=order.token)
+ fulfillments = order.fulfillments.exclude(status=FulfillmentStatus.CANCELED)
+ ctx = {"order": order, "fulfillments": fulfillments, "note_form": note_form}
+ return TemplateResponse(request, "order/details.html", ctx)
def payment(request, token):
orders = Order.objects.confirmed().filter(billing_address__isnull=False)
orders = orders.prefetch_related(
- 'lines__variant__images', 'lines__variant__product__images')
- orders = orders.select_related(
- 'billing_address', 'shipping_address', 'user')
+ "lines__variant__images", "lines__variant__product__images"
+ )
+ orders = orders.select_related("billing_address", "shipping_address", "user")
order = get_object_or_404(orders, token=token)
payments = order.payments.all()
form_data = request.POST or None
@@ -61,13 +62,15 @@ def payment(request, token):
waiting_payment = payments.filter(
is_active=True,
charge_status=ChargeStatus.NOT_CHARGED,
- transactions__kind=TransactionKind.AUTH).first()
+ transactions__kind=TransactionKind.AUTH,
+ ).first()
if not waiting_payment:
waiting_payment_form = None
else:
form_data = None
waiting_payment_form = PaymentDeleteForm(
- None, order=order, initial={'payment_id': waiting_payment.id})
+ None, order=order, initial={"payment_id": waiting_payment.id}
+ )
if order.is_fully_paid() or not order.billing_address:
form_data = None
payment_form = None
@@ -75,20 +78,23 @@ def payment(request, token):
payment_form = PaymentsForm(form_data)
# FIXME: redirect if there is only one payment
if payment_form.is_valid():
- payment = payment_form.cleaned_data['gateway']
- return redirect(
- 'order:payment', token=order.token, gateway=payment)
+ payment = payment_form.cleaned_data["gateway"]
+ return redirect("order:payment", token=order.token, gateway=payment)
ctx = {
- 'order': order, 'payment_form': payment_form, 'payments': payments,
- 'waiting_payment': waiting_payment,
- 'waiting_payment_form': waiting_payment_form}
- return TemplateResponse(request, 'order/payment.html', ctx)
+ "order": order,
+ "payment_form": payment_form,
+ "payments": payments,
+ "waiting_payment": waiting_payment,
+ "waiting_payment_form": waiting_payment_form,
+ }
+ return TemplateResponse(request, "order/payment.html", ctx)
@check_order_status
def start_payment(request, order, gateway):
- payment_gateway, connection_params = get_payment_gateway(gateway)
- extra_data = {'customer_user_agent': request.META.get('HTTP_USER_AGENT')}
+ payment_gateway, gateway_config = get_payment_gateway(gateway)
+ connection_params = gateway_config.connection_params
+ extra_data = {"customer_user_agent": request.META.get("HTTP_USER_AGENT")}
with transaction.atomic():
payment = create_payment(
gateway=gateway,
@@ -98,35 +104,40 @@ def start_payment(request, order, gateway):
customer_ip_address=get_client_ip(request),
total=order.total.gross.amount,
order=order,
- extra_data=extra_data)
+ extra_data=extra_data,
+ )
- if (order.is_fully_paid()
- or payment.charge_status == ChargeStatus.FULLY_REFUNDED):
+ if (
+ order.is_fully_paid()
+ or payment.charge_status == ChargeStatus.FULLY_REFUNDED
+ ):
return redirect(order.get_absolute_url())
payment_info = create_payment_information(payment)
form = payment_gateway.create_form(
data=request.POST or None,
payment_information=payment_info,
- connection_params=connection_params)
+ connection_params=connection_params,
+ )
if form.is_valid():
try:
gateway_process_payment(
- payment=payment, payment_token=form.get_payment_token())
+ payment=payment, payment_token=form.get_payment_token()
+ )
except Exception as exc:
form.add_error(None, str(exc))
else:
if order.is_fully_paid():
- return redirect('order:payment-success', token=order.token)
+ return redirect("order:payment-success", token=order.token)
return redirect(order.get_absolute_url())
- client_token = payment_gateway.get_client_token(
- connection_params=connection_params)
+ client_token = payment_gateway.get_client_token(connection_params=connection_params)
ctx = {
- 'form': form,
- 'payment': payment,
- 'client_token': client_token,
- 'order': order}
+ "form": form,
+ "payment": payment,
+ "client_token": client_token,
+ "order": order,
+ }
return TemplateResponse(request, payment_gateway.TEMPLATE_PATH, ctx)
@@ -136,7 +147,7 @@ def cancel_payment(request, order):
if form.is_valid():
with transaction.atomic():
form.save()
- return redirect('order:payment', token=order.token)
+ return redirect("order:payment", token=order.token)
return HttpResponseForbidden()
@@ -147,7 +158,7 @@ def payment_success(request, token):
Redirects user to payment success.
All post data and query strings are dropped.
"""
- url = reverse('order:checkout-success', kwargs={'token': token})
+ url = reverse("order:checkout-success", kwargs={"token": token})
return redirect(url)
@@ -160,27 +171,24 @@ def checkout_success(request, token):
"""
order = get_object_or_404(Order, token=token)
email = order.user_email
- ctx = {'email': email, 'order': order}
+ ctx = {"email": email, "order": order}
if request.user.is_authenticated:
- return TemplateResponse(request, 'order/checkout_success.html', ctx)
+ return TemplateResponse(request, "order/checkout_success.html", ctx)
form_data = request.POST.copy()
if form_data:
- form_data.update({'email': email})
+ form_data.update({"email": email})
register_form = PasswordForm(form_data or None)
if register_form.is_valid():
register_form.save()
- password = register_form.cleaned_data.get('password')
- user = auth.authenticate(
- request=request, email=email, password=password)
+ password = register_form.cleaned_data.get("password")
+ user = auth.authenticate(request=request, email=email, password=password)
auth.login(request, user)
attach_order_to_user(order, user)
- return redirect('order:details', token=token)
+ return redirect("order:details", token=token)
user_exists = User.objects.filter(email=email).exists()
- login_form = LoginForm(
- initial={'username': email}) if user_exists else None
- ctx.update({'form': register_form, 'login_form': login_form})
- return TemplateResponse(
- request, 'order/checkout_success_anonymous.html', ctx)
+ login_form = LoginForm(initial={"username": email}) if user_exists else None
+ ctx.update({"form": register_form, "login_form": login_form})
+ return TemplateResponse(request, "order/checkout_success_anonymous.html", ctx)
@login_required
@@ -192,14 +200,15 @@ def connect_order_with_user(request, token):
order = None
if not order:
msg = pgettext_lazy(
- 'Connect order with user warning message',
+ "Connect order with user warning message",
"We couldn't assign the order to your account as the email"
- " addresses don't match")
+ " addresses don't match",
+ )
messages.warning(request, msg)
- return redirect('account:details')
+ return redirect("account:details")
attach_order_to_user(order, request.user)
msg = pgettext_lazy(
- 'storefront message',
- 'The order is now assigned to your account')
+ "storefront message", "The order is now assigned to your account"
+ )
messages.success(request, msg)
- return redirect('order:details', token=order.token)
+ return redirect("order:details", token=order.token)
diff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.py
index ef2513cf3d..4664e61782 100644
--- a/saleor/payment/__init__.py
+++ b/saleor/payment/__init__.py
@@ -5,9 +5,10 @@ from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.translation import pgettext_lazy
+from .interface import ConfigData
-class PaymentError(Exception):
+class PaymentError(Exception):
def __init__(self, message):
super(PaymentError, self).__init__(message)
self.message = message
@@ -18,33 +19,32 @@ class GatewayError(IOError):
class CustomPaymentChoices:
- MANUAL = 'manual'
+ MANUAL = "manual"
- CHOICES = [
- (MANUAL, pgettext_lazy('Custom payment choice type', 'Manual'))]
+ CHOICES = [(MANUAL, pgettext_lazy("Custom payment choice type", "Manual"))]
class OperationType(Enum):
- PROCESS_PAYMENT = 'process_payment'
- AUTH = 'authorize'
- CAPTURE = 'capture'
- VOID = 'void'
- REFUND = 'refund'
+ PROCESS_PAYMENT = "process_payment"
+ AUTH = "authorize"
+ CAPTURE = "capture"
+ VOID = "void"
+ REFUND = "refund"
class TransactionError(Enum):
"""Represents a transaction error."""
- INCORRECT_NUMBER = 'incorrect_number'
- INVALID_NUMBER = 'invalid_number'
- INCORRECT_CVV = 'incorrect_cvv'
- INVALID_CVV = 'invalid_cvv'
- INCORRECT_ZIP = 'incorrect_zip'
- INCORRECT_ADDRESS = 'incorrect_address'
- INVALID_EXPIRY_DATE = 'invalid_expiry_date'
- EXPIRED = 'expired'
- PROCESSING_ERROR = 'processing_error'
- DECLINED = 'declined'
+ INCORRECT_NUMBER = "incorrect_number"
+ INVALID_NUMBER = "invalid_number"
+ INCORRECT_CVV = "incorrect_cvv"
+ INVALID_CVV = "invalid_cvv"
+ INCORRECT_ZIP = "incorrect_zip"
+ INCORRECT_ADDRESS = "incorrect_address"
+ INVALID_EXPIRY_DATE = "invalid_expiry_date"
+ EXPIRED = "expired"
+ PROCESSING_ERROR = "processing_error"
+ DECLINED = "declined"
class TransactionKind:
@@ -59,17 +59,19 @@ class TransactionKind:
- REFUND - full or partial return of captured funds to the customer.
"""
- AUTH = 'auth'
- CAPTURE = 'capture'
- VOID = 'void'
- REFUND = 'refund'
+ AUTH = "auth"
+ CAPTURE = "capture"
+ VOID = "void"
+ REFUND = "refund"
# FIXME we could use another status like WAITING_FOR_AUTH for transactions
# Which were authorized, but needs to be confirmed manually by staff
# eg. Braintree with "submit_for_settlement" enabled
- CHOICES = [(AUTH, pgettext_lazy('transaction kind', 'Authorization')),
- (REFUND, pgettext_lazy('transaction kind', 'Refund')),
- (CAPTURE, pgettext_lazy('transaction kind', 'Capture')),
- (VOID, pgettext_lazy('transaction kind', 'Void'))]
+ CHOICES = [
+ (AUTH, pgettext_lazy("transaction kind", "Authorization")),
+ (REFUND, pgettext_lazy("transaction kind", "Refund")),
+ (CAPTURE, pgettext_lazy("transaction kind", "Capture")),
+ (VOID, pgettext_lazy("transaction kind", "Void")),
+ ]
class ChargeStatus:
@@ -85,36 +87,43 @@ class ChargeStatus:
- FULLY_REFUNDED - all charged funds were returned to the customer.
"""
- NOT_CHARGED = 'not-charged'
- PARTIALLY_CHARGED = 'partially-charged'
- FULLY_CHARGED = 'fully-charged'
- PARTIALLY_REFUNDED = 'partially-refunded'
- FULLY_REFUNDED = 'fully-refunded'
+ NOT_CHARGED = "not-charged"
+ PARTIALLY_CHARGED = "partially-charged"
+ FULLY_CHARGED = "fully-charged"
+ PARTIALLY_REFUNDED = "partially-refunded"
+ FULLY_REFUNDED = "fully-refunded"
CHOICES = [
- (NOT_CHARGED, pgettext_lazy('payment status', 'Not charged')),
- (PARTIALLY_CHARGED, pgettext_lazy(
- 'payment status', 'Partially charged')),
- (FULLY_CHARGED, pgettext_lazy('payment status', 'Fully charged')),
- (PARTIALLY_REFUNDED, pgettext_lazy(
- 'payment status', 'Partially refunded')),
- (FULLY_REFUNDED, pgettext_lazy('payment status', 'Fully refunded'))]
+ (NOT_CHARGED, pgettext_lazy("payment status", "Not charged")),
+ (PARTIALLY_CHARGED, pgettext_lazy("payment status", "Partially charged")),
+ (FULLY_CHARGED, pgettext_lazy("payment status", "Fully charged")),
+ (PARTIALLY_REFUNDED, pgettext_lazy("payment status", "Partially refunded")),
+ (FULLY_REFUNDED, pgettext_lazy("payment status", "Fully refunded")),
+ ]
GATEWAYS_ENUM = Enum(
- 'GatewaysEnum',
- {key.upper(): key.lower()
- for key in settings.CHECKOUT_PAYMENT_GATEWAYS})
+ "GatewaysEnum",
+ {key.upper(): key.lower() for key in settings.CHECKOUT_PAYMENT_GATEWAYS},
+)
def get_payment_gateway(gateway_name):
if gateway_name not in settings.CHECKOUT_PAYMENT_GATEWAYS:
- raise ValueError('%s is not allowed gateway' % gateway_name)
+ raise ValueError("%s is not allowed gateway" % gateway_name)
if gateway_name not in settings.PAYMENT_GATEWAYS:
raise ImproperlyConfigured(
- 'Payment gateway %s is not configured.' % gateway_name)
+ "Payment gateway %s is not configured." % gateway_name
+ )
+
gateway_module = importlib.import_module(
- settings.PAYMENT_GATEWAYS[gateway_name]['module'])
- gateway_params = settings.PAYMENT_GATEWAYS[gateway_name][
- 'connection_params']
- return gateway_module, gateway_params
+ settings.PAYMENT_GATEWAYS[gateway_name]["module"]
+ )
+
+ gateway_config = settings.PAYMENT_GATEWAYS[gateway_name]["config"]
+ config = ConfigData(
+ auto_capture=gateway_config["auto_capture"],
+ connection_params=gateway_config["connection_params"],
+ )
+
+ return gateway_module, config
diff --git a/saleor/payment/gateways/braintree/__init__.py b/saleor/payment/gateways/braintree/__init__.py
index 0844300348..ce660a2d7b 100644
--- a/saleor/payment/gateways/braintree/__init__.py
+++ b/saleor/payment/gateways/braintree/__init__.py
@@ -1,17 +1,17 @@
import logging
-from typing import Dict, List
+from typing import Any, Dict, List
import braintree as braintree_sdk
from django.core.exceptions import ImproperlyConfigured
from django.utils.translation import pgettext_lazy
-from ...interface import GatewayResponse, PaymentData
+from ...interface import ConfigData, GatewayResponse, PaymentData
from .errors import DEFAULT_ERROR_MESSAGE, BraintreeException
from .forms import BraintreePaymentForm
logger = logging.getLogger(__name__)
-TEMPLATE_PATH = 'order/payment/braintree.html'
+TEMPLATE_PATH = "order/payment/braintree.html"
# FIXME: Move to SiteSettings
@@ -24,38 +24,39 @@ THREE_D_SECURE_REQUIRED = False
# if no error_msg_override is provided,
# then error message returned by the gateway will be used
ERROR_CODES_WHITELIST = {
- '91506': """
+ "91506": """
Cannot refund transaction unless it is settled.
Please try again later. Settlement time might vary depending
- on the issuers bank.""",
+ on the issuers bank."""
}
class TransactionKind:
- AUTH = 'auth'
- CAPTURE = 'capture'
- CHARGE = 'charge'
- REFUND = 'refund'
- VOID = 'void'
+ AUTH = "auth"
+ CAPTURE = "capture"
+ CHARGE = "charge"
+ REFUND = "refund"
+ VOID = "void"
def get_customer_data(payment_information: PaymentData) -> Dict:
billing = payment_information.billing
return {
- 'order_id': payment_information.order_id,
- 'billing': {
- 'first_name': billing.first_name,
- 'last_name': billing.last_name,
- 'company': billing.company_name,
- 'postal_code': billing.postal_code,
- 'street_address': billing.street_address_1,
- 'extended_address': billing.street_address_2,
- 'locality': billing.city,
- 'region': billing.country_area,
- 'country_code_alpha2': billing.country},
- 'risk_data': {
- 'customer_ip': payment_information.customer_ip_address or ''},
- 'customer': {'email': payment_information.customer_email}}
+ "order_id": payment_information.order_id,
+ "billing": {
+ "first_name": billing.first_name,
+ "last_name": billing.last_name,
+ "company": billing.company_name,
+ "postal_code": billing.postal_code,
+ "street_address": billing.street_address_1,
+ "extended_address": billing.street_address_2,
+ "locality": billing.city,
+ "region": billing.country_area,
+ "country_code_alpha2": billing.country,
+ },
+ "risk_data": {"customer_ip": payment_information.customer_ip_address or ""},
+ "customer": {"email": payment_information.customer_email},
+ }
def get_error_for_client(errors: List) -> str:
@@ -63,13 +64,13 @@ def get_error_for_client(errors: List) -> str:
client side.
"""
if not errors:
- return ''
+ return ""
default_msg = pgettext_lazy(
- 'payment error',
- 'Unable to process transaction. Please try again in a moment')
+ "payment error", "Unable to process transaction. Please try again in a moment"
+ )
for error in errors:
- if error['code'] in ERROR_CODES_WHITELIST:
- return ERROR_CODES_WHITELIST[error['code']] or error['message']
+ if error["code"] in ERROR_CODES_WHITELIST:
+ return ERROR_CODES_WHITELIST[error["code"]] or error["message"]
return default_msg
@@ -78,29 +79,30 @@ def extract_gateway_response(braintree_result) -> Dict:
errors = []
if not braintree_result.is_success:
errors = [
- {'code': error.code, 'message': error.message}
- for error in braintree_result.errors.deep_errors]
+ {"code": error.code, "message": error.message}
+ for error in braintree_result.errors.deep_errors
+ ]
bt_transaction = braintree_result.transaction
if not bt_transaction:
- return {'errors': errors}
+ return {"errors": errors}
return {
- 'transaction_id': getattr(bt_transaction, 'id', ''),
- 'currency': bt_transaction.currency_iso_code,
- 'amount': bt_transaction.amount, # Decimal type
- 'credit_card': bt_transaction.credit_card,
- 'errors': errors}
+ "transaction_id": getattr(bt_transaction, "id", ""),
+ "currency": bt_transaction.currency_iso_code,
+ "amount": bt_transaction.amount, # Decimal type
+ "credit_card": bt_transaction.credit_card,
+ "errors": errors,
+ }
def create_form(data, payment_information, connection_params):
- return BraintreePaymentForm(
- data=data, payment_information=payment_information)
+ return BraintreePaymentForm(data=data, payment_information=payment_information)
def get_braintree_gateway(sandbox_mode, merchant_id, public_key, private_key):
if not all([merchant_id, private_key, public_key]):
- raise ImproperlyConfigured('Incorrectly configured Braintree gateway.')
+ raise ImproperlyConfigured("Incorrectly configured Braintree gateway.")
environment = braintree_sdk.Environment.Sandbox
if not sandbox_mode:
environment = braintree_sdk.Environment.Production
@@ -109,141 +111,132 @@ def get_braintree_gateway(sandbox_mode, merchant_id, public_key, private_key):
environment=environment,
merchant_id=merchant_id,
public_key=public_key,
- private_key=private_key)
+ private_key=private_key,
+ )
gateway = braintree_sdk.BraintreeGateway(config=config)
return gateway
-def get_client_token(connection_params: Dict) -> str:
+def get_client_token(connection_params: Dict[str, Any]) -> str:
gateway = get_braintree_gateway(**connection_params)
client_token = gateway.client_token.generate()
return client_token
-def authorize(
- payment_information: PaymentData, connection_params: Dict
-) -> GatewayResponse:
- gateway = get_braintree_gateway(**connection_params)
+def authorize(payment_information: PaymentData, config: ConfigData) -> GatewayResponse:
+ gateway = get_braintree_gateway(**config.connection_params)
try:
- result = gateway.transaction.sale({
- 'amount': str(payment_information.amount),
- 'payment_method_nonce': payment_information.token,
- 'options': {
- 'submit_for_settlement': CONFIRM_MANUALLY,
- 'three_d_secure': {
- 'required': THREE_D_SECURE_REQUIRED}},
- **get_customer_data(payment_information)})
+ result = gateway.transaction.sale(
+ {
+ "amount": str(payment_information.amount),
+ "payment_method_nonce": payment_information.token,
+ "options": {
+ "submit_for_settlement": config.auto_capture,
+ "three_d_secure": {"required": THREE_D_SECURE_REQUIRED},
+ },
+ **get_customer_data(payment_information),
+ }
+ )
except braintree_sdk.exceptions.NotFoundError:
raise BraintreeException(DEFAULT_ERROR_MESSAGE)
gateway_response = extract_gateway_response(result)
- error = get_error_for_client(gateway_response['errors'])
+ error = get_error_for_client(gateway_response["errors"])
+ kind = TransactionKind.CAPTURE if config.auto_capture else TransactionKind.AUTH
return GatewayResponse(
is_success=result.is_success,
- kind=TransactionKind.AUTH,
- amount=gateway_response.get(
- 'amount', payment_information.amount),
- currency=gateway_response.get(
- 'currency', payment_information.currency),
+ kind=kind,
+ amount=gateway_response.get("amount", payment_information.amount),
+ currency=gateway_response.get("currency", payment_information.currency),
transaction_id=gateway_response.get(
- 'transaction_id', payment_information.token),
+ "transaction_id", payment_information.token
+ ),
error=error,
- raw_response=gateway_response
+ raw_response=gateway_response,
)
-def capture(
- payment_information: PaymentData, connection_params: Dict
-) -> GatewayResponse:
- gateway = get_braintree_gateway(**connection_params)
+def capture(payment_information: PaymentData, config: ConfigData) -> 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))
+ amount=str(payment_information.amount),
+ )
except braintree_sdk.exceptions.NotFoundError:
raise BraintreeException(DEFAULT_ERROR_MESSAGE)
gateway_response = extract_gateway_response(result)
- error = get_error_for_client(gateway_response['errors'])
+ error = get_error_for_client(gateway_response["errors"])
return GatewayResponse(
is_success=result.is_success,
kind=TransactionKind.CAPTURE,
- amount=gateway_response.get(
- 'amount', payment_information.amount),
- currency=gateway_response.get(
- 'currency', payment_information.currency),
+ amount=gateway_response.get("amount", payment_information.amount),
+ currency=gateway_response.get("currency", payment_information.currency),
transaction_id=gateway_response.get(
- 'transaction_id', payment_information.token),
+ "transaction_id", payment_information.token
+ ),
error=error,
- raw_response=gateway_response
+ raw_response=gateway_response,
)
-def void(
- payment_information: PaymentData, connection_params: Dict
-) -> GatewayResponse:
- gateway = get_braintree_gateway(**connection_params)
+def void(payment_information: PaymentData, config: ConfigData) -> GatewayResponse:
+ gateway = get_braintree_gateway(**config.connection_params)
try:
- result = gateway.transaction.void(
- transaction_id=payment_information.token)
+ result = gateway.transaction.void(transaction_id=payment_information.token)
except braintree_sdk.exceptions.NotFoundError:
raise BraintreeException(DEFAULT_ERROR_MESSAGE)
gateway_response = extract_gateway_response(result)
- error = get_error_for_client(gateway_response['errors'])
+ error = get_error_for_client(gateway_response["errors"])
return GatewayResponse(
is_success=result.is_success,
kind=TransactionKind.VOID,
- amount=gateway_response.get(
- 'amount', payment_information.amount),
- currency=gateway_response.get(
- 'currency', payment_information.currency),
+ amount=gateway_response.get("amount", payment_information.amount),
+ currency=gateway_response.get("currency", payment_information.currency),
transaction_id=gateway_response.get(
- 'transaction_id', payment_information.token),
+ "transaction_id", payment_information.token
+ ),
error=error,
- raw_response=gateway_response
+ raw_response=gateway_response,
)
-def refund(
- payment_information: Dict, connection_params: Dict) -> GatewayResponse:
- gateway = get_braintree_gateway(**connection_params)
+def refund(payment_information: PaymentData, config: ConfigData) -> GatewayResponse:
+ gateway = get_braintree_gateway(**config.connection_params)
try:
result = gateway.transaction.refund(
transaction_id=payment_information.token,
- amount_or_options=str(payment_information.amount))
+ amount_or_options=str(payment_information.amount),
+ )
except braintree_sdk.exceptions.NotFoundError:
raise BraintreeException(DEFAULT_ERROR_MESSAGE)
gateway_response = extract_gateway_response(result)
- error = get_error_for_client(gateway_response['errors'])
+ error = get_error_for_client(gateway_response["errors"])
return GatewayResponse(
is_success=result.is_success,
kind=TransactionKind.REFUND,
- amount=gateway_response.get(
- 'amount', payment_information.amount),
- currency=gateway_response.get(
- 'currency', payment_information.currency),
+ amount=gateway_response.get("amount", payment_information.amount),
+ currency=gateway_response.get("currency", payment_information.currency),
transaction_id=gateway_response.get(
- 'transaction_id', payment_information.token),
+ "transaction_id", payment_information.token
+ ),
error=error,
- raw_response=gateway_response
-
+ raw_response=gateway_response,
)
def process_payment(
- payment_information: PaymentData, connection_params: Dict
+ payment_information: PaymentData, config: ConfigData
) -> GatewayResponse:
- auth_resp = authorize(payment_information, connection_params)
- if auth_resp.is_success:
- payment_information.token = auth_resp.transaction_id
- return capture(payment_information, connection_params)
+ auth_resp = authorize(payment_information, config)
return auth_resp
diff --git a/saleor/payment/gateways/dummy/__init__.py b/saleor/payment/gateways/dummy/__init__.py
index 94ead66f85..9fb048f5f4 100644
--- a/saleor/payment/gateways/dummy/__init__.py
+++ b/saleor/payment/gateways/dummy/__init__.py
@@ -1,14 +1,10 @@
import uuid
-from typing import Dict
from ... import ChargeStatus, TransactionKind
-from ...interface import GatewayResponse, PaymentData
+from ...interface import ConfigData, GatewayResponse, PaymentData
from .forms import DummyPaymentForm
-TEMPLATE_PATH = 'order/payment/dummy.html'
-
-# The gateway does not support payment authorization
-SUPPORTS_AUTHORIZATION = False
+TEMPLATE_PATH = "order/payment/dummy.html"
def dummy_success():
@@ -23,51 +19,43 @@ def create_form(data, payment_information, connection_params):
return DummyPaymentForm(data=data)
-def authorize(
- payment_information: PaymentData, connection_params) -> GatewayResponse:
+def authorize(payment_information: PaymentData, config: ConfigData) -> GatewayResponse:
success = dummy_success()
error = None
if not success:
- error = 'Unable to authorize transaction'
+ error = "Unable to authorize transaction"
return GatewayResponse(
is_success=success,
kind=TransactionKind.AUTH,
amount=payment_information.amount,
currency=payment_information.currency,
transaction_id=payment_information.token,
- error=error
+ error=error,
)
-def void(
- payment_information: PaymentData, connection_params) -> GatewayResponse:
+def void(payment_information: PaymentData, config: ConfigData) -> GatewayResponse:
error = None
success = dummy_success()
if not success:
- error = 'Unable to void the transaction.'
+ error = "Unable to void the transaction."
return GatewayResponse(
is_success=success,
kind=TransactionKind.VOID,
amount=payment_information.amount,
currency=payment_information.currency,
transaction_id=payment_information.token,
- error=error
+ error=error,
)
-def capture(
- payment_information: PaymentData, connection_params
-) -> GatewayResponse:
- """Performs Authorize and Capture transactions in a single run."""
- if not SUPPORTS_AUTHORIZATION:
- auth_resp = authorize(payment_information, connection_params)
- if not auth_resp.is_success:
- return auth_resp
+def capture(payment_information: PaymentData, config: ConfigData) -> GatewayResponse:
+ """Perform capture transaction."""
error = None
success = dummy_success()
if not success:
- error = 'Unable to process capture'
+ error = "Unable to process capture"
return GatewayResponse(
is_success=success,
@@ -75,45 +63,43 @@ def capture(
amount=payment_information.amount,
currency=payment_information.currency,
transaction_id=payment_information.token,
- error=error
+ error=error,
)
-def refund(
- payment_information: PaymentData, connection_params: Dict
-) -> GatewayResponse:
+def refund(payment_information: PaymentData, config: ConfigData) -> GatewayResponse:
error = None
success = dummy_success()
if not success:
- error = 'Unable to process refund'
+ error = "Unable to process refund"
return GatewayResponse(
is_success=success,
kind=TransactionKind.REFUND,
amount=payment_information.amount,
currency=payment_information.currency,
transaction_id=payment_information.token,
- error=error
+ error=error,
)
def process_payment(
- payment_information: PaymentData, connection_params
+ payment_information: PaymentData, config: ConfigData
) -> GatewayResponse:
"""Process the payment."""
token = payment_information.token
# Process payment normally if payment token is valid
if token not in dict(ChargeStatus.CHOICES):
- return capture(payment_information, connection_params)
+ return capture(payment_information, config)
# Process payment by charge status which is selected in the payment form
# Note that is for testing by dummy gateway only
charge_status = token
- authorize_response = authorize(payment_information, connection_params)
+ authorize_response = authorize(payment_information, config)
if charge_status == ChargeStatus.NOT_CHARGED:
return authorize_response
- capture_response = capture(payment_information, connection_params)
+ capture_response = capture(payment_information, config)
if charge_status == ChargeStatus.FULLY_REFUNDED:
- return refund(payment_information, connection_params)
+ return refund(payment_information, config)
return capture_response
diff --git a/saleor/payment/gateways/razorpay/__init__.py b/saleor/payment/gateways/razorpay/__init__.py
index 3105277229..d2671bdde9 100644
--- a/saleor/payment/gateways/razorpay/__init__.py
+++ b/saleor/payment/gateways/razorpay/__init__.py
@@ -7,25 +7,23 @@ import razorpay
import razorpay.errors
from ... import TransactionKind
-from ...interface import GatewayResponse, PaymentData
+from ...interface import ConfigData, GatewayResponse, PaymentData
from . import errors
from .forms import RazorPaymentForm
from .utils import get_amount_for_razorpay, get_error_response
-TEMPLATE_PATH = 'order/payment/razorpay.html'
+TEMPLATE_PATH = "order/payment/razorpay.html"
# The list of currencies supported by razorpay
-SUPPORTED_CURRENCIES = 'INR',
-
-# The gateway does not support payment authorization
-SUPPORTS_AUTHORIZATION = False
+SUPPORTED_CURRENCIES = ("INR",)
# Define what are the razorpay exceptions,
# as the razorpay provider doesn't define a base exception as of now.
RAZORPAY_EXCEPTIONS = (
razorpay.errors.BadRequestError,
razorpay.errors.GatewayError,
- razorpay.errors.ServerError)
+ razorpay.errors.ServerError,
+)
# Get the logger for this file, it will allow us to log
# error responses from razorpay.
@@ -33,26 +31,25 @@ logger = logging.getLogger(__name__)
def _generate_response(
- payment_information: PaymentData, kind: str, data: Dict
+ payment_information: PaymentData, kind: str, data: Dict
) -> GatewayResponse:
"""Generate Saleor transaction information from
Razorpay's success payload or from passed data."""
return GatewayResponse(
- transaction_id=data.get('id', payment_information.token),
+ transaction_id=data.get("id", payment_information.token),
kind=kind,
- amount=data.get('amount', payment_information.amount),
- currency=data.get('currency', payment_information.currency),
- error=data.get('error'),
- is_success=data.get('is_success', True),
- raw_response=data
+ amount=data.get("amount", payment_information.amount),
+ currency=data.get("currency", payment_information.currency),
+ error=data.get("error"),
+ is_success=data.get("is_success", True),
+ raw_response=data,
)
def check_payment_supported(payment_information: PaymentData):
"""Checks that a given payment is supported."""
if payment_information.currency not in SUPPORTED_CURRENCIES:
- return errors.UNSUPPORTED_CURRENCY % {
- 'currency': payment_information.currency}
+ return errors.UNSUPPORTED_CURRENCY % {"currency": payment_information.currency}
def get_error_message_from_razorpay_error(exc: BaseException):
@@ -68,13 +65,14 @@ def get_error_message_from_razorpay_error(exc: BaseException):
def clean_razorpay_response(response: Dict):
"""As the Razorpay response payload contains the final amount
in Indian rupees, we convert the amount to paisa (by dividing by 100)."""
- response['amount'] = Decimal(response['amount']) / 100
+ response["amount"] = Decimal(response["amount"]) / 100
def create_form(data, payment_information, connection_params):
"""Return the associated razorpay payment form."""
return RazorPaymentForm(
- data=data, payment_information=payment_information,
+ data=data,
+ payment_information=payment_information,
connection_params=connection_params,
)
@@ -90,10 +88,8 @@ def get_client_token(**_):
return str(uuid.uuid4())
-def capture(
- payment_information: PaymentData, connection_params: Dict
-) -> GatewayResponse:
- """Charge a authorized payment using the razorpay client.
+def capture(payment_information: PaymentData, config: ConfigData) -> GatewayResponse:
+ """Capture a authorized payment using the razorpay client.
But it first check if the given payment instance is supported
by the gateway.
@@ -103,32 +99,33 @@ def capture(
a short user friendly description of the error
after logging the error to stderr."""
error = check_payment_supported(payment_information=payment_information)
- razorpay_client = get_client(**connection_params)
+ razorpay_client = get_client(**config.connection_params)
razorpay_amount = get_amount_for_razorpay(payment_information.amount)
if not error:
try:
response = razorpay_client.payment.capture(
- payment_information.token, razorpay_amount)
+ payment_information.token, razorpay_amount
+ )
clean_razorpay_response(response)
except RAZORPAY_EXCEPTIONS as exc:
error = get_error_message_from_razorpay_error(exc)
response = get_error_response(
- payment_information.amount, error=error,
- id=payment_information.token)
+ payment_information.amount, error=error, id=payment_information.token
+ )
else:
response = get_error_response(
- payment_information.amount, error=error,
- id=payment_information.token)
+ payment_information.amount, error=error, id=payment_information.token
+ )
return _generate_response(
payment_information=payment_information,
- kind=TransactionKind.CAPTURE, data=response)
+ kind=TransactionKind.CAPTURE,
+ data=response,
+ )
-def refund(
- payment_information: PaymentData, connection_params
-) -> GatewayResponse:
+def refund(payment_information: PaymentData, config: ConfigData) -> GatewayResponse:
"""Refund a payment using the razorpay client.
But it first check if the given payment instance is supported
@@ -141,29 +138,30 @@ def refund(
error = check_payment_supported(payment_information=payment_information)
if error:
- response = get_error_response(
- payment_information.amount, error=error)
+ response = get_error_response(payment_information.amount, error=error)
else:
- razorpay_client = get_client(**connection_params)
- razorpay_amount = get_amount_for_razorpay(
- payment_information.amount)
+ razorpay_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)
+ payment_information.token, razorpay_amount
+ )
clean_razorpay_response(response)
except RAZORPAY_EXCEPTIONS as exc:
error = get_error_message_from_razorpay_error(exc)
- response = get_error_response(
- payment_information.amount, error=error)
+ response = get_error_response(payment_information.amount, error=error)
return _generate_response(
payment_information=payment_information,
- kind=TransactionKind.REFUND, data=response)
+ kind=TransactionKind.REFUND,
+ data=response,
+ )
def process_payment(
- payment_information: PaymentData, connection_params
+ payment_information: PaymentData, config: ConfigData
) -> GatewayResponse:
return capture(
payment_information=payment_information,
- connection_params=connection_params)
+ connection_params=config.connection_params,
+ )
diff --git a/saleor/payment/gateways/stripe/__init__.py b/saleor/payment/gateways/stripe/__init__.py
index 74d2d86971..c842aaa110 100644
--- a/saleor/payment/gateways/stripe/__init__.py
+++ b/saleor/payment/gateways/stripe/__init__.py
@@ -3,14 +3,18 @@ from typing import Dict
import stripe
from ... import TransactionKind
-from ...interface import GatewayResponse, PaymentData
+from ...interface import ConfigData, GatewayResponse, PaymentData
from .forms import StripePaymentModalForm
from .utils import (
- get_amount_for_stripe, get_amount_from_stripe, get_currency_for_stripe,
- get_currency_from_stripe, get_payment_billing_fullname,
- shipping_to_stripe_dict)
+ get_amount_for_stripe,
+ get_amount_from_stripe,
+ get_currency_for_stripe,
+ get_currency_from_stripe,
+ get_payment_billing_fullname,
+ shipping_to_stripe_dict,
+)
-TEMPLATE_PATH = 'order/payment/stripe.html'
+TEMPLATE_PATH = "order/payment/stripe.html"
def get_client_token(**_):
@@ -20,35 +24,37 @@ def get_client_token(**_):
return
-def authorize(
- payment_information: PaymentData, connection_params: Dict
-) -> GatewayResponse:
- client, error = _get_client(**connection_params), None
+def authorize(payment_information: PaymentData, config: ConfigData) -> GatewayResponse:
+ client, error = _get_client(**config.connection_params), None
try:
- # Authorize without capture
+ # Authorize with/without capture
response = _create_stripe_charge(
- client=client, payment_information=payment_information,
- should_capture=False)
+ client=client,
+ payment_information=payment_information,
+ should_capture=config.auto_capture,
+ )
except stripe.error.StripeError as exc:
response = _get_error_response_from_exc(exc)
error = exc.user_message
+ kind = TransactionKind.CAPTURE if config.auto_capture else TransactionKind.AUTH
+
# Create response
return _create_response(
payment_information=payment_information,
- kind=TransactionKind.AUTH, response=response, error=error)
+ kind=kind,
+ response=response,
+ error=error,
+ )
-def capture(
- payment_information: PaymentData, connection_params: Dict
-) -> GatewayResponse:
- client, error = _get_client(**connection_params), None
+def capture(payment_information: PaymentData, config: ConfigData) -> GatewayResponse:
+ client, error = _get_client(**config.connection_params), None
# Get amount from argument or payment, and convert to stripe's amount
amount = payment_information.amount
- stripe_amount = get_amount_for_stripe(
- amount, payment_information.currency)
+ stripe_amount = get_amount_for_stripe(amount, payment_information.currency)
try:
# Retrieve stripe charge and capture specific amount
@@ -61,24 +67,23 @@ def capture(
# Create response
return _create_response(
payment_information=payment_information,
- kind=TransactionKind.CAPTURE, response=response, error=error)
+ kind=TransactionKind.CAPTURE,
+ response=response,
+ error=error,
+ )
-def refund(
- payment_information: PaymentData, connection_params: Dict
-) -> GatewayResponse:
- client, error = _get_client(**connection_params), None
+def refund(payment_information: PaymentData, config: ConfigData) -> GatewayResponse:
+ client, error = _get_client(**config.connection_params), None
# Get amount from payment, and convert to stripe's amount
amount = payment_information.amount
- stripe_amount = get_amount_for_stripe(
- amount, payment_information.currency)
+ stripe_amount = get_amount_for_stripe(amount, payment_information.currency)
try:
# Retrieve stripe charge and refund specific amount
stripe_charge = client.Charge.retrieve(payment_information.token)
- response = client.Refund.create(
- charge=stripe_charge.id, amount=stripe_amount)
+ response = client.Refund.create(charge=stripe_charge.id, amount=stripe_amount)
except stripe.error.StripeError as exc:
response = _get_error_response_from_exc(exc)
error = exc.user_message
@@ -86,13 +91,14 @@ def refund(
# Create response
return _create_response(
payment_information=payment_information,
- kind=TransactionKind.REFUND, response=response, error=error)
+ kind=TransactionKind.REFUND,
+ response=response,
+ error=error,
+ )
-def void(
- payment_information: PaymentData, connection_params: Dict
-) -> GatewayResponse:
- client, error = _get_client(**connection_params), None
+def void(payment_information: PaymentData, config: ConfigData) -> GatewayResponse:
+ client, error = _get_client(**config.connection_params), None
try:
# Retrieve stripe charge and refund all
@@ -105,88 +111,97 @@ def void(
# Create response
return _create_response(
payment_information=payment_information,
- kind=TransactionKind.VOID, response=response, error=error)
+ kind=TransactionKind.VOID,
+ response=response,
+ error=error,
+ )
def process_payment(
- payment_information: PaymentData, connection_params: Dict
+ payment_information: PaymentData, config: ConfigData
) -> GatewayResponse:
- return charge(payment_information, connection_params)
+ # Stripe supports capture during authorize process. No need to run other steps.
+ # If 'auto_capture is True', it will also capture funds from the card.
+ return authorize(payment_information, config)
def create_form(
- data: Dict, payment_information: PaymentData,
- connection_params: Dict) -> StripePaymentModalForm:
+ data: Dict, payment_information: PaymentData, connection_params: Dict
+) -> StripePaymentModalForm:
return StripePaymentModalForm(
- data=data, payment_information=payment_information,
- gateway_params=connection_params)
+ data=data,
+ payment_information=payment_information,
+ gateway_params=connection_params,
+ )
def _get_client(**connection_params):
- stripe.api_key = connection_params.get('secret_key')
+ stripe.api_key = connection_params.get("secret_key")
return stripe
def _get_stripe_charge_payload(
- payment_information: PaymentData, should_capture: bool) -> Dict:
+ payment_information: PaymentData, should_capture: bool
+) -> Dict:
shipping = payment_information.shipping
# Get currency
currency = get_currency_for_stripe(payment_information.currency)
# Get appropriate amount for stripe
- stripe_amount = get_amount_for_stripe(
- payment_information.amount, currency)
+ stripe_amount = get_amount_for_stripe(payment_information.amount, currency)
# Get billing name from payment
name = get_payment_billing_fullname(payment_information)
# Construct the charge payload from the data
charge_payload = {
- 'capture': should_capture,
- 'amount': stripe_amount,
- 'currency': currency,
- 'source': payment_information.token,
- 'description': name}
+ "capture": should_capture,
+ "amount": stripe_amount,
+ "currency": currency,
+ "source": payment_information.token,
+ "description": name,
+ }
if shipping:
# Update shipping address to prevent fraud in Stripe
- charge_payload['shipping'] = {
- 'name': name,
- 'address': shipping_to_stripe_dict(shipping)}
+ charge_payload["shipping"] = {
+ "name": name,
+ "address": shipping_to_stripe_dict(shipping),
+ }
return charge_payload
def _create_stripe_charge(client, payment_information, should_capture: bool):
"""Create a charge with specific amount, ignoring payment's total."""
- charge_payload = _get_stripe_charge_payload(
- payment_information, should_capture)
+ charge_payload = _get_stripe_charge_payload(payment_information, should_capture)
return client.Charge.create(**charge_payload)
def _create_response(
- payment_information: PaymentData, kind: str, response: Dict,
- error: str) -> GatewayResponse:
+ payment_information: PaymentData, kind: str, response: Dict, error: str
+) -> GatewayResponse:
# Get currency from response or payment
currency = get_currency_from_stripe(
- response.get('currency', payment_information.currency))
+ response.get("currency", payment_information.currency)
+ )
amount = payment_information.amount
# Get amount from response or payment
- if 'amount' in response:
- stripe_amount = response.get('amount')
- if 'amount_refunded' in response:
+ if "amount" in response:
+ stripe_amount = response.get("amount")
+ if "amount_refunded" in response:
# This happens for partial catpure which will refund the left
# Then the actual amount should minus refunded amount
- stripe_amount -= response.get('amount_refunded')
+ stripe_amount -= response.get("amount_refunded")
amount = get_amount_from_stripe(stripe_amount, currency)
# Get token from response or use provided one
- token = response.get('id', payment_information.token)
+ token = response.get("id", payment_information.token)
# Check if the response's status is flagged as succeeded
- is_success = (response.get('status') == 'succeeded')
+ is_success = response.get("status") == "succeeded"
return GatewayResponse(
is_success=is_success,
transaction_id=token,
@@ -194,7 +209,7 @@ def _create_response(
amount=amount,
currency=currency,
error=error,
- raw_response=response
+ raw_response=response,
)
diff --git a/saleor/payment/gateways/stripe/utils.py b/saleor/payment/gateways/stripe/utils.py
index a28b448bd0..03523d4f91 100644
--- a/saleor/payment/gateways/stripe/utils.py
+++ b/saleor/payment/gateways/stripe/utils.py
@@ -7,11 +7,26 @@ 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 PaymentData
+from ...interface import AddressData, PaymentData
ZERO_DECIMAL_CURRENCIES = [
- 'BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA',
- 'PYG', 'RWF', 'UGX', 'VND', 'VUV', 'XAF', 'XOF', 'XPF']
+ "BIF",
+ "CLP",
+ "DJF",
+ "GNF",
+ "JPY",
+ "KMF",
+ "KRW",
+ "MGA",
+ "PYG",
+ "RWF",
+ "UGX",
+ "VND",
+ "VUV",
+ "XAF",
+ "XOF",
+ "XPF",
+]
def get_amount_for_stripe(amount, currency):
@@ -57,19 +72,20 @@ def get_currency_from_stripe(currency):
return currency.upper()
-def get_payment_billing_fullname(
- payment_information: PaymentData) -> str:
+def get_payment_billing_fullname(payment_information: PaymentData) -> str:
# Get billing name from payment
- return '%s %s' % (
+ return "%s %s" % (
payment_information.billing.last_name,
- payment_information.billing.first_name)
+ payment_information.billing.first_name,
+ )
-def shipping_to_stripe_dict(shipping: Dict):
+def shipping_to_stripe_dict(shipping: AddressData) -> Dict:
return {
- 'line1': shipping.street_address_1,
- 'line2': shipping.street_address_2,
- 'city': shipping.city,
- 'state': shipping.country_area,
- 'postal_code': shipping.postal_code,
- 'country': dict(countries).get(shipping.country, '')}
+ "line1": shipping.street_address_1,
+ "line2": shipping.street_address_2,
+ "city": shipping.city,
+ "state": shipping.country_area,
+ "postal_code": shipping.postal_code,
+ "country": dict(countries).get(shipping.country, ""),
+ }
diff --git a/saleor/payment/interface.py b/saleor/payment/interface.py
index 2374464259..58191fcd3e 100644
--- a/saleor/payment/interface.py
+++ b/saleor/payment/interface.py
@@ -1,6 +1,6 @@
from dataclasses import dataclass
from decimal import Decimal
-from typing import Dict, Optional
+from typing import Any, Dict, Optional
@dataclass
@@ -47,3 +47,16 @@ class PaymentData:
order_id: int
customer_ip_address: str
customer_email: str
+
+
+@dataclass
+class ConfigData:
+ """Dataclass for storing gateway config data. Used for unifying the
+ representation of config data. It is required to communicate between
+ Saleor and given payment gateway."""
+
+ auto_capture: bool
+
+ # Each gateway has different connection data so we are not able to create
+ # a unified structure
+ connection_params: Dict[str, Any]
diff --git a/saleor/payment/models.py b/saleor/payment/models.py
index cf569b9ac2..44bf7f60d2 100644
--- a/saleor/payment/models.py
+++ b/saleor/payment/models.py
@@ -11,8 +11,7 @@ from prices import Money
from ..checkout.models import Checkout
from ..core.utils.taxes import zero_money
from ..order.models import Order
-from . import (
- ChargeStatus, CustomPaymentChoices, TransactionError, TransactionKind)
+from . import ChargeStatus, CustomPaymentChoices, TransactionError, TransactionKind
class Payment(models.Model):
@@ -35,23 +34,27 @@ class Payment(models.Model):
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
charge_status = models.CharField(
- max_length=20, choices=ChargeStatus.CHOICES,
- default=ChargeStatus.NOT_CHARGED)
- token = models.CharField(max_length=128, blank=True, default='')
+ max_length=20, choices=ChargeStatus.CHOICES, default=ChargeStatus.NOT_CHARGED
+ )
+ token = models.CharField(max_length=128, blank=True, default="")
total = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- default=Decimal('0.0'))
+ default=Decimal("0.0"),
+ )
captured_amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- default=Decimal('0.0'))
+ default=Decimal("0.0"),
+ )
currency = models.CharField(max_length=10) # FIXME: add ISO4217 validator
checkout = models.ForeignKey(
- Checkout, null=True, related_name='payments', on_delete=models.SET_NULL)
+ Checkout, null=True, related_name="payments", on_delete=models.SET_NULL
+ )
order = models.ForeignKey(
- Order, null=True, related_name='payments', on_delete=models.PROTECT)
+ Order, null=True, related_name="payments", on_delete=models.PROTECT
+ )
billing_email = models.EmailField(blank=True)
billing_first_name = models.CharField(max_length=256, blank=True)
@@ -65,27 +68,32 @@ class Payment(models.Model):
billing_country_code = models.CharField(max_length=2, blank=True)
billing_country_area = models.CharField(max_length=256, blank=True)
- cc_first_digits = models.CharField(max_length=6, blank=True, default='')
- cc_last_digits = models.CharField(max_length=4, blank=True, default='')
- cc_brand = models.CharField(max_length=40, blank=True, default='')
+ cc_first_digits = models.CharField(max_length=6, blank=True, default="")
+ cc_last_digits = models.CharField(max_length=4, blank=True, default="")
+ cc_brand = models.CharField(max_length=40, blank=True, default="")
cc_exp_month = models.PositiveIntegerField(
- validators=[MinValueValidator(1), MaxValueValidator(12)],
- null=True, blank=True)
+ validators=[MinValueValidator(1), MaxValueValidator(12)], null=True, blank=True
+ )
cc_exp_year = models.PositiveIntegerField(
- validators=[MinValueValidator(1000)], null=True, blank=True)
+ validators=[MinValueValidator(1000)], null=True, blank=True
+ )
customer_ip_address = models.GenericIPAddressField(blank=True, null=True)
- extra_data = models.TextField(blank=True, default='')
+ extra_data = models.TextField(blank=True, default="")
class Meta:
- ordering = ('pk', )
+ ordering = ("pk",)
def __repr__(self):
- return 'Payment(gateway=%s, is_active=%s, created=%s, charge_status=%s)' % (
- self.gateway, self.is_active, self.created, self.charge_status)
+ return "Payment(gateway=%s, is_active=%s, created=%s, charge_status=%s)" % (
+ self.gateway,
+ self.is_active,
+ self.created,
+ self.charge_status,
+ )
def get_last_transaction(self):
- return max(self.transactions.all(), default=None, key=attrgetter('pk'))
+ return max(self.transactions.all(), default=None, key=attrgetter("pk"))
def get_total(self):
return Money(self.total, self.currency or settings.DEFAULT_CURRENCY)
@@ -99,27 +107,31 @@ class Payment(models.Model):
# There is no authorized amount anymore when capture is succeeded
# since capture can only be made once, even it is a partial capture
- if any([txn.kind == TransactionKind.CAPTURE
- and txn.is_success for txn in transactions]):
+ if any(
+ [
+ txn.kind == TransactionKind.CAPTURE and txn.is_success
+ for txn in transactions
+ ]
+ ):
return money
# Filter the succeeded auth transactions
authorized_txns = [
- txn for txn in transactions
- if txn.kind == TransactionKind.AUTH and txn.is_success]
+ txn
+ for txn in transactions
+ if txn.kind == TransactionKind.AUTH and txn.is_success
+ ]
# Calculate authorized amount from all succeeded auth transactions
for txn in authorized_txns:
- money += Money(
- txn.amount, self.currency or settings.DEFAULT_CURRENCY)
+ money += Money(txn.amount, self.currency or settings.DEFAULT_CURRENCY)
# If multiple partial capture is supported later though it's unlikely,
# the authorized amount should exclude the already captured amount here
return money
def get_captured_amount(self):
- return Money(
- self.captured_amount, self.currency or settings.DEFAULT_CURRENCY)
+ return Money(self.captured_amount, self.currency or settings.DEFAULT_CURRENCY)
def get_charge_amount(self):
"""Retrieve the maximum capture possible."""
@@ -127,9 +139,12 @@ class Payment(models.Model):
@property
def is_authorized(self):
- return any([
- txn.kind == TransactionKind.AUTH
- and txn.is_success for txn in self.transactions.all()])
+ return any(
+ [
+ txn.kind == TransactionKind.AUTH and txn.is_success
+ for txn in self.transactions.all()
+ ]
+ )
@property
def not_charged(self):
@@ -139,12 +154,11 @@ class Payment(models.Model):
return self.is_active and self.not_charged
def can_capture(self):
- from .utils import get_can_gateway_authorize
-
if not (self.is_active and self.not_charged):
return False
- if get_can_gateway_authorize(self.gateway):
+ gateway_config = settings.PAYMENT_GATEWAYS[self.gateway]["config"]
+ if gateway_config["auto_capture"]:
return self.is_authorized
return True
@@ -156,10 +170,13 @@ class Payment(models.Model):
can_refund_charge_status = (
ChargeStatus.PARTIALLY_CHARGED,
ChargeStatus.FULLY_CHARGED,
- ChargeStatus.PARTIALLY_REFUNDED)
+ ChargeStatus.PARTIALLY_REFUNDED,
+ )
return (
- self.is_active and self.charge_status in can_refund_charge_status
- and self.gateway != CustomPaymentChoices.MANUAL)
+ self.is_active
+ and self.charge_status in can_refund_charge_status
+ and self.gateway != CustomPaymentChoices.MANUAL
+ )
class Transaction(models.Model):
@@ -171,26 +188,33 @@ class Transaction(models.Model):
created = models.DateTimeField(auto_now_add=True, editable=False)
payment = models.ForeignKey(
- Payment, related_name='transactions', on_delete=models.PROTECT)
- token = models.CharField(max_length=128, blank=True, default='')
+ Payment, related_name="transactions", on_delete=models.PROTECT
+ )
+ token = models.CharField(max_length=128, blank=True, default="")
kind = models.CharField(max_length=10, choices=TransactionKind.CHOICES)
is_success = models.BooleanField(default=False)
currency = models.CharField(max_length=10)
amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- default=Decimal('0.0'))
+ default=Decimal("0.0"),
+ )
error = models.CharField(
choices=[(tag, tag.value) for tag in TransactionError],
- max_length=256, null=True)
+ max_length=256,
+ null=True,
+ )
gateway_response = JSONField(encoder=DjangoJSONEncoder)
class Meta:
- ordering = ('pk', )
+ ordering = ("pk",)
def __repr__(self):
- return 'Transaction(type=%s, is_success=%s, created=%s)' % (
- self.kind, self.is_success, self.created)
+ return "Transaction(type=%s, is_success=%s, created=%s)" % (
+ self.kind,
+ self.is_success,
+ self.created,
+ )
def get_amount(self):
return Money(self.amount, self.currency or settings.DEFAULT_CURRENCY)
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index dde60b22ce..07a17534c7 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -16,16 +16,28 @@ from ..order import OrderEvents, OrderEventsEmails, utils as order_utils
from ..order.emails import send_payment_confirmation
from ..order.models import Order
from . import (
- ChargeStatus, CustomPaymentChoices, GatewayError, OperationType,
- PaymentError, TransactionKind, get_payment_gateway)
+ ChargeStatus,
+ CustomPaymentChoices,
+ GatewayError,
+ OperationType,
+ PaymentError,
+ TransactionKind,
+ get_payment_gateway,
+)
from .interface import AddressData, GatewayResponse, PaymentData
from .models import Payment, Transaction
logger = logging.getLogger(__name__)
-GENERIC_TRANSACTION_ERROR = 'Transaction was unsuccessful'
+GENERIC_TRANSACTION_ERROR = "Transaction was unsuccessful"
REQUIRED_GATEWAY_KEYS = {
- 'transaction_id', 'is_success', 'kind', 'error', 'amount', 'currency'}
+ "transaction_id",
+ "is_success",
+ "kind",
+ "error",
+ "amount",
+ "currency",
+}
ALLOWED_GATEWAY_KINDS = {choices[0] for choices in TransactionKind.CHOICES}
@@ -43,14 +55,9 @@ def get_gateway_operation_func(gateway, operation_type):
return gateway.refund
-def get_can_gateway_authorize(gateway):
- gateway, _ = get_payment_gateway(gateway)
- return getattr(gateway, 'SUPPORTS_AUTHORIZATION', True)
-
-
def create_payment_information(
- payment: Payment, payment_token: str = None,
- amount: Decimal = None) -> PaymentData:
+ payment: Payment, payment_token: str = None, amount: Decimal = None
+) -> PaymentData:
"""Extracts order information along with payment details.
Returns information required to process payment and additional
@@ -72,7 +79,7 @@ def create_payment_information(
shipping=shipping,
order_id=payment.order.id,
customer_ip_address=payment.customer_ip_address,
- customer_email=payment.billing_email
+ customer_email=payment.billing_email,
)
@@ -83,8 +90,10 @@ def handle_fully_paid_order(order):
order.events.create(
type=OrderEvents.EMAIL_SENT.value,
parameters={
- 'email': order.get_user_current_email(),
- 'email_type': OrderEventsEmails.PAYMENT.value})
+ "email": order.get_user_current_email(),
+ "email_type": OrderEventsEmails.PAYMENT.value,
+ },
+ )
if order_utils.order_needs_automatic_fullfilment(order):
order_utils.automatically_fulfill_digital_lines(order)
@@ -92,7 +101,7 @@ def handle_fully_paid_order(order):
analytics.report_order(order.tracking_client_id, order)
except Exception:
# Analytics failing should not abort the checkout flow
- logger.exception('Recording order in analytics failed')
+ logger.exception("Recording order in analytics failed")
def require_active_payment(view):
@@ -101,58 +110,63 @@ def require_active_payment(view):
Decorate a view to check if payment is authorized, so any actions
can be performed on it.
"""
+
@wraps(view)
def func(payment: Payment, *args, **kwargs):
if not payment.is_active:
- raise PaymentError('This payment is no longer active.')
+ raise PaymentError("This payment is no longer active.")
return view(payment, *args, **kwargs)
+
return func
def create_payment(
- gateway: str,
- total: Decimal,
- currency: str,
- email: str,
- billing_address: Address,
- customer_ip_address: str = '',
- payment_token: str = '',
- extra_data: Dict = None,
- checkout: Checkout = None,
- order: Order = None) -> Payment:
+ gateway: str,
+ total: Decimal,
+ currency: str,
+ email: str,
+ billing_address: Address,
+ customer_ip_address: str = "",
+ payment_token: str = "",
+ extra_data: Dict = None,
+ checkout: Checkout = None,
+ order: Order = None,
+) -> Payment:
"""Create a payment instance.
This method is responsible for creating payment instances that works for
both Django views and GraphQL mutations.
"""
defaults = {
- 'billing_email': email,
- 'billing_first_name': billing_address.first_name,
- 'billing_last_name': billing_address.last_name,
- 'billing_company_name': billing_address.company_name,
- 'billing_address_1': billing_address.street_address_1,
- 'billing_address_2': billing_address.street_address_2,
- 'billing_city': billing_address.city,
- 'billing_postal_code': billing_address.postal_code,
- 'billing_country_code': billing_address.country.code,
- 'billing_country_area': billing_address.country_area,
- 'currency': currency,
- 'gateway': gateway,
- 'total': total}
+ "billing_email": email,
+ "billing_first_name": billing_address.first_name,
+ "billing_last_name": billing_address.last_name,
+ "billing_company_name": billing_address.company_name,
+ "billing_address_1": billing_address.street_address_1,
+ "billing_address_2": billing_address.street_address_2,
+ "billing_city": billing_address.city,
+ "billing_postal_code": billing_address.postal_code,
+ "billing_country_code": billing_address.country.code,
+ "billing_country_area": billing_address.country_area,
+ "currency": currency,
+ "gateway": gateway,
+ "total": total,
+ }
if extra_data is None:
extra_data = {}
data = {
- 'is_active': True,
- 'customer_ip_address': customer_ip_address,
- 'extra_data': extra_data,
- 'token': payment_token}
+ "is_active": True,
+ "customer_ip_address": customer_ip_address,
+ "extra_data": extra_data,
+ "token": payment_token,
+ }
if order is not None:
- data['order'] = order
+ data["order"] = order
if checkout is not None:
- data['checkout'] = checkout
+ data["checkout"] = checkout
payment, _ = Payment.objects.get_or_create(defaults=defaults, **data)
return payment
@@ -167,22 +181,25 @@ def mark_order_as_paid(order: Order, request_user: User):
"""
payment = create_payment(
gateway=CustomPaymentChoices.MANUAL,
- payment_token='',
+ payment_token="",
currency=order.total.gross.currency,
email=order.user_email,
billing_address=order.billing_address,
total=order.total.gross.amount,
- order=order)
+ order=order,
+ )
payment.charge_status = ChargeStatus.FULLY_CHARGED
payment.captured_amount = order.total.gross.amount
- payment.save(update_fields=['captured_amount', 'charge_status'])
- order.events.create(
- type=OrderEvents.ORDER_MARKED_AS_PAID.value, user=request_user)
+ payment.save(update_fields=["captured_amount", "charge_status"])
+ order.events.create(type=OrderEvents.ORDER_MARKED_AS_PAID.value, user=request_user)
def create_transaction(
- payment: Payment, kind: str, payment_information: Dict,
- gateway_response: GatewayResponse = None, error_msg=None
+ payment: Payment,
+ kind: str,
+ payment_information: PaymentData,
+ gateway_response: GatewayResponse = None,
+ error_msg=None,
) -> Transaction:
"""Create a transaction based on transaction kind and gateway response."""
@@ -196,7 +213,7 @@ def create_transaction(
amount=payment_information.amount,
currency=payment_information.currency,
error=error_msg,
- raw_response={}
+ raw_response={},
)
txn = Transaction.objects.create(
@@ -207,7 +224,7 @@ def create_transaction(
amount=gateway_response.amount,
currency=gateway_response.currency,
error=gateway_response.error,
- gateway_response=gateway_response.raw_response or {}
+ gateway_response=gateway_response.raw_response or {},
)
return txn
@@ -216,25 +233,24 @@ def gateway_get_client_token(gateway_name: str):
"""Gets client token, that will be used as a customer's identificator for
client-side tokenization of the chosen payment method.
"""
- gateway, gateway_params = get_payment_gateway(gateway_name)
- return gateway.get_client_token(connection_params=gateway_params)
+ gateway, gateway_config = get_payment_gateway(gateway_name)
+ return gateway.get_client_token(config=gateway_config)
def clean_capture(payment: Payment, amount: Decimal):
"""Check if payment can be captured."""
if amount <= 0:
- raise PaymentError('Amount should be a positive number.')
+ raise PaymentError("Amount should be a positive number.")
if not payment.can_capture():
- raise PaymentError('This payment cannot be captured.')
- if amount > payment.total or amount > (
- payment.total - payment.captured_amount):
- raise PaymentError('Unable to capture more than authorized amount.')
+ raise PaymentError("This payment cannot be captured.")
+ if amount > payment.total or amount > (payment.total - payment.captured_amount):
+ raise PaymentError("Unable to charge more than un-captured amount.")
def clean_authorize(payment: Payment):
"""Check if payment can be authorized."""
if not payment.can_authorize():
- raise PaymentError('Charged transactions cannot be authorized again.')
+ raise PaymentError("Charged transactions cannot be authorized again.")
def clean_mark_order_as_paid(order: Order):
@@ -242,8 +258,10 @@ def clean_mark_order_as_paid(order: Order):
if order.payments.exists():
raise PaymentError(
pgettext_lazy(
- 'Mark order as paid validation error',
- 'Orders with payments can not be manually marked as paid.'))
+ "Mark order as paid validation error",
+ "Orders with payments can not be manually marked as paid.",
+ )
+ )
def call_gateway(operation_type, payment, payment_token, **extra_params):
@@ -251,7 +269,7 @@ def call_gateway(operation_type, payment, payment_token, **extra_params):
Additionally does validation of the returned gateway response.
"""
- gateway, connection_params = get_payment_gateway(payment.gateway)
+ gateway, gateway_config = get_payment_gateway(payment.gateway)
gateway_response = None
error_msg = None
@@ -262,8 +280,7 @@ def call_gateway(operation_type, payment, payment_token, **extra_params):
try:
func = get_gateway_operation_func(gateway, operation_type)
except AttributeError:
- error_msg = 'Gateway doesn\'t implement {} operation'.format(
- operation_type.name)
+ error_msg = "Gateway doesn't implement {} operation".format(operation_type.name)
logger.exception(error_msg)
raise PaymentError(error_msg)
@@ -274,25 +291,26 @@ def call_gateway(operation_type, payment, payment_token, **extra_params):
default_transaction_kind = TransactionKind.CAPTURE
if operation_type != OperationType.PROCESS_PAYMENT:
default_transaction_kind = getattr(
- TransactionKind, OperationType(operation_type).name)
+ TransactionKind, OperationType(operation_type).name
+ )
# Validate the default transaction kind
if default_transaction_kind not in dict(TransactionKind.CHOICES):
- error_msg = 'The default transaction kind is invalid'
+ error_msg = "The default transaction kind is invalid"
logger.exception(error_msg)
raise PaymentError(error_msg)
try:
gateway_response = func(
- payment_information=payment_information,
- connection_params=connection_params)
+ payment_information=payment_information, config=gateway_config
+ )
validate_gateway_response(gateway_response)
except GatewayError:
- error_msg = 'Gateway response validation failed'
+ error_msg = "Gateway response validation failed"
logger.exception(error_msg)
gateway_response = None # Set response empty as the validation failed
except Exception:
- error_msg = 'Gateway encountered an error'
+ error_msg = "Gateway encountered an error"
logger.exception(error_msg)
finally:
payment_transaction = create_transaction(
@@ -300,12 +318,12 @@ def call_gateway(operation_type, payment, payment_token, **extra_params):
kind=default_transaction_kind,
payment_information=payment_information,
error_msg=error_msg,
- gateway_response=gateway_response)
+ gateway_response=gateway_response,
+ )
if not payment_transaction.is_success:
# Attempt to get errors from response, if none raise a generic one
- raise PaymentError(
- payment_transaction.error or GENERIC_TRANSACTION_ERROR)
+ raise PaymentError(payment_transaction.error or GENERIC_TRANSACTION_ERROR)
return payment_transaction
@@ -314,21 +332,22 @@ def validate_gateway_response(response: GatewayResponse):
"""Validates response to be a correct format for Saleor to process."""
if not isinstance(response, GatewayResponse):
- raise GatewayError('Gateway needs to return a GatewayResponse obj')
+ raise GatewayError("Gateway needs to return a GatewayResponse obj")
if response.kind not in ALLOWED_GATEWAY_KINDS:
raise GatewayError(
- 'Gateway response kind must be one of {}'.format(
- sorted(ALLOWED_GATEWAY_KINDS)))
+ "Gateway response kind must be one of {}".format(
+ sorted(ALLOWED_GATEWAY_KINDS)
+ )
+ )
if response.currency != settings.DEFAULT_CURRENCY:
- logger.warning('Transaction currency is different than Saleor\'s.')
+ logger.warning("Transaction currency is different than Saleor's.")
try:
json.dumps(response.raw_response, cls=DjangoJSONEncoder)
except (TypeError, ValueError):
- raise GatewayError(
- 'Gateway response needs to be json serializable')
+ raise GatewayError("Gateway response needs to be json serializable")
def _gateway_postprocess(transaction, payment):
@@ -343,33 +362,35 @@ def _gateway_postprocess(transaction, payment):
if payment.get_charge_amount() <= 0:
payment.charge_status = ChargeStatus.FULLY_CHARGED
- payment.save(update_fields=['charge_status', 'captured_amount'])
+ payment.save(update_fields=["charge_status", "captured_amount"])
order = payment.order
if order and order.is_fully_paid():
handle_fully_paid_order(order)
elif transaction_kind == TransactionKind.VOID:
payment.is_active = False
- payment.save(update_fields=['is_active'])
+ payment.save(update_fields=["is_active"])
elif transaction_kind == TransactionKind.REFUND:
- changed_fields = ['captured_amount']
+ changed_fields = ["captured_amount"]
payment.captured_amount -= transaction.amount
payment.charge_status = ChargeStatus.PARTIALLY_REFUNDED
if payment.captured_amount <= 0:
payment.charge_status = ChargeStatus.FULLY_REFUNDED
payment.is_active = False
- changed_fields += ['charge_status', 'is_active']
+ changed_fields += ["charge_status", "is_active"]
payment.save(update_fields=changed_fields)
@require_active_payment
-def gateway_process_payment(
- payment: Payment, payment_token: str) -> Transaction:
+def gateway_process_payment(payment: Payment, payment_token: str) -> Transaction:
"""Performs whole payment process on a gateway."""
transaction = call_gateway(
operation_type=OperationType.PROCESS_PAYMENT,
- payment=payment, payment_token=payment_token, amount=payment.total)
+ payment=payment,
+ payment_token=payment_token,
+ amount=payment.total,
+ )
_gateway_postprocess(transaction, payment)
return transaction
@@ -385,8 +406,8 @@ def gateway_authorize(payment: Payment, payment_token: str) -> Transaction:
clean_authorize(payment)
return call_gateway(
- operation_type=OperationType.AUTH,
- payment=payment, payment_token=payment_token)
+ operation_type=OperationType.AUTH, payment=payment, payment_token=payment_token
+ )
@require_active_payment
@@ -396,18 +417,19 @@ def gateway_capture(payment: Payment, amount: Decimal = None) -> Transaction:
amount = payment.get_charge_amount()
clean_capture(payment, amount)
- if get_can_gateway_authorize(payment):
- auth_transaction = payment.transactions.filter(
- kind=TransactionKind.AUTH, is_success=True).first()
- if auth_transaction is None:
- raise PaymentError('Cannot capture unauthorized transaction')
- payment_token = auth_transaction.token
- else:
- payment_token = payment.token
+ auth_transaction = payment.transactions.filter(
+ kind=TransactionKind.AUTH, is_success=True
+ ).first()
+ if auth_transaction is None:
+ raise PaymentError("Cannot capture unauthorized transaction")
+ payment_token = auth_transaction.token
transaction = call_gateway(
operation_type=OperationType.CAPTURE,
- payment=payment, payment_token=payment_token, amount=amount)
+ payment=payment,
+ payment_token=payment_token,
+ amount=amount,
+ )
_gateway_postprocess(transaction, payment)
return transaction
@@ -416,17 +438,18 @@ def gateway_capture(payment: Payment, amount: Decimal = None) -> Transaction:
@require_active_payment
def gateway_void(payment) -> Transaction:
if not payment.can_void():
- raise PaymentError('Only pre-authorized transactions can be voided.')
+ raise PaymentError("Only pre-authorized transactions can be voided.")
auth_transaction = payment.transactions.filter(
- kind=TransactionKind.AUTH, is_success=True).first()
+ kind=TransactionKind.AUTH, is_success=True
+ ).first()
if auth_transaction is None:
- raise PaymentError('Cannot void unauthorized transaction')
+ raise PaymentError("Cannot void unauthorized transaction")
payment_token = auth_transaction.token
transaction = call_gateway(
- operation_type=OperationType.VOID,
- payment=payment, payment_token=payment_token)
+ operation_type=OperationType.VOID, payment=payment, payment_token=payment_token
+ )
_gateway_postprocess(transaction, payment)
return transaction
@@ -442,22 +465,26 @@ def gateway_refund(payment, amount: Decimal = None) -> Transaction:
amount = payment.captured_amount
if not payment.can_refund():
- raise PaymentError('This payment cannot be refunded.')
+ raise PaymentError("This payment cannot be refunded.")
if amount <= 0:
- raise PaymentError('Amount should be a positive number.')
+ raise PaymentError("Amount should be a positive number.")
if amount > payment.captured_amount:
- raise PaymentError('Cannot refund more than captured')
+ raise PaymentError("Cannot refund more than captured")
transaction = payment.transactions.filter(
- kind=TransactionKind.CAPTURE, is_success=True).first()
+ kind=TransactionKind.CAPTURE, is_success=True
+ ).first()
if transaction is None:
- raise PaymentError('Cannot refund uncaptured/uncharged transaction')
+ raise PaymentError("Cannot refund uncaptured transaction")
payment_token = transaction.token
transaction = call_gateway(
operation_type=OperationType.REFUND,
- payment=payment, payment_token=payment_token, amount=amount)
+ payment=payment,
+ payment_token=payment_token,
+ amount=amount,
+ )
_gateway_postprocess(transaction, payment)
return transaction
diff --git a/saleor/settings.py b/saleor/settings.py
index 59ca18562e..5599df1491 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -12,7 +12,7 @@ from . import __version__
def get_list(text):
- return [item.strip() for item in text.split(',')]
+ return [item.strip() for item in text.split(",")]
def get_bool_from_env(name, default_value):
@@ -21,436 +21,439 @@ def get_bool_from_env(name, default_value):
try:
return ast.literal_eval(value)
except ValueError as e:
- raise ValueError(
- '{} is an invalid value for {}'.format(value, name)) from e
+ raise ValueError("{} is an invalid value for {}".format(value, name)) from e
return default_value
-DEBUG = get_bool_from_env('DEBUG', True)
+DEBUG = get_bool_from_env("DEBUG", True)
SITE_ID = 1
-PROJECT_ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), '..'))
+PROJECT_ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), ".."))
-ROOT_URLCONF = 'saleor.urls'
+ROOT_URLCONF = "saleor.urls"
-WSGI_APPLICATION = 'saleor.wsgi.application'
+WSGI_APPLICATION = "saleor.wsgi.application"
ADMINS = (
# ('Your Name', '[email protected]'),
)
MANAGERS = ADMINS
-INTERNAL_IPS = get_list(os.environ.get('INTERNAL_IPS', '127.0.0.1'))
+INTERNAL_IPS = get_list(os.environ.get("INTERNAL_IPS", "127.0.0.1"))
# Some cloud providers (Heroku) export REDIS_URL variable instead of CACHE_URL
-REDIS_URL = os.environ.get('REDIS_URL')
+REDIS_URL = os.environ.get("REDIS_URL")
if REDIS_URL:
- CACHE_URL = os.environ.setdefault('CACHE_URL', REDIS_URL)
-CACHES = {'default': django_cache_url.config()}
+ CACHE_URL = os.environ.setdefault("CACHE_URL", REDIS_URL)
+CACHES = {"default": django_cache_url.config()}
DATABASES = {
- 'default': dj_database_url.config(
- default='postgres://saleor:saleor@localhost:5432/saleor',
- conn_max_age=600)}
+ "default": dj_database_url.config(
+ default="postgres://saleor:saleor@localhost:5432/saleor", conn_max_age=600
+ )
+}
-TIME_ZONE = 'America/Chicago'
-LANGUAGE_CODE = 'en'
+TIME_ZONE = "America/Chicago"
+LANGUAGE_CODE = "en"
LANGUAGES = [
- ('ar', _('Arabic')),
- ('az', _('Azerbaijani')),
- ('bg', _('Bulgarian')),
- ('bn', _('Bengali')),
- ('ca', _('Catalan')),
- ('cs', _('Czech')),
- ('da', _('Danish')),
- ('de', _('German')),
- ('en', _('English')),
- ('es', _('Spanish')),
- ('et', _('Estonian')),
- ('fa', _('Persian')),
- ('fr', _('French')),
- ('hi', _('Hindi')),
- ('hu', _('Hungarian')),
- ('hy', _('Armenian')),
- ('id', _('Indonesian')),
- ('it', _('Italian')),
- ('ja', _('Japanese')),
- ('ko', _('Korean')),
- ('mn', _('Mongolian')),
- ('nb', _('Norwegian')),
- ('nl', _('Dutch')),
- ('pl', _('Polish')),
- ('pt', _('Portuguese')),
- ('pt-br', _('Brazilian Portuguese')),
- ('ro', _('Romanian')),
- ('ru', _('Russian')),
- ('sk', _('Slovak')),
- ('sr', _('Serbian')),
- ('sw', _('Swahili')),
- ('sv', _('Swedish')),
- ('th', _('Thai')),
- ('tr', _('Turkish')),
- ('uk', _('Ukrainian')),
- ('vi', _('Vietnamese')),
- ('zh-hans', _('Simplified Chinese')),
- ('zh-hant', _('Traditional Chinese'))]
-LOCALE_PATHS = [os.path.join(PROJECT_ROOT, 'locale')]
+ ("ar", _("Arabic")),
+ ("az", _("Azerbaijani")),
+ ("bg", _("Bulgarian")),
+ ("bn", _("Bengali")),
+ ("ca", _("Catalan")),
+ ("cs", _("Czech")),
+ ("da", _("Danish")),
+ ("de", _("German")),
+ ("en", _("English")),
+ ("es", _("Spanish")),
+ ("et", _("Estonian")),
+ ("fa", _("Persian")),
+ ("fr", _("French")),
+ ("hi", _("Hindi")),
+ ("hu", _("Hungarian")),
+ ("hy", _("Armenian")),
+ ("id", _("Indonesian")),
+ ("it", _("Italian")),
+ ("ja", _("Japanese")),
+ ("ko", _("Korean")),
+ ("mn", _("Mongolian")),
+ ("nb", _("Norwegian")),
+ ("nl", _("Dutch")),
+ ("pl", _("Polish")),
+ ("pt", _("Portuguese")),
+ ("pt-br", _("Brazilian Portuguese")),
+ ("ro", _("Romanian")),
+ ("ru", _("Russian")),
+ ("sk", _("Slovak")),
+ ("sr", _("Serbian")),
+ ("sw", _("Swahili")),
+ ("sv", _("Swedish")),
+ ("th", _("Thai")),
+ ("tr", _("Turkish")),
+ ("uk", _("Ukrainian")),
+ ("vi", _("Vietnamese")),
+ ("zh-hans", _("Simplified Chinese")),
+ ("zh-hant", _("Traditional Chinese")),
+]
+LOCALE_PATHS = [os.path.join(PROJECT_ROOT, "locale")]
USE_I18N = True
USE_L10N = True
USE_TZ = True
-FORM_RENDERER = 'django.forms.renderers.TemplatesSetting'
+FORM_RENDERER = "django.forms.renderers.TemplatesSetting"
-EMAIL_URL = os.environ.get('EMAIL_URL')
-SENDGRID_USERNAME = os.environ.get('SENDGRID_USERNAME')
-SENDGRID_PASSWORD = os.environ.get('SENDGRID_PASSWORD')
+EMAIL_URL = os.environ.get("EMAIL_URL")
+SENDGRID_USERNAME = os.environ.get("SENDGRID_USERNAME")
+SENDGRID_PASSWORD = os.environ.get("SENDGRID_PASSWORD")
if not EMAIL_URL and SENDGRID_USERNAME and SENDGRID_PASSWORD:
- EMAIL_URL = 'smtp://%s:%[email protected]:587/?tls=True' % (
- SENDGRID_USERNAME, SENDGRID_PASSWORD)
-email_config = dj_email_url.parse(EMAIL_URL or 'console://')
-
-EMAIL_FILE_PATH = email_config['EMAIL_FILE_PATH']
-EMAIL_HOST_USER = email_config['EMAIL_HOST_USER']
-EMAIL_HOST_PASSWORD = email_config['EMAIL_HOST_PASSWORD']
-EMAIL_HOST = email_config['EMAIL_HOST']
-EMAIL_PORT = email_config['EMAIL_PORT']
-EMAIL_BACKEND = email_config['EMAIL_BACKEND']
-EMAIL_USE_TLS = email_config['EMAIL_USE_TLS']
-EMAIL_USE_SSL = email_config['EMAIL_USE_SSL']
-
-ENABLE_SSL = get_bool_from_env('ENABLE_SSL', False)
+ EMAIL_URL = "smtp://%s:%[email protected]:587/?tls=True" % (
+ SENDGRID_USERNAME,
+ SENDGRID_PASSWORD,
+ )
+email_config = dj_email_url.parse(EMAIL_URL or "console://")
+
+EMAIL_FILE_PATH = email_config["EMAIL_FILE_PATH"]
+EMAIL_HOST_USER = email_config["EMAIL_HOST_USER"]
+EMAIL_HOST_PASSWORD = email_config["EMAIL_HOST_PASSWORD"]
+EMAIL_HOST = email_config["EMAIL_HOST"]
+EMAIL_PORT = email_config["EMAIL_PORT"]
+EMAIL_BACKEND = email_config["EMAIL_BACKEND"]
+EMAIL_USE_TLS = email_config["EMAIL_USE_TLS"]
+EMAIL_USE_SSL = email_config["EMAIL_USE_SSL"]
+
+ENABLE_SSL = get_bool_from_env("ENABLE_SSL", False)
if ENABLE_SSL:
SECURE_SSL_REDIRECT = not DEBUG
-DEFAULT_FROM_EMAIL = os.environ.get('DEFAULT_FROM_EMAIL', EMAIL_HOST_USER)
-ORDER_FROM_EMAIL = os.getenv('ORDER_FROM_EMAIL', DEFAULT_FROM_EMAIL)
+DEFAULT_FROM_EMAIL = os.environ.get("DEFAULT_FROM_EMAIL", EMAIL_HOST_USER)
+ORDER_FROM_EMAIL = os.getenv("ORDER_FROM_EMAIL", DEFAULT_FROM_EMAIL)
-MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
-MEDIA_URL = os.environ.get('MEDIA_URL', '/media/')
+MEDIA_ROOT = os.path.join(PROJECT_ROOT, "media")
+MEDIA_URL = os.environ.get("MEDIA_URL", "/media/")
-STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
-STATIC_URL = os.environ.get('STATIC_URL', '/static/')
+STATIC_ROOT = os.path.join(PROJECT_ROOT, "static")
+STATIC_URL = os.environ.get("STATIC_URL", "/static/")
STATICFILES_DIRS = [
- ('assets', os.path.join(PROJECT_ROOT, 'saleor', 'static', 'assets')),
- ('favicons', os.path.join(PROJECT_ROOT, 'saleor', 'static', 'favicons')),
- ('images', os.path.join(PROJECT_ROOT, 'saleor', 'static', 'images')),
- ('dashboard/images', os.path.join(
- PROJECT_ROOT, 'saleor', 'static', 'dashboard', 'images'))]
+ ("assets", os.path.join(PROJECT_ROOT, "saleor", "static", "assets")),
+ ("favicons", os.path.join(PROJECT_ROOT, "saleor", "static", "favicons")),
+ ("images", os.path.join(PROJECT_ROOT, "saleor", "static", "images")),
+ (
+ "dashboard/images",
+ os.path.join(PROJECT_ROOT, "saleor", "static", "dashboard", "images"),
+ ),
+]
STATICFILES_FINDERS = [
- 'django.contrib.staticfiles.finders.FileSystemFinder',
- 'django.contrib.staticfiles.finders.AppDirectoriesFinder']
+ "django.contrib.staticfiles.finders.FileSystemFinder",
+ "django.contrib.staticfiles.finders.AppDirectoriesFinder",
+]
context_processors = [
- 'django.contrib.auth.context_processors.auth',
- 'django.template.context_processors.debug',
- 'django.template.context_processors.i18n',
- 'django.template.context_processors.media',
- 'django.template.context_processors.static',
- 'django.template.context_processors.tz',
- 'django.contrib.messages.context_processors.messages',
- 'django.template.context_processors.request',
- 'saleor.core.context_processors.default_currency',
- 'saleor.checkout.context_processors.checkout_counter',
- 'saleor.core.context_processors.search_enabled',
- 'saleor.site.context_processors.site',
- 'social_django.context_processors.backends',
- 'social_django.context_processors.login_redirect']
+ "django.contrib.auth.context_processors.auth",
+ "django.template.context_processors.debug",
+ "django.template.context_processors.i18n",
+ "django.template.context_processors.media",
+ "django.template.context_processors.static",
+ "django.template.context_processors.tz",
+ "django.contrib.messages.context_processors.messages",
+ "django.template.context_processors.request",
+ "saleor.core.context_processors.default_currency",
+ "saleor.checkout.context_processors.checkout_counter",
+ "saleor.core.context_processors.search_enabled",
+ "saleor.site.context_processors.site",
+ "social_django.context_processors.backends",
+ "social_django.context_processors.login_redirect",
+]
loaders = [
- 'django.template.loaders.filesystem.Loader',
- 'django.template.loaders.app_directories.Loader']
+ "django.template.loaders.filesystem.Loader",
+ "django.template.loaders.app_directories.Loader",
+]
if not DEBUG:
- loaders = [('django.template.loaders.cached.Loader', loaders)]
-
-TEMPLATES = [{
- 'BACKEND': 'django.template.backends.django.DjangoTemplates',
- 'DIRS': [os.path.join(PROJECT_ROOT, 'templates')],
- 'OPTIONS': {
- 'debug': DEBUG,
- 'context_processors': context_processors,
- 'loaders': loaders,
- 'string_if_invalid': '<< MISSING VARIABLE "%s" >>' if DEBUG else ''}}]
+ loaders = [("django.template.loaders.cached.Loader", loaders)]
+
+TEMPLATES = [
+ {
+ "BACKEND": "django.template.backends.django.DjangoTemplates",
+ "DIRS": [os.path.join(PROJECT_ROOT, "templates")],
+ "OPTIONS": {
+ "debug": DEBUG,
+ "context_processors": context_processors,
+ "loaders": loaders,
+ "string_if_invalid": '<< MISSING VARIABLE "%s" >>' if DEBUG else "",
+ },
+ }
+]
# Make this unique, and don't share it with anybody.
-SECRET_KEY = os.environ.get('SECRET_KEY')
+SECRET_KEY = os.environ.get("SECRET_KEY")
MIDDLEWARE = [
- 'django.contrib.sessions.middleware.SessionMiddleware',
- 'django.middleware.security.SecurityMiddleware',
- 'django.middleware.common.CommonMiddleware',
- 'django.middleware.csrf.CsrfViewMiddleware',
- 'django.contrib.auth.middleware.AuthenticationMiddleware',
- 'django.contrib.messages.middleware.MessageMiddleware',
- 'django.middleware.locale.LocaleMiddleware',
- 'django_babel.middleware.LocaleMiddleware',
- 'saleor.core.middleware.discounts',
- 'saleor.core.middleware.google_analytics',
- 'saleor.core.middleware.country',
- 'saleor.core.middleware.currency',
- 'saleor.core.middleware.site',
- 'saleor.core.middleware.taxes',
- 'social_django.middleware.SocialAuthExceptionMiddleware',
- 'impersonate.middleware.ImpersonateMiddleware',
- 'saleor.graphql.middleware.jwt_middleware'
+ "django.contrib.sessions.middleware.SessionMiddleware",
+ "django.middleware.security.SecurityMiddleware",
+ "django.middleware.common.CommonMiddleware",
+ "django.middleware.csrf.CsrfViewMiddleware",
+ "django.contrib.auth.middleware.AuthenticationMiddleware",
+ "django.contrib.messages.middleware.MessageMiddleware",
+ "django.middleware.locale.LocaleMiddleware",
+ "django_babel.middleware.LocaleMiddleware",
+ "saleor.core.middleware.discounts",
+ "saleor.core.middleware.google_analytics",
+ "saleor.core.middleware.country",
+ "saleor.core.middleware.currency",
+ "saleor.core.middleware.site",
+ "saleor.core.middleware.taxes",
+ "social_django.middleware.SocialAuthExceptionMiddleware",
+ "impersonate.middleware.ImpersonateMiddleware",
+ "saleor.graphql.middleware.jwt_middleware",
]
INSTALLED_APPS = [
# External apps that need to go before django's
- 'storages',
-
+ "storages",
# Django modules
- 'django.contrib.contenttypes',
- 'django.contrib.sessions',
- 'django.contrib.messages',
- 'django.contrib.sitemaps',
- 'django.contrib.sites',
- 'django.contrib.staticfiles',
- 'django.contrib.auth',
- 'django.contrib.postgres',
- 'django.forms',
-
+ "django.contrib.contenttypes",
+ "django.contrib.sessions",
+ "django.contrib.messages",
+ "django.contrib.sitemaps",
+ "django.contrib.sites",
+ "django.contrib.staticfiles",
+ "django.contrib.auth",
+ "django.contrib.postgres",
+ "django.forms",
# Local apps
- 'saleor.account',
- 'saleor.discount',
- 'saleor.product',
- 'saleor.checkout',
- 'saleor.core',
- 'saleor.graphql',
- 'saleor.menu',
- 'saleor.order',
- 'saleor.dashboard',
- 'saleor.seo',
- 'saleor.shipping',
- 'saleor.search',
- 'saleor.site',
- 'saleor.data_feeds',
- 'saleor.page',
- 'saleor.payment',
-
+ "saleor.account",
+ "saleor.discount",
+ "saleor.product",
+ "saleor.checkout",
+ "saleor.core",
+ "saleor.graphql",
+ "saleor.menu",
+ "saleor.order",
+ "saleor.dashboard",
+ "saleor.seo",
+ "saleor.shipping",
+ "saleor.search",
+ "saleor.site",
+ "saleor.data_feeds",
+ "saleor.page",
+ "saleor.payment",
# External apps
- 'versatileimagefield',
- 'django_babel',
- 'bootstrap4',
- 'django_measurement',
- 'django_prices',
- 'django_prices_openexchangerates',
- 'django_prices_vatlayer',
- 'graphene_django',
- 'mptt',
- 'webpack_loader',
- 'social_django',
- 'django_countries',
- 'django_filters',
- 'django_celery_results',
- 'impersonate',
- 'phonenumber_field',
- 'captcha']
-
-
-ENABLE_DEBUG_TOOLBAR = get_bool_from_env('ENABLE_DEBUG_TOOLBAR', False)
+ "versatileimagefield",
+ "django_babel",
+ "bootstrap4",
+ "django_measurement",
+ "django_prices",
+ "django_prices_openexchangerates",
+ "django_prices_vatlayer",
+ "graphene_django",
+ "mptt",
+ "webpack_loader",
+ "social_django",
+ "django_countries",
+ "django_filters",
+ "django_celery_results",
+ "impersonate",
+ "phonenumber_field",
+ "captcha",
+]
+
+
+ENABLE_DEBUG_TOOLBAR = get_bool_from_env("ENABLE_DEBUG_TOOLBAR", False)
if ENABLE_DEBUG_TOOLBAR:
- MIDDLEWARE.append(
- 'debug_toolbar.middleware.DebugToolbarMiddleware')
- INSTALLED_APPS.append('debug_toolbar')
+ MIDDLEWARE.append("debug_toolbar.middleware.DebugToolbarMiddleware")
+ INSTALLED_APPS.append("debug_toolbar")
DEBUG_TOOLBAR_PANELS = [
# adds a request history to the debug toolbar
- 'ddt_request_history.panels.request_history.RequestHistoryPanel',
-
- 'debug_toolbar.panels.versions.VersionsPanel',
- 'debug_toolbar.panels.timer.TimerPanel',
- 'debug_toolbar.panels.settings.SettingsPanel',
- 'debug_toolbar.panels.headers.HeadersPanel',
- 'debug_toolbar.panels.request.RequestPanel',
- 'debug_toolbar.panels.sql.SQLPanel',
- 'debug_toolbar.panels.templates.TemplatesPanel',
- 'debug_toolbar.panels.staticfiles.StaticFilesPanel',
- 'debug_toolbar.panels.cache.CachePanel',
- 'debug_toolbar.panels.signals.SignalsPanel',
- 'debug_toolbar.panels.logging.LoggingPanel',
- 'debug_toolbar.panels.redirects.RedirectsPanel',
- 'debug_toolbar.panels.profiling.ProfilingPanel',
+ "ddt_request_history.panels.request_history.RequestHistoryPanel",
+ "debug_toolbar.panels.versions.VersionsPanel",
+ "debug_toolbar.panels.timer.TimerPanel",
+ "debug_toolbar.panels.settings.SettingsPanel",
+ "debug_toolbar.panels.headers.HeadersPanel",
+ "debug_toolbar.panels.request.RequestPanel",
+ "debug_toolbar.panels.sql.SQLPanel",
+ "debug_toolbar.panels.templates.TemplatesPanel",
+ "debug_toolbar.panels.staticfiles.StaticFilesPanel",
+ "debug_toolbar.panels.cache.CachePanel",
+ "debug_toolbar.panels.signals.SignalsPanel",
+ "debug_toolbar.panels.logging.LoggingPanel",
+ "debug_toolbar.panels.redirects.RedirectsPanel",
+ "debug_toolbar.panels.profiling.ProfilingPanel",
]
- DEBUG_TOOLBAR_CONFIG = {
- 'RESULTS_CACHE_SIZE': 100}
+ DEBUG_TOOLBAR_CONFIG = {"RESULTS_CACHE_SIZE": 100}
-ENABLE_SILK = get_bool_from_env('ENABLE_SILK', False)
+ENABLE_SILK = get_bool_from_env("ENABLE_SILK", False)
if ENABLE_SILK:
- MIDDLEWARE.insert(0, 'silk.middleware.SilkyMiddleware')
- INSTALLED_APPS.append('silk')
+ MIDDLEWARE.insert(0, "silk.middleware.SilkyMiddleware")
+ INSTALLED_APPS.append("silk")
LOGGING = {
- 'version': 1,
- 'disable_existing_loggers': False,
- 'root': {
- 'level': 'INFO',
- 'handlers': ['console']},
- 'formatters': {
- 'verbose': {
- 'format': (
- '%(levelname)s %(name)s %(message)s'
- ' [PID:%(process)d:%(threadName)s]')},
- 'simple': {
- 'format': '%(levelname)s %(message)s'}},
- 'filters': {
- 'require_debug_false': {
- '()': 'django.utils.log.RequireDebugFalse'}},
- 'handlers': {
- 'mail_admins': {
- 'level': 'ERROR',
- 'filters': ['require_debug_false'],
- 'class': 'django.utils.log.AdminEmailHandler'},
- 'console': {
- 'level': 'DEBUG',
- 'class': 'logging.StreamHandler',
- 'formatter': 'verbose'}},
- 'loggers': {
- 'django': {
- 'handlers': ['console', 'mail_admins'],
- 'level': 'INFO',
- 'propagate': True},
- 'django.server': {
- 'handlers': ['console'],
- 'level': 'INFO',
- 'propagate': True},
- 'saleor': {
- 'handlers': ['console'],
- 'level': 'DEBUG',
- 'propagate': True}}}
-
-AUTH_USER_MODEL = 'account.User'
-
-LOGIN_URL = '/account/login/'
-
-DEFAULT_COUNTRY = os.environ.get('DEFAULT_COUNTRY', 'US')
-DEFAULT_CURRENCY = os.environ.get('DEFAULT_CURRENCY', 'USD')
+ "version": 1,
+ "disable_existing_loggers": False,
+ "root": {"level": "INFO", "handlers": ["console"]},
+ "formatters": {
+ "verbose": {
+ "format": (
+ "%(levelname)s %(name)s %(message)s" " [PID:%(process)d:%(threadName)s]"
+ )
+ },
+ "simple": {"format": "%(levelname)s %(message)s"},
+ },
+ "filters": {"require_debug_false": {"()": "django.utils.log.RequireDebugFalse"}},
+ "handlers": {
+ "mail_admins": {
+ "level": "ERROR",
+ "filters": ["require_debug_false"],
+ "class": "django.utils.log.AdminEmailHandler",
+ },
+ "console": {
+ "level": "DEBUG",
+ "class": "logging.StreamHandler",
+ "formatter": "verbose",
+ },
+ },
+ "loggers": {
+ "django": {
+ "handlers": ["console", "mail_admins"],
+ "level": "INFO",
+ "propagate": True,
+ },
+ "django.server": {"handlers": ["console"], "level": "INFO", "propagate": True},
+ "saleor": {"handlers": ["console"], "level": "DEBUG", "propagate": True},
+ },
+}
+
+AUTH_USER_MODEL = "account.User"
+
+LOGIN_URL = "/account/login/"
+
+DEFAULT_COUNTRY = os.environ.get("DEFAULT_COUNTRY", "US")
+DEFAULT_CURRENCY = os.environ.get("DEFAULT_CURRENCY", "USD")
DEFAULT_DECIMAL_PLACES = get_currency_fraction(DEFAULT_CURRENCY)
DEFAULT_MAX_DIGITS = 12
AVAILABLE_CURRENCIES = [DEFAULT_CURRENCY]
COUNTRIES_OVERRIDE = {
- 'EU': pgettext_lazy(
- 'Name of political and economical union of european countries',
- 'European Union')}
+ "EU": pgettext_lazy(
+ "Name of political and economical union of european countries", "European Union"
+ )
+}
-OPENEXCHANGERATES_API_KEY = os.environ.get('OPENEXCHANGERATES_API_KEY')
+OPENEXCHANGERATES_API_KEY = os.environ.get("OPENEXCHANGERATES_API_KEY")
# VAT configuration
# Enabling vat requires valid vatlayer access key.
# If you are subscribed to a paid vatlayer plan, you can enable HTTPS.
-VATLAYER_ACCESS_KEY = os.environ.get('VATLAYER_ACCESS_KEY')
-VATLAYER_USE_HTTPS = get_bool_from_env('VATLAYER_USE_HTTPS', False)
+VATLAYER_ACCESS_KEY = os.environ.get("VATLAYER_ACCESS_KEY")
+VATLAYER_USE_HTTPS = get_bool_from_env("VATLAYER_USE_HTTPS", False)
ACCOUNT_ACTIVATION_DAYS = 3
-LOGIN_REDIRECT_URL = 'home'
+LOGIN_REDIRECT_URL = "home"
-GOOGLE_ANALYTICS_TRACKING_ID = os.environ.get('GOOGLE_ANALYTICS_TRACKING_ID')
+GOOGLE_ANALYTICS_TRACKING_ID = os.environ.get("GOOGLE_ANALYTICS_TRACKING_ID")
def get_host():
from django.contrib.sites.models import Site
+
return Site.objects.get_current().domain
PAYMENT_HOST = get_host
-PAYMENT_MODEL = 'order.Payment'
+PAYMENT_MODEL = "order.Payment"
-SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'
+SESSION_SERIALIZER = "django.contrib.sessions.serializers.JSONSerializer"
# Do not use cached session if locmem cache backend is used but fallback to use
# default django.contrib.sessions.backends.db instead
-if not CACHES['default']['BACKEND'].endswith('LocMemCache'):
- SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'
+if not CACHES["default"]["BACKEND"].endswith("LocMemCache"):
+ SESSION_ENGINE = "django.contrib.sessions.backends.cached_db"
-MESSAGE_TAGS = {
- messages.ERROR: 'danger'}
+MESSAGE_TAGS = {messages.ERROR: "danger"}
LOW_STOCK_THRESHOLD = 10
-MAX_CHECKOUT_LINE_QUANTITY = int(os.environ.get('MAX_CHECKOUT_LINE_QUANTITY', 50))
+MAX_CHECKOUT_LINE_QUANTITY = int(os.environ.get("MAX_CHECKOUT_LINE_QUANTITY", 50))
PAGINATE_BY = 16
DASHBOARD_PAGINATE_BY = 30
DASHBOARD_SEARCH_LIMIT = 5
bootstrap4 = {
- 'set_placeholder': False,
- 'set_required': False,
- 'success_css_class': '',
- 'form_renderers': {
- 'default': 'saleor.core.utils.form_renderer.FormRenderer'}}
+ "set_placeholder": False,
+ "set_required": False,
+ "success_css_class": "",
+ "form_renderers": {"default": "saleor.core.utils.form_renderer.FormRenderer"},
+}
-TEST_RUNNER = 'tests.runner.PytestTestRunner'
+TEST_RUNNER = "tests.runner.PytestTestRunner"
-ALLOWED_HOSTS = get_list(
- os.environ.get('ALLOWED_HOSTS', 'localhost,127.0.0.1'))
-ALLOWED_GRAPHQL_ORIGINS = os.environ.get('ALLOWED_GRAPHQL_ORIGINS', '*')
+ALLOWED_HOSTS = get_list(os.environ.get("ALLOWED_HOSTS", "localhost,127.0.0.1"))
+ALLOWED_GRAPHQL_ORIGINS = os.environ.get("ALLOWED_GRAPHQL_ORIGINS", "*")
-SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
+SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
# Amazon S3 configuration
-AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID')
-AWS_LOCATION = os.environ.get('AWS_LOCATION', '')
-AWS_MEDIA_BUCKET_NAME = os.environ.get('AWS_MEDIA_BUCKET_NAME')
-AWS_MEDIA_CUSTOM_DOMAIN = os.environ.get('AWS_MEDIA_CUSTOM_DOMAIN')
-AWS_QUERYSTRING_AUTH = get_bool_from_env('AWS_QUERYSTRING_AUTH', False)
-AWS_S3_CUSTOM_DOMAIN = os.environ.get('AWS_STATIC_CUSTOM_DOMAIN')
-AWS_S3_ENDPOINT_URL = os.environ.get('AWS_S3_ENDPOINT_URL', None)
-AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')
-AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME')
-AWS_DEFAULT_ACL = os.environ.get('AWS_DEFAULT_ACL', None)
+AWS_ACCESS_KEY_ID = os.environ.get("AWS_ACCESS_KEY_ID")
+AWS_LOCATION = os.environ.get("AWS_LOCATION", "")
+AWS_MEDIA_BUCKET_NAME = os.environ.get("AWS_MEDIA_BUCKET_NAME")
+AWS_MEDIA_CUSTOM_DOMAIN = os.environ.get("AWS_MEDIA_CUSTOM_DOMAIN")
+AWS_QUERYSTRING_AUTH = get_bool_from_env("AWS_QUERYSTRING_AUTH", False)
+AWS_S3_CUSTOM_DOMAIN = os.environ.get("AWS_STATIC_CUSTOM_DOMAIN")
+AWS_S3_ENDPOINT_URL = os.environ.get("AWS_S3_ENDPOINT_URL", None)
+AWS_SECRET_ACCESS_KEY = os.environ.get("AWS_SECRET_ACCESS_KEY")
+AWS_STORAGE_BUCKET_NAME = os.environ.get("AWS_STORAGE_BUCKET_NAME")
+AWS_DEFAULT_ACL = os.environ.get("AWS_DEFAULT_ACL", None)
if AWS_STORAGE_BUCKET_NAME:
- STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
+ STATICFILES_STORAGE = "storages.backends.s3boto3.S3Boto3Storage"
if AWS_MEDIA_BUCKET_NAME:
- DEFAULT_FILE_STORAGE = 'saleor.core.storages.S3MediaStorage'
+ DEFAULT_FILE_STORAGE = "saleor.core.storages.S3MediaStorage"
THUMBNAIL_DEFAULT_STORAGE = DEFAULT_FILE_STORAGE
-MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'
+MESSAGE_STORAGE = "django.contrib.messages.storage.session.SessionStorage"
VERSATILEIMAGEFIELD_RENDITION_KEY_SETS = {
- 'products': [
- ('product_gallery', 'thumbnail__540x540'),
- ('product_gallery_2x', 'thumbnail__1080x1080'),
- ('product_small', 'thumbnail__60x60'),
- ('product_small_2x', 'thumbnail__120x120'),
- ('product_list', 'thumbnail__255x255'),
- ('product_list_2x', 'thumbnail__510x510')],
- 'background_images': [
- ('header_image', 'thumbnail__1080x440')],
- 'user_avatars': [
- ('default', 'thumbnail__445x445'),
+ "products": [
+ ("product_gallery", "thumbnail__540x540"),
+ ("product_gallery_2x", "thumbnail__1080x1080"),
+ ("product_small", "thumbnail__60x60"),
+ ("product_small_2x", "thumbnail__120x120"),
+ ("product_list", "thumbnail__255x255"),
+ ("product_list_2x", "thumbnail__510x510"),
],
+ "background_images": [("header_image", "thumbnail__1080x440")],
+ "user_avatars": [("default", "thumbnail__445x445")],
}
VERSATILEIMAGEFIELD_SETTINGS = {
# Images should be pre-generated on Production environment
- 'create_images_on_demand': get_bool_from_env(
- 'CREATE_IMAGES_ON_DEMAND', DEBUG),
+ "create_images_on_demand": get_bool_from_env("CREATE_IMAGES_ON_DEMAND", DEBUG)
}
PLACEHOLDER_IMAGES = {
- 60: 'images/placeholder60x60.png',
- 120: 'images/placeholder120x120.png',
- 255: 'images/placeholder255x255.png',
- 540: 'images/placeholder540x540.png',
- 1080: 'images/placeholder1080x1080.png'}
+ 60: "images/placeholder60x60.png",
+ 120: "images/placeholder120x120.png",
+ 255: "images/placeholder255x255.png",
+ 540: "images/placeholder540x540.png",
+ 1080: "images/placeholder1080x1080.png",
+}
-DEFAULT_PLACEHOLDER = 'images/placeholder255x255.png'
+DEFAULT_PLACEHOLDER = "images/placeholder255x255.png"
WEBPACK_LOADER = {
- 'DEFAULT': {
- 'CACHE': not DEBUG,
- 'BUNDLE_DIR_NAME': 'assets/',
- 'STATS_FILE': os.path.join(PROJECT_ROOT, 'webpack-bundle.json'),
- 'POLL_INTERVAL': 0.1,
- 'IGNORE': [
- r'.+\.hot-update\.js',
- r'.+\.map']}}
+ "DEFAULT": {
+ "CACHE": not DEBUG,
+ "BUNDLE_DIR_NAME": "assets/",
+ "STATS_FILE": os.path.join(PROJECT_ROOT, "webpack-bundle.json"),
+ "POLL_INTERVAL": 0.1,
+ "IGNORE": [r".+\.hot-update\.js", r".+\.map"],
+ }
+}
LOGOUT_ON_PASSWORD_CHANGE = False
@@ -460,90 +463,88 @@ DB_SEARCH_ENABLED = True
# support deployment-dependant elastic enviroment variable
ES_URL = (
- os.environ.get('ELASTICSEARCH_URL')
- or os.environ.get('SEARCHBOX_URL')
- or os.environ.get('BONSAI_URL'))
+ os.environ.get("ELASTICSEARCH_URL")
+ or os.environ.get("SEARCHBOX_URL")
+ or os.environ.get("BONSAI_URL")
+)
ENABLE_SEARCH = bool(ES_URL) or DB_SEARCH_ENABLED # global search disabling
-SEARCH_BACKEND = 'saleor.search.backends.postgresql'
+SEARCH_BACKEND = "saleor.search.backends.postgresql"
if ES_URL:
- SEARCH_BACKEND = 'saleor.search.backends.elasticsearch'
- INSTALLED_APPS.append('django_elasticsearch_dsl')
- ELASTICSEARCH_DSL = {
- 'default': {
- 'hosts': ES_URL}}
+ SEARCH_BACKEND = "saleor.search.backends.elasticsearch"
+ INSTALLED_APPS.append("django_elasticsearch_dsl")
+ ELASTICSEARCH_DSL = {"default": {"hosts": ES_URL}}
AUTHENTICATION_BACKENDS = [
- 'saleor.account.backends.facebook.CustomFacebookOAuth2',
- 'saleor.account.backends.google.CustomGoogleOAuth2',
- 'graphql_jwt.backends.JSONWebTokenBackend',
- 'django.contrib.auth.backends.ModelBackend']
+ "saleor.account.backends.facebook.CustomFacebookOAuth2",
+ "saleor.account.backends.google.CustomGoogleOAuth2",
+ "graphql_jwt.backends.JSONWebTokenBackend",
+ "django.contrib.auth.backends.ModelBackend",
+]
SOCIAL_AUTH_PIPELINE = [
- 'social_core.pipeline.social_auth.social_details',
- 'social_core.pipeline.social_auth.social_uid',
- 'social_core.pipeline.social_auth.auth_allowed',
- 'social_core.pipeline.social_auth.social_user',
- 'social_core.pipeline.social_auth.associate_by_email',
- 'social_core.pipeline.user.create_user',
- 'social_core.pipeline.social_auth.associate_user',
- 'social_core.pipeline.social_auth.load_extra_data',
- 'social_core.pipeline.user.user_details']
+ "social_core.pipeline.social_auth.social_details",
+ "social_core.pipeline.social_auth.social_uid",
+ "social_core.pipeline.social_auth.auth_allowed",
+ "social_core.pipeline.social_auth.social_user",
+ "social_core.pipeline.social_auth.associate_by_email",
+ "social_core.pipeline.user.create_user",
+ "social_core.pipeline.social_auth.associate_user",
+ "social_core.pipeline.social_auth.load_extra_data",
+ "social_core.pipeline.user.user_details",
+]
SOCIAL_AUTH_USERNAME_IS_FULL_EMAIL = True
SOCIAL_AUTH_USER_MODEL = AUTH_USER_MODEL
-SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']
-SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = {
- 'fields': 'id, email'}
+SOCIAL_AUTH_FACEBOOK_SCOPE = ["email"]
+SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = {"fields": "id, email"}
# As per March 2018, Facebook requires all traffic to go through HTTPS only
SOCIAL_AUTH_REDIRECT_IS_HTTPS = True
# CELERY SETTINGS
-CELERY_BROKER_URL = os.environ.get(
- 'CELERY_BROKER_URL', os.environ.get('CLOUDAMQP_URL')) or ''
+CELERY_BROKER_URL = (
+ os.environ.get("CELERY_BROKER_URL", os.environ.get("CLOUDAMQP_URL")) or ""
+)
CELERY_TASK_ALWAYS_EAGER = not CELERY_BROKER_URL
-CELERY_ACCEPT_CONTENT = ['json']
-CELERY_TASK_SERIALIZER = 'json'
-CELERY_RESULT_SERIALIZER = 'json'
-CELERY_RESULT_BACKEND = 'django-db'
+CELERY_ACCEPT_CONTENT = ["json"]
+CELERY_TASK_SERIALIZER = "json"
+CELERY_RESULT_SERIALIZER = "json"
+CELERY_RESULT_BACKEND = "django-db"
# Impersonate module settings
IMPERSONATE = {
- 'URI_EXCLUSIONS': [r'^dashboard/'],
- 'CUSTOM_USER_QUERYSET': 'saleor.account.impersonate.get_impersonatable_users', # noqa
- 'USE_HTTP_REFERER': True,
- 'CUSTOM_ALLOW': 'saleor.account.impersonate.can_impersonate'}
+ "URI_EXCLUSIONS": [r"^dashboard/"],
+ "CUSTOM_USER_QUERYSET": "saleor.account.impersonate.get_impersonatable_users", # noqa
+ "USE_HTTP_REFERER": True,
+ "CUSTOM_ALLOW": "saleor.account.impersonate.can_impersonate",
+}
# Rich-text editor
ALLOWED_TAGS = [
- 'a',
- 'b',
- 'blockquote',
- 'br',
- 'em',
- 'h2',
- 'h3',
- 'i',
- 'img',
- 'li',
- 'ol',
- 'p',
- 'strong',
- 'ul']
-ALLOWED_ATTRIBUTES = {
- '*': ['align', 'style'],
- 'a': ['href', 'title'],
- 'img': ['src']}
-ALLOWED_STYLES = ['text-align']
+ "a",
+ "b",
+ "blockquote",
+ "br",
+ "em",
+ "h2",
+ "h3",
+ "i",
+ "img",
+ "li",
+ "ol",
+ "p",
+ "strong",
+ "ul",
+]
+ALLOWED_ATTRIBUTES = {"*": ["align", "style"], "a": ["href", "title"], "img": ["src"]}
+ALLOWED_STYLES = ["text-align"]
# Slugs for menus precreated in Django migrations
-DEFAULT_MENUS = {
- 'top_menu_name': 'navbar',
- 'bottom_menu_name': 'footer'}
+DEFAULT_MENUS = {"top_menu_name": "navbar", "bottom_menu_name": "footer"}
# This enable the new 'No Captcha reCaptcha' version (the simple checkbox)
# instead of the old (deprecated) one. For more information see:
@@ -551,75 +552,83 @@ DEFAULT_MENUS = {
NOCAPTCHA = True
# Set Google's reCaptcha keys
-RECAPTCHA_PUBLIC_KEY = os.environ.get('RECAPTCHA_PUBLIC_KEY')
-RECAPTCHA_PRIVATE_KEY = os.environ.get('RECAPTCHA_PRIVATE_KEY')
+RECAPTCHA_PUBLIC_KEY = os.environ.get("RECAPTCHA_PUBLIC_KEY")
+RECAPTCHA_PRIVATE_KEY = os.environ.get("RECAPTCHA_PRIVATE_KEY")
# Sentry
-SENTRY_DSN = os.environ.get('SENTRY_DSN')
+SENTRY_DSN = os.environ.get("SENTRY_DSN")
if SENTRY_DSN:
- INSTALLED_APPS.append('raven.contrib.django.raven_compat')
- RAVEN_CONFIG = {
- 'dsn': SENTRY_DSN,
- 'release': __version__}
+ INSTALLED_APPS.append("raven.contrib.django.raven_compat")
+ RAVEN_CONFIG = {"dsn": SENTRY_DSN, "release": __version__}
-SERIALIZATION_MODULES = {
- 'json': 'saleor.core.utils.json_serializer'}
+SERIALIZATION_MODULES = {"json": "saleor.core.utils.json_serializer"}
-DUMMY = 'dummy'
-BRAINTREE = 'braintree'
-RAZORPAY = 'razorpay'
-STRIPE = 'stripe'
+DUMMY = "dummy"
+BRAINTREE = "braintree"
+RAZORPAY = "razorpay"
+STRIPE = "stripe"
CHECKOUT_PAYMENT_GATEWAYS = {
- DUMMY: pgettext_lazy('Payment method name', 'Dummy gateway'),
- RAZORPAY: RAZORPAY} # FIXME: remove me
+ DUMMY: pgettext_lazy("Payment method name", "Dummy gateway")
+}
PAYMENT_GATEWAYS = {
DUMMY: {
- 'module': 'saleor.payment.gateways.dummy',
- 'connection_params': {}},
+ "module": "saleor.payment.gateways.dummy",
+ "config": {"auto_capture": True, "connection_params": {}},
+ },
BRAINTREE: {
- 'module': 'saleor.payment.gateways.braintree',
- 'connection_params': {
- 'sandbox_mode': get_bool_from_env('BRAINTREE_SANDBOX_MODE', True),
- 'merchant_id': os.environ.get('BRAINTREE_MERCHANT_ID'),
- 'public_key': os.environ.get('BRAINTREE_PUBLIC_KEY'),
- 'private_key': os.environ.get('BRAINTREE_PRIVATE_KEY')
- }
+ "module": "saleor.payment.gateways.braintree",
+ "config": {
+ "auto_capture": True,
+ "connection_params": {
+ "sandbox_mode": get_bool_from_env("BRAINTREE_SANDBOX_MODE", True),
+ "merchant_id": os.environ.get("BRAINTREE_MERCHANT_ID"),
+ "public_key": os.environ.get("BRAINTREE_PUBLIC_KEY"),
+ "private_key": os.environ.get("BRAINTREE_PRIVATE_KEY"),
+ },
+ },
},
RAZORPAY: {
- 'module': 'saleor.payment.gateways.razorpay',
- 'connection_params': {
- 'public_key': os.environ.get('RAZORPAY_PUBLIC_KEY'),
- 'secret_key': os.environ.get('RAZORPAY_SECRET_KEY'),
- 'prefill': get_bool_from_env('RAZORPAY_PREFILL', True),
- 'store_name': os.environ.get('RAZORPAY_STORE_NAME'),
- 'store_image': os.environ.get('RAZORPAY_STORE_IMAGE')
- }
+ "module": "saleor.payment.gateways.razorpay",
+ "config": {
+ "auto_capture": True,
+ "connection_params": {
+ "public_key": os.environ.get("RAZORPAY_PUBLIC_KEY"),
+ "secret_key": os.environ.get("RAZORPAY_SECRET_KEY"),
+ "prefill": get_bool_from_env("RAZORPAY_PREFILL", True),
+ "store_name": os.environ.get("RAZORPAY_STORE_NAME"),
+ "store_image": os.environ.get("RAZORPAY_STORE_IMAGE"),
+ },
+ },
},
STRIPE: {
- 'module': 'saleor.payment.gateways.stripe',
- 'connection_params': {
- 'public_key': os.environ.get('STRIPE_PUBLIC_KEY'),
- 'secret_key': os.environ.get('STRIPE_SECRET_KEY'),
- 'store_name': os.environ.get(
- 'STRIPE_STORE_NAME', 'Saleor'),
- 'store_image': os.environ.get('STRIPE_STORE_IMAGE', None),
- 'prefill': get_bool_from_env('STRIPE_PREFILL', True),
- 'remember_me': os.environ.get('STRIPE_REMEMBER_ME', True),
- 'locale': os.environ.get('STRIPE_LOCALE', 'auto'),
- 'enable_billing_address': os.environ.get(
- 'STRIPE_ENABLE_BILLING_ADDRESS', False),
- 'enable_shipping_address': os.environ.get(
- 'STRIPE_ENABLE_SHIPPING_ADDRESS', False)
- }
- }
+ "module": "saleor.payment.gateways.stripe",
+ "config": {
+ "auto_capture": True,
+ "connection_params": {
+ "public_key": os.environ.get("STRIPE_PUBLIC_KEY"),
+ "secret_key": os.environ.get("STRIPE_SECRET_KEY"),
+ "store_name": os.environ.get("STRIPE_STORE_NAME", "Saleor"),
+ "store_image": os.environ.get("STRIPE_STORE_IMAGE", None),
+ "prefill": get_bool_from_env("STRIPE_PREFILL", True),
+ "remember_me": os.environ.get("STRIPE_REMEMBER_ME", True),
+ "locale": os.environ.get("STRIPE_LOCALE", "auto"),
+ "enable_billing_address": os.environ.get(
+ "STRIPE_ENABLE_BILLING_ADDRESS", False
+ ),
+ "enable_shipping_address": os.environ.get(
+ "STRIPE_ENABLE_SHIPPING_ADDRESS", False
+ ),
+ },
+ },
+ },
}
GRAPHENE = {
- 'RELAY_CONNECTION_ENFORCE_FIRST_OR_LAST': True,
- 'RELAY_CONNECTION_MAX_LIMIT': 100
+ "RELAY_CONNECTION_ENFORCE_FIRST_OR_LAST": True,
+ "RELAY_CONNECTION_MAX_LIMIT": 100,
}
diff --git a/tests/gateway/test_braintree.py b/tests/gateway/test_braintree.py
index e55cc132bb..5a5e3cd980 100644
--- a/tests/gateway/test_braintree.py
+++ b/tests/gateway/test_braintree.py
@@ -9,19 +9,33 @@ from braintree.validation_error import ValidationError
from django.core.exceptions import ImproperlyConfigured
from saleor.payment.gateways.braintree import (
- CONFIRM_MANUALLY, THREE_D_SECURE_REQUIRED, TransactionKind, authorize,
- capture, create_form, extract_gateway_response, get_braintree_gateway,
- get_client_token, get_customer_data, get_error_for_client, process_payment,
- refund, void)
+ CONFIRM_MANUALLY,
+ THREE_D_SECURE_REQUIRED,
+ TransactionKind,
+ authorize,
+ capture,
+ create_form,
+ extract_gateway_response,
+ get_braintree_gateway,
+ get_client_token,
+ get_customer_data,
+ get_error_for_client,
+ process_payment,
+ refund,
+ void,
+)
from saleor.payment.gateways.braintree.errors import (
- DEFAULT_ERROR_MESSAGE, BraintreeException)
+ DEFAULT_ERROR_MESSAGE,
+ BraintreeException,
+)
from saleor.payment.gateways.braintree.forms import BraintreePaymentForm
+from saleor.payment.interface import ConfigData
from saleor.payment.utils import create_payment_information
INCORRECT_TOKEN_ERROR = (
- 'Unable to process the transaction. Transaction\'s token is incorrect '
- 'or expired.')
-DEFAULT_ERROR = 'Unable to process transaction. Please try again in a moment'
+ "Unable to process the transaction. Transaction's token is incorrect " "or expired."
+)
+DEFAULT_ERROR = "Unable to process transaction. Please try again in a moment"
@pytest.fixture
@@ -30,29 +44,32 @@ def braintree_success_response():
spec=SuccessfulResult,
is_success=True,
transaction=Mock(
- id='1x02131',
+ id="1x02131",
spec=Transaction,
- amount=Decimal('0.20'),
- created_at='2018-10-20 18:34:22',
- credit_card='', # FIXME we should provide a proper CreditCard mock
- additional_processor_response='',
- gateway_rejection_reason='',
- processor_response_code='1000',
- processor_response_text='Approved',
- processor_settlement_response_code='',
- processor_settlement_response_text='',
- risk_data='',
- currency_iso_code='EUR',
- status='authorized'))
+ amount=Decimal("0.20"),
+ created_at="2018-10-20 18:34:22",
+ credit_card="", # FIXME we should provide a proper CreditCard mock
+ additional_processor_response="",
+ gateway_rejection_reason="",
+ processor_response_code="1000",
+ processor_response_text="Approved",
+ processor_settlement_response_code="",
+ processor_settlement_response_text="",
+ risk_data="",
+ currency_iso_code="EUR",
+ status="authorized",
+ ),
+ )
@pytest.fixture
def braintree_error():
return Mock(
spec=ValidationError,
- code='91507',
- attribute='base',
- message='Cannot submit for settlement unless status is authorized.')
+ code="91507",
+ attribute="base",
+ message="Cannot submit for settlement unless status is authorized.",
+ )
@pytest.fixture
@@ -61,9 +78,8 @@ def braintree_error_response(braintree_error):
spec=ErrorResult,
is_success=False,
transaction=None,
- errors=Mock(
- spec=Errors,
- deep_errors=[braintree_error]))
+ errors=Mock(spec=Errors, deep_errors=[braintree_error]),
+ )
@pytest.fixture
@@ -73,17 +89,21 @@ def braintree_not_found_error():
@pytest.fixture
def gateway_config():
- return {
- 'sandbox_mode': False,
- 'merchant_id': '123',
- 'public_key': '456',
- 'private_key': '789'}
+ return ConfigData(
+ auto_capture=False,
+ connection_params={
+ "sandbox_mode": False,
+ "merchant_id": "123",
+ "public_key": "456",
+ "private_key": "789",
+ },
+ )
def success_gateway_response(gateway_response):
data = extract_gateway_response(gateway_response)
- data.pop('currency')
- data.pop('amount')
+ data.pop("currency")
+ data.pop("amount")
return data
@@ -92,108 +112,111 @@ def test_get_customer_data(payment_dummy):
payment_info = create_payment_information(payment)
result = get_customer_data(payment_info)
expected_result = {
- 'order_id': payment.order_id,
- 'billing': {
- 'first_name': payment.billing_first_name,
- 'last_name': payment.billing_last_name,
- 'company': payment.billing_company_name,
- 'postal_code': payment.billing_postal_code,
- 'street_address': payment.billing_address_1[:255],
- 'extended_address': payment.billing_address_2[:255],
- 'locality': payment.billing_city,
- 'region': payment.billing_country_area,
- 'country_code_alpha2': payment.billing_country_code},
- 'risk_data': {
- 'customer_ip': payment.customer_ip_address or ''},
- 'customer': {
- 'email': payment.billing_email}}
+ "order_id": payment.order_id,
+ "billing": {
+ "first_name": payment.billing_first_name,
+ "last_name": payment.billing_last_name,
+ "company": payment.billing_company_name,
+ "postal_code": payment.billing_postal_code,
+ "street_address": payment.billing_address_1[:255],
+ "extended_address": payment.billing_address_2[:255],
+ "locality": payment.billing_city,
+ "region": payment.billing_country_area,
+ "country_code_alpha2": payment.billing_country_code,
+ },
+ "risk_data": {"customer_ip": payment.customer_ip_address or ""},
+ "customer": {"email": payment.billing_email},
+ }
assert result == expected_result
def test_get_error_for_client(braintree_error, monkeypatch):
# no error
- assert get_error_for_client([]) == ''
+ assert get_error_for_client([]) == ""
- error = {'code': braintree_error.code, 'message': braintree_error.message}
+ error = {"code": braintree_error.code, "message": braintree_error.message}
# error not whitelisted
- monkeypatch.setattr(
- 'saleor.payment.gateways.braintree.ERROR_CODES_WHITELIST', {})
+ monkeypatch.setattr("saleor.payment.gateways.braintree.ERROR_CODES_WHITELIST", {})
assert get_error_for_client([error]) == DEFAULT_ERROR
monkeypatch.setattr(
- 'saleor.payment.gateways.braintree.ERROR_CODES_WHITELIST',
- {braintree_error.code: ''})
+ "saleor.payment.gateways.braintree.ERROR_CODES_WHITELIST",
+ {braintree_error.code: ""},
+ )
assert get_error_for_client([error]) == braintree_error.message
monkeypatch.setattr(
- 'saleor.payment.gateways.braintree.ERROR_CODES_WHITELIST',
- {braintree_error.code: 'Error msg override'})
- assert get_error_for_client([error]) == 'Error msg override'
+ "saleor.payment.gateways.braintree.ERROR_CODES_WHITELIST",
+ {braintree_error.code: "Error msg override"},
+ )
+ assert get_error_for_client([error]) == "Error msg override"
def test_extract_gateway_response(braintree_success_response):
result = extract_gateway_response(braintree_success_response)
t = braintree_success_response.transaction
expected_result = {
- 'currency': t.currency_iso_code,
- 'amount': t.amount,
- 'credit_card': t.credit_card,
- 'errors': [],
- 'transaction_id': t.id}
+ "currency": t.currency_iso_code,
+ "amount": t.amount,
+ "credit_card": t.credit_card,
+ "errors": [],
+ "transaction_id": t.id,
+ }
assert result == expected_result
def test_extract_gateway_response_no_transaction(
- braintree_error_response, braintree_error):
+ braintree_error_response, braintree_error
+):
result = extract_gateway_response(braintree_error_response)
assert result == {
- 'errors': [
- {
- 'code': braintree_error.code,
- 'message': braintree_error.message}]}
+ "errors": [{"code": braintree_error.code, "message": braintree_error.message}]
+ }
@pytest.mark.integration
def test_get_braintree_gateway(gateway_config):
- result = get_braintree_gateway(**gateway_config)
- assert gateway_config['sandbox_mode'] == False
+ connection_params = gateway_config.connection_params
+ result = get_braintree_gateway(**gateway_config.connection_params)
+ assert connection_params["sandbox_mode"] == False
assert result.config.environment == Environment.Production
- assert result.config.merchant_id == gateway_config['merchant_id']
- assert result.config.public_key == gateway_config['public_key']
- assert result.config.private_key == gateway_config['private_key']
+ assert result.config.merchant_id == connection_params["merchant_id"]
+ assert result.config.public_key == connection_params["public_key"]
+ assert result.config.private_key == connection_params["private_key"]
@pytest.mark.integration
def test_get_braintree_gateway_sandbox(gateway_config):
- gateway_config['sandbox_mode'] = True
- result = get_braintree_gateway(**gateway_config)
+ gateway_config.connection_params["sandbox_mode"] = True
+ result = get_braintree_gateway(**gateway_config.connection_params)
assert result.config.environment == Environment.Sandbox
def test_get_braintree_gateway_inproperly_configured(gateway_config):
with pytest.raises(ImproperlyConfigured):
- gateway_config['private_key'] = None
- get_braintree_gateway(**gateway_config)
+ gateway_config.connection_params["private_key"] = None
+ get_braintree_gateway(**gateway_config.connection_params)
-@patch('saleor.payment.gateways.braintree.get_braintree_gateway')
+@patch("saleor.payment.gateways.braintree.get_braintree_gateway")
def test_get_client_token(mock_gateway, gateway_config):
- client_token = 'client-token'
- mock_generate = Mock(return_value='client-token')
+ client_token = "client-token"
+ mock_generate = Mock(return_value="client-token")
mock_gateway.return_value = Mock(client_token=Mock(generate=mock_generate))
- result = get_client_token(gateway_config)
- mock_gateway.assert_called_once_with(**gateway_config)
+ result = get_client_token(gateway_config.connection_params)
+ mock_gateway.assert_called_once_with(**gateway_config.connection_params)
mock_generate.assert_called_once_with()
assert result == client_token
@pytest.mark.integration
-@patch('saleor.payment.gateways.braintree.get_braintree_gateway')
+@patch("saleor.payment.gateways.braintree.get_braintree_gateway")
def test_process_payment_error_response(
- mock_gateway, payment_dummy, braintree_error_response, gateway_config):
+ mock_gateway, payment_dummy, braintree_error_response, gateway_config
+):
payment = payment_dummy
- payment_token = 'payment-token'
+ payment_token = "payment-token"
mock_response = Mock(return_value=braintree_error_response)
mock_gateway.return_value = Mock(transaction=Mock(sale=mock_response))
@@ -201,15 +224,17 @@ def test_process_payment_error_response(
response = process_payment(payment_info, gateway_config)
assert response.kind == TransactionKind.AUTH
+ assert response.is_success is False
@pytest.mark.integration
-@patch('saleor.payment.gateways.braintree.get_braintree_gateway')
+@patch("saleor.payment.gateways.braintree.get_braintree_gateway")
def test_process_payment(
- mock_gateway, payment_dummy, braintree_success_response,
- gateway_config):
+ mock_gateway, payment_dummy, braintree_success_response, gateway_config
+):
+ gateway_config.auto_capture = True
payment = payment_dummy
- payment_token = 'payment-token'
+ payment_token = "payment-token"
mock_response = Mock(return_value=braintree_success_response)
mock_gateway.return_value = Mock(transaction=Mock(sale=mock_response))
@@ -220,11 +245,12 @@ def test_process_payment(
@pytest.mark.integration
-@patch('saleor.payment.gateways.braintree.get_braintree_gateway')
+@patch("saleor.payment.gateways.braintree.get_braintree_gateway")
def test_authorize_error_response(
- mock_gateway, payment_dummy, braintree_error_response, gateway_config):
+ mock_gateway, payment_dummy, braintree_error_response, gateway_config
+):
payment = payment_dummy
- payment_token = 'payment-token'
+ payment_token = "payment-token"
mock_response = Mock(return_value=braintree_error_response)
mock_gateway.return_value = Mock(transaction=Mock(sale=mock_response))
@@ -237,12 +263,12 @@ def test_authorize_error_response(
@pytest.mark.integration
-@patch('saleor.payment.gateways.braintree.get_braintree_gateway')
+@patch("saleor.payment.gateways.braintree.get_braintree_gateway")
def test_authorize_incorrect_token(
- mock_gateway, payment_dummy, braintree_not_found_error,
- gateway_config):
+ mock_gateway, payment_dummy, braintree_not_found_error, gateway_config
+):
payment = payment_dummy
- payment_token = 'payment-token'
+ payment_token = "payment-token"
mock_response = Mock(side_effect=braintree_not_found_error)
mock_gateway.return_value = Mock(transaction=Mock(sale=mock_response))
@@ -253,15 +279,15 @@ def test_authorize_incorrect_token(
@pytest.mark.integration
-@patch('saleor.payment.gateways.braintree.get_braintree_gateway')
+@patch("saleor.payment.gateways.braintree.get_braintree_gateway")
def test_authorize(
- mock_gateway, payment_dummy, braintree_success_response,
- gateway_config):
+ mock_gateway, payment_dummy, braintree_success_response, gateway_config
+):
payment = payment_dummy
mock_response = Mock(return_value=braintree_success_response)
mock_gateway.return_value = Mock(transaction=Mock(sale=mock_response))
- payment_info = create_payment_information(payment, 'auth-token')
+ payment_info = create_payment_information(payment, "auth-token")
response = authorize(payment_info, gateway_config)
assert not response.error
@@ -271,27 +297,30 @@ def test_authorize(
assert response.transaction_id == braintree_success_response.transaction.id
assert response.is_success == braintree_success_response.is_success
- mock_response.assert_called_once_with({
- 'amount': str(payment.total),
- 'payment_method_nonce': 'auth-token',
- 'options': {
- 'submit_for_settlement': CONFIRM_MANUALLY,
- 'three_d_secure': {
- 'required': THREE_D_SECURE_REQUIRED}},
- **get_customer_data(payment_info)})
+ mock_response.assert_called_once_with(
+ {
+ "amount": str(payment.total),
+ "payment_method_nonce": "auth-token",
+ "options": {
+ "submit_for_settlement": CONFIRM_MANUALLY,
+ "three_d_secure": {"required": THREE_D_SECURE_REQUIRED},
+ },
+ **get_customer_data(payment_info),
+ }
+ )
@pytest.mark.integration
-@patch('saleor.payment.gateways.braintree.get_braintree_gateway')
+@patch("saleor.payment.gateways.braintree.get_braintree_gateway")
def test_refund(
- mock_gateway, payment_txn_captured, braintree_success_response,
- gateway_config):
+ mock_gateway, payment_txn_captured, braintree_success_response, gateway_config
+):
payment = payment_txn_captured
- amount = Decimal('10.00')
+ amount = Decimal("10.00")
mock_response = Mock(return_value=braintree_success_response)
mock_gateway.return_value = Mock(transaction=Mock(refund=mock_response))
- payment_info = create_payment_information(payment, 'token', amount)
+ payment_info = create_payment_information(payment, "token", amount)
response = refund(payment_info, gateway_config)
assert not response.error
@@ -301,57 +330,58 @@ def test_refund(
assert response.transaction_id == braintree_success_response.transaction.id
assert response.is_success == braintree_success_response.is_success
mock_response.assert_called_once_with(
- amount_or_options=str(amount), transaction_id=payment_info.token)
+ amount_or_options=str(amount), transaction_id=payment_info.token
+ )
@pytest.mark.integration
-@patch('saleor.payment.gateways.braintree.get_braintree_gateway')
+@patch("saleor.payment.gateways.braintree.get_braintree_gateway")
def test_refund_incorrect_token(
- mock_gateway, payment_txn_captured, braintree_not_found_error,
- gateway_config):
+ mock_gateway, payment_txn_captured, braintree_not_found_error, gateway_config
+):
payment = payment_txn_captured
- amount = Decimal('10.00')
+ amount = Decimal("10.00")
mock_response = Mock(side_effect=braintree_not_found_error)
mock_gateway.return_value = Mock(transaction=Mock(refund=mock_response))
- payment_info = create_payment_information(payment, 'token', amount)
+ payment_info = create_payment_information(payment, "token", amount)
with pytest.raises(BraintreeException) as e:
refund(payment_info, gateway_config)
assert str(e.value) == DEFAULT_ERROR_MESSAGE
@pytest.mark.integration
-@patch('saleor.payment.gateways.braintree.get_braintree_gateway')
+@patch("saleor.payment.gateways.braintree.get_braintree_gateway")
def test_refund_error_response(
- mock_gateway, payment_txn_captured, braintree_error_response,
- gateway_config):
+ mock_gateway, payment_txn_captured, braintree_error_response, gateway_config
+):
payment = payment_txn_captured
- amount = Decimal('10.00')
+ amount = Decimal("10.00")
mock_response = Mock(return_value=braintree_error_response)
mock_gateway.return_value = Mock(transaction=Mock(refund=mock_response))
- payment_info = create_payment_information(payment, 'token', amount)
+ payment_info = create_payment_information(payment, "token", amount)
response = refund(payment_info, gateway_config)
- assert response.raw_response == extract_gateway_response(
- braintree_error_response)
+ assert response.raw_response == extract_gateway_response(braintree_error_response)
assert not response.is_success
assert response.error == DEFAULT_ERROR
@pytest.mark.integration
-@patch('saleor.payment.gateways.braintree.get_braintree_gateway')
+@patch("saleor.payment.gateways.braintree.get_braintree_gateway")
def test_capture(
- mock_gateway, payment_txn_preauth, braintree_success_response,
- gateway_config):
+ mock_gateway, payment_txn_preauth, braintree_success_response, gateway_config
+):
payment = payment_txn_preauth
- amount = Decimal('10.00')
+ amount = Decimal("10.00")
mock_response = Mock(return_value=braintree_success_response)
mock_gateway.return_value = Mock(
- transaction=Mock(submit_for_settlement=mock_response))
+ transaction=Mock(submit_for_settlement=mock_response)
+ )
- payment_info = create_payment_information(payment, 'token', amount)
+ payment_info = create_payment_information(payment, "token", amount)
response = capture(payment_info, gateway_config)
assert not response.error
@@ -362,18 +392,20 @@ def test_capture(
assert response.is_success == braintree_success_response.is_success
mock_response.assert_called_once_with(
- amount=str(amount), transaction_id=payment_info.token)
+ amount=str(amount), transaction_id=payment_info.token
+ )
@pytest.mark.integration
-@patch('saleor.payment.gateways.braintree.get_braintree_gateway')
+@patch("saleor.payment.gateways.braintree.get_braintree_gateway")
def test_capture_incorrect_token(
- mock_gateway, payment_txn_preauth, braintree_not_found_error,
- gateway_config):
+ mock_gateway, payment_txn_preauth, braintree_not_found_error, gateway_config
+):
payment = payment_txn_preauth
mock_response = Mock(side_effect=braintree_not_found_error)
mock_gateway.return_value = Mock(
- transaction=Mock(submit_for_settlement=mock_response))
+ transaction=Mock(submit_for_settlement=mock_response)
+ )
payment_info = create_payment_information(payment)
with pytest.raises(BraintreeException) as e:
@@ -382,34 +414,34 @@ def test_capture_incorrect_token(
@pytest.mark.integration
-@patch('saleor.payment.gateways.braintree.get_braintree_gateway')
+@patch("saleor.payment.gateways.braintree.get_braintree_gateway")
def test_capture_error_response(
- mock_gateway, payment_txn_preauth, braintree_error_response,
- gateway_config):
+ mock_gateway, payment_txn_preauth, braintree_error_response, gateway_config
+):
payment = payment_txn_preauth
mock_response = Mock(return_value=braintree_error_response)
mock_gateway.return_value = Mock(
- transaction=Mock(submit_for_settlement=mock_response))
+ transaction=Mock(submit_for_settlement=mock_response)
+ )
- payment_info = create_payment_information(payment, 'token')
+ payment_info = create_payment_information(payment, "token")
response = capture(payment_info, gateway_config)
- assert response.raw_response == extract_gateway_response(
- braintree_error_response)
+ assert response.raw_response == extract_gateway_response(braintree_error_response)
assert not response.is_success
assert response.error == DEFAULT_ERROR
@pytest.mark.integration
-@patch('saleor.payment.gateways.braintree.get_braintree_gateway')
+@patch("saleor.payment.gateways.braintree.get_braintree_gateway")
def test_void(
- mock_gateway, payment_txn_preauth, braintree_success_response,
- gateway_config):
+ mock_gateway, payment_txn_preauth, braintree_success_response, gateway_config
+):
payment = payment_txn_preauth
mock_response = Mock(return_value=braintree_success_response)
mock_gateway.return_value = Mock(transaction=Mock(void=mock_response))
- payment_info = create_payment_information(payment, 'token')
+ payment_info = create_payment_information(payment, "token")
response = void(payment_info, gateway_config)
assert not response.error
@@ -422,10 +454,10 @@ def test_void(
@pytest.mark.integration
-@patch('saleor.payment.gateways.braintree.get_braintree_gateway')
+@patch("saleor.payment.gateways.braintree.get_braintree_gateway")
def test_void_incorrect_token(
- mock_gateway, payment_txn_preauth, braintree_not_found_error,
- gateway_config):
+ mock_gateway, payment_txn_preauth, braintree_not_found_error, gateway_config
+):
payment = payment_txn_preauth
mock_response = Mock(side_effect=braintree_not_found_error)
@@ -438,10 +470,10 @@ def test_void_incorrect_token(
@pytest.mark.integration
-@patch('saleor.payment.gateways.braintree.get_braintree_gateway')
+@patch("saleor.payment.gateways.braintree.get_braintree_gateway")
def test_void_error_response(
- mock_gateway, payment_txn_preauth, braintree_error_response,
- gateway_config):
+ mock_gateway, payment_txn_preauth, braintree_error_response, gateway_config
+):
payment = payment_txn_preauth
mock_response = Mock(return_value=braintree_error_response)
mock_gateway.return_value = Mock(transaction=Mock(void=mock_response))
@@ -449,15 +481,14 @@ def test_void_error_response(
payment_info = create_payment_information(payment)
response = void(payment_info, gateway_config)
- assert response.raw_response == extract_gateway_response(
- braintree_error_response)
+ assert response.raw_response == extract_gateway_response(braintree_error_response)
assert not response.is_success
assert response.error == DEFAULT_ERROR
def test_braintree_payment_form_incorrect_amount(payment_dummy):
- amount = Decimal('0.01')
- data = {'amount': amount, 'payment_method_nonce': 'fake-nonce'}
+ amount = Decimal("0.01")
+ data = {"amount": amount, "payment_method_nonce": "fake-nonce"}
assert amount != payment_dummy.total
payment_info = create_payment_information(payment_dummy)
@@ -469,12 +500,12 @@ def test_braintree_payment_form_incorrect_amount(payment_dummy):
def test_braintree_payment_form(payment_dummy):
payment = payment_dummy
- data = {'amount': payment.total, 'payment_method_nonce': 'fake-nonce'}
+ data = {"amount": payment.total, "payment_method_nonce": "fake-nonce"}
payment_info = create_payment_information(payment)
form = create_form(
- data=data, payment_information=payment_info,
- connection_params={'secret': '123'})
+ data=data, payment_information=payment_info, connection_params={"secret": "123"}
+ )
assert isinstance(form, BraintreePaymentForm)
assert form.is_valid()
diff --git a/tests/gateway/test_dummy.py b/tests/gateway/test_dummy.py
index d3bd0a3033..7c0f1bb475 100644
--- a/tests/gateway/test_dummy.py
+++ b/tests/gateway/test_dummy.py
@@ -3,61 +3,23 @@ from decimal import Decimal
import pytest
from saleor.payment import (
- ChargeStatus, PaymentError, TransactionKind, get_payment_gateway)
+ ChargeStatus,
+ PaymentError,
+ TransactionKind,
+ get_payment_gateway,
+)
from saleor.payment.utils import (
- create_payment_information, gateway_authorize, gateway_capture,
- gateway_process_payment, gateway_refund, gateway_void)
-
-
-def test_charge_success(payment_dummy):
- gateway_capture(payment=payment_dummy)
- capture_txn = payment_dummy.transactions.last()
-
- assert capture_txn.is_success
- assert capture_txn.kind == TransactionKind.CAPTURE
- assert capture_txn.payment == payment_dummy
- assert capture_txn.amount == payment_dummy.total
-
- payment_dummy.refresh_from_db()
- assert payment_dummy.charge_status == ChargeStatus.FULLY_CHARGED
- assert payment_dummy.captured_amount == payment_dummy.total
- assert payment_dummy.is_active
-
-
-def test_charge_gateway_error(payment_dummy, monkeypatch):
- monkeypatch.setattr(
- 'saleor.payment.gateways.dummy.dummy_success', lambda: False)
- with pytest.raises(PaymentError):
- txn = gateway_capture(
- payment=payment_dummy, payment_token='Fake',
- amount=payment_dummy.total)
- assert txn.kind == TransactionKind.CAPTURE
- assert not txn.is_success
- assert txn.payment == payment_dummy
-
-
- 'is_active, charge_status', [
- (False, ChargeStatus.NOT_CHARGED),
- (False, ChargeStatus.PARTIALLY_CHARGED),
- (False, ChargeStatus.FULLY_CHARGED),
- (False, ChargeStatus.PARTIALLY_REFUNDED),
- (False, ChargeStatus.FULLY_REFUNDED),
- (True, ChargeStatus.FULLY_CHARGED),
- (True, ChargeStatus.PARTIALLY_REFUNDED),
- (True, ChargeStatus.FULLY_REFUNDED), ])
-def test_charge_failed(is_active, charge_status, payment_dummy):
- payment = payment_dummy
- payment.is_active = is_active
- payment.charge_status = charge_status
- payment.save()
- with pytest.raises(PaymentError):
- txn = gateway_capture(payment=payment)
- assert txn is None
+ create_payment_information,
+ gateway_authorize,
+ gateway_capture,
+ gateway_process_payment,
+ gateway_refund,
+ gateway_void,
+)
def test_authorize_success(payment_dummy):
- txn = gateway_authorize(payment=payment_dummy, payment_token='Fake')
+ txn = gateway_authorize(payment=payment_dummy, payment_token="Fake")
assert txn.is_success
assert txn.kind == TransactionKind.AUTH
assert txn.payment == payment_dummy
@@ -66,7 +28,8 @@ def test_authorize_success(payment_dummy):
@pytest.mark.parametrize(
- 'is_active, charge_status', [
+ "is_active, charge_status",
+ [
(False, ChargeStatus.NOT_CHARGED),
(False, ChargeStatus.PARTIALLY_CHARGED),
(False, ChargeStatus.FULLY_CHARGED),
@@ -75,22 +38,23 @@ def test_authorize_success(payment_dummy):
(True, ChargeStatus.PARTIALLY_CHARGED),
(True, ChargeStatus.FULLY_CHARGED),
(True, ChargeStatus.PARTIALLY_REFUNDED),
- (True, ChargeStatus.FULLY_REFUNDED), ])
+ (True, ChargeStatus.FULLY_REFUNDED),
+ ],
+)
def test_authorize_failed(is_active, charge_status, payment_dummy):
payment = payment_dummy
payment.is_active = is_active
payment.charge_status = charge_status
payment.save()
with pytest.raises(PaymentError):
- txn = gateway_authorize(payment=payment, payment_token='Fake')
+ txn = gateway_authorize(payment=payment, payment_token="Fake")
assert txn is None
def test_authorize_gateway_error(payment_dummy, monkeypatch):
- monkeypatch.setattr(
- 'saleor.payment.gateways.dummy.dummy_success', lambda: False)
+ monkeypatch.setattr("saleor.payment.gateways.dummy.dummy_success", lambda: False)
with pytest.raises(PaymentError):
- txn = gateway_authorize(payment=payment_dummy, payment_token='Fake')
+ txn = gateway_authorize(payment=payment_dummy, payment_token="Fake")
assert txn.kind == TransactionKind.AUTH
assert not txn.is_success
assert txn.payment == payment_dummy
@@ -109,7 +73,8 @@ def test_void_success(payment_txn_preauth):
@pytest.mark.parametrize(
- 'is_active, charge_status', [
+ "is_active, charge_status",
+ [
(False, ChargeStatus.NOT_CHARGED),
(False, ChargeStatus.PARTIALLY_CHARGED),
(False, ChargeStatus.FULLY_CHARGED),
@@ -118,7 +83,9 @@ def test_void_success(payment_txn_preauth):
(True, ChargeStatus.PARTIALLY_CHARGED),
(True, ChargeStatus.FULLY_CHARGED),
(True, ChargeStatus.PARTIALLY_REFUNDED),
- (True, ChargeStatus.FULLY_REFUNDED), ])
+ (True, ChargeStatus.FULLY_REFUNDED),
+ ],
+)
def test_void_failed(is_active, charge_status, payment_dummy):
payment = payment_dummy
payment.is_active = is_active
@@ -130,8 +97,7 @@ def test_void_failed(is_active, charge_status, payment_dummy):
def test_void_gateway_error(payment_txn_preauth, monkeypatch):
- monkeypatch.setattr(
- 'saleor.payment.gateways.dummy.dummy_success', lambda: False)
+ monkeypatch.setattr("saleor.payment.gateways.dummy.dummy_success", lambda: False)
with pytest.raises(PaymentError):
txn = gateway_void(payment=payment_txn_preauth)
assert txn.kind == TransactionKind.VOID
@@ -140,9 +106,9 @@ def test_void_gateway_error(payment_txn_preauth, monkeypatch):
@pytest.mark.parametrize(
- 'amount, charge_status', [
- (80, ChargeStatus.FULLY_CHARGED),
- (70, ChargeStatus.PARTIALLY_CHARGED), ])
+ "amount, charge_status",
+ [(80, ChargeStatus.FULLY_CHARGED), (70, ChargeStatus.PARTIALLY_CHARGED)],
+)
def test_capture_success(amount, charge_status, payment_txn_preauth):
txn = gateway_capture(payment=payment_txn_preauth, amount=Decimal(amount))
assert txn.is_success
@@ -153,15 +119,18 @@ def test_capture_success(amount, charge_status, payment_txn_preauth):
@pytest.mark.parametrize(
- 'amount, captured_amount, charge_status, is_active', [
+ "amount, captured_amount, charge_status, is_active",
+ [
(80, 0, ChargeStatus.NOT_CHARGED, False),
(120, 0, ChargeStatus.NOT_CHARGED, True),
(80, 20, ChargeStatus.PARTIALLY_CHARGED, True),
(80, 80, ChargeStatus.FULLY_CHARGED, True),
- (80, 0, ChargeStatus.FULLY_REFUNDED, True), ])
+ (80, 0, ChargeStatus.FULLY_REFUNDED, True),
+ ],
+)
def test_capture_failed(
- amount, captured_amount, charge_status, is_active,
- payment_dummy):
+ amount, captured_amount, charge_status, is_active, payment_dummy
+):
payment = payment_dummy
payment.is_active = is_active
payment.captured_amount = captured_amount
@@ -173,8 +142,7 @@ def test_capture_failed(
def test_capture_gateway_error(payment_txn_preauth, monkeypatch):
- monkeypatch.setattr(
- 'saleor.payment.gateways.dummy.dummy_success', lambda: False)
+ monkeypatch.setattr("saleor.payment.gateways.dummy.dummy_success", lambda: False)
with pytest.raises(PaymentError):
txn = gateway_capture(payment=payment_txn_preauth, amount=80)
assert txn.kind == TransactionKind.CAPTURE
@@ -183,13 +151,20 @@ def test_capture_gateway_error(payment_txn_preauth, monkeypatch):
@pytest.mark.parametrize(
- 'initial_captured_amount, refund_amount, final_captured_amount, final_charge_status, active_after',
+ "initial_captured_amount, refund_amount, final_captured_amount, final_charge_status, active_after",
[
(80, 80, 0, ChargeStatus.FULLY_REFUNDED, False),
- (80, 10, 70, ChargeStatus.PARTIALLY_REFUNDED, True), ])
+ (80, 10, 70, ChargeStatus.PARTIALLY_REFUNDED, True),
+ ],
+)
def test_refund_success(
- initial_captured_amount, refund_amount, final_captured_amount,
- final_charge_status, active_after, payment_txn_captured):
+ initial_captured_amount,
+ refund_amount,
+ final_captured_amount,
+ final_charge_status,
+ active_after,
+ payment_txn_captured,
+):
payment = payment_txn_captured
payment.charge_status = ChargeStatus.FULLY_CHARGED
payment.captured_amount = initial_captured_amount
@@ -204,15 +179,18 @@ def test_refund_success(
@pytest.mark.parametrize(
- 'initial_captured_amount, refund_amount, initial_charge_status', [
+ "initial_captured_amount, refund_amount, initial_charge_status",
+ [
(0, 10, ChargeStatus.NOT_CHARGED),
(10, 20, ChargeStatus.PARTIALLY_CHARGED),
(10, 20, ChargeStatus.FULLY_CHARGED),
(10, 20, ChargeStatus.PARTIALLY_REFUNDED),
- (80, 0, ChargeStatus.FULLY_REFUNDED), ])
+ (80, 0, ChargeStatus.FULLY_REFUNDED),
+ ],
+)
def test_refund_failed(
- initial_captured_amount, refund_amount, initial_charge_status,
- payment_dummy):
+ initial_captured_amount, refund_amount, initial_charge_status, payment_dummy
+):
payment = payment_dummy
payment.charge_status = initial_charge_status
payment.captured_amount = Decimal(initial_captured_amount)
@@ -223,14 +201,13 @@ def test_refund_failed(
def test_refund_gateway_error(payment_txn_captured, monkeypatch):
- monkeypatch.setattr(
- 'saleor.payment.gateways.dummy.dummy_success', lambda: False)
+ monkeypatch.setattr("saleor.payment.gateways.dummy.dummy_success", lambda: False)
payment = payment_txn_captured
payment.charge_status = ChargeStatus.FULLY_CHARGED
- payment.captured_amount = Decimal('80.00')
+ payment.captured_amount = Decimal("80.00")
payment.save()
with pytest.raises(PaymentError):
- gateway_refund(payment=payment, amount=Decimal('80.00'))
+ gateway_refund(payment=payment, amount=Decimal("80.00"))
payment.refresh_from_db()
txn = payment.transactions.last()
@@ -238,26 +215,29 @@ def test_refund_gateway_error(payment_txn_captured, monkeypatch):
assert not txn.is_success
assert txn.payment == payment
assert payment.charge_status == ChargeStatus.FULLY_CHARGED
- assert payment.captured_amount == Decimal('80.00')
+ assert payment.captured_amount == Decimal("80.00")
@pytest.mark.parametrize(
- 'kind, charge_status',
+ "kind, charge_status",
(
(TransactionKind.AUTH, ChargeStatus.NOT_CHARGED),
(TransactionKind.CAPTURE, ChargeStatus.FULLY_CHARGED),
- (TransactionKind.REFUND, ChargeStatus.FULLY_REFUNDED), ))
+ (TransactionKind.REFUND, ChargeStatus.FULLY_REFUNDED),
+ ),
+)
def test_dummy_payment_form(kind, charge_status, payment_dummy):
payment = payment_dummy
- data = {'charge_status': charge_status}
- payment_gateway, gateway_params = get_payment_gateway(payment.gateway)
+ data = {"charge_status": charge_status}
+ payment_gateway, gateway_config = get_payment_gateway(payment.gateway)
payment_info = create_payment_information(payment)
form = payment_gateway.create_form(
- data=data, payment_information=payment_info,
- connection_params=gateway_params)
+ data=data,
+ payment_information=payment_info,
+ connection_params=gateway_config.connection_params,
+ )
assert form.is_valid()
- gateway_process_payment(
- payment=payment, payment_token=form.get_payment_token())
+ gateway_process_payment(payment=payment, payment_token=form.get_payment_token())
payment.refresh_from_db()
assert payment.transactions.last().kind == kind
diff --git a/tests/gateway/test_razorpay.py b/tests/gateway/test_razorpay.py
index a09660574a..8e3b760644 100644
--- a/tests/gateway/test_razorpay.py
+++ b/tests/gateway/test_razorpay.py
@@ -6,37 +6,53 @@ from razorpay.errors import BadRequestError, ServerError
from saleor.payment import ChargeStatus, TransactionKind
from saleor.payment.gateways.razorpay import (
- capture, check_payment_supported, clean_razorpay_response,
- create_form, errors, get_amount_for_razorpay, get_client, get_client_token,
- logger, refund)
+ capture,
+ check_payment_supported,
+ clean_razorpay_response,
+ create_form,
+ errors,
+ get_amount_for_razorpay,
+ get_client,
+ get_client_token,
+ logger,
+ refund,
+)
from saleor.payment.gateways.razorpay.forms import (
- RazorPayCheckoutWidget, RazorPaymentForm)
+ RazorPayCheckoutWidget,
+ RazorPaymentForm,
+)
+from saleor.payment.interface import ConfigData
from saleor.payment.utils import create_payment_information
-TRANSACTION_AMOUNT = Decimal('61.33')
+TRANSACTION_AMOUNT = Decimal("61.33")
-def gateway_params():
- return {
- 'public_key': 'public',
- 'secret_key': 'secret',
- 'prefill': True,
- 'store_name': 'Saleor',
- 'store_image': 'image.png'}
+def gateway_config():
+ return ConfigData(
+ auto_capture=False,
+ connection_params={
+ "public_key": "public",
+ "secret_key": "secret",
+ "prefill": True,
+ "store_name": "Saleor",
+ "store_image": "image.png",
+ },
+ )
@pytest.fixture()
def razorpay_success_response():
return {
- 'id': 'transaction123',
- 'amount': get_amount_for_razorpay(TRANSACTION_AMOUNT),
- 'currency': 'INR'}
+ "id": "transaction123",
+ "amount": get_amount_for_razorpay(TRANSACTION_AMOUNT),
+ "currency": "INR",
+ }
@pytest.fixture()
def razorpay_payment(payment_dummy):
- payment_dummy.currency = 'INR'
+ payment_dummy.currency = "INR"
return payment_dummy
@@ -44,49 +60,56 @@ def razorpay_payment(payment_dummy):
def charged_payment(razorpay_payment):
razorpay_payment.captured_amount = razorpay_payment.total
razorpay_payment.charge_status = ChargeStatus.FULLY_CHARGED
- razorpay_payment.save(update_fields=['captured_amount', 'charge_status'])
+ razorpay_payment.save(update_fields=["captured_amount", "charge_status"])
razorpay_payment.transactions.create(
amount=razorpay_payment.total,
kind=TransactionKind.CAPTURE,
gateway_response={},
- is_success=True)
+ is_success=True,
+ )
return razorpay_payment
-def test_checkout_widget_render_without_prefill(razorpay_payment, gateway_params):
- gateway_params['prefill'] = False
+def test_checkout_widget_render_without_prefill(razorpay_payment, gateway_config):
+ gateway_config.connection_params["prefill"] = False
payment_info = create_payment_information(razorpay_payment)
widget = RazorPayCheckoutWidget(
- payment_information=payment_info, attrs={'data-custom': '123'},
- **gateway_params)
+ payment_information=payment_info,
+ attrs={"data-custom": "123"},
+ **gateway_config.connection_params
+ )
assert widget.render() == (
'<script data-amount="8000" data-buttontext="Pay now with Razorpay" '
'data-currency="INR" data-custom="123" '
'data-description="Total payment" '
'data-image="image.png" data-key="public" data-name="Saleor" '
- 'src="https://checkout.razorpay.com/v1/checkout.js"></script>')
+ 'src="https://checkout.razorpay.com/v1/checkout.js"></script>'
+ )
-def test_checkout_widget_render_with_prefill(razorpay_payment, gateway_params):
+def test_checkout_widget_render_with_prefill(razorpay_payment, gateway_config):
payment_info = create_payment_information(razorpay_payment)
widget = RazorPayCheckoutWidget(
- payment_information=payment_info, **gateway_params)
+ payment_information=payment_info, **gateway_config.connection_params
+ )
assert widget.render() == (
'<script data-amount="8000" data-buttontext="Pay now with Razorpay" '
'data-currency="INR" data-description="Total payment" '
'data-image="image.png" data-key="public" data-name="Saleor" '
'data-prefill.email="[email protected]" '
'data-prefill.name="Doe John" '
- 'src="https://checkout.razorpay.com/v1/checkout.js"></script>')
+ 'src="https://checkout.razorpay.com/v1/checkout.js"></script>'
+ )
-def test_checkout_form(razorpay_payment, gateway_params):
+def test_checkout_form(razorpay_payment, gateway_config):
payment_info = create_payment_information(razorpay_payment)
form = create_form(
- data={'razorpay_payment_id': '123'},
+ data={"razorpay_payment_id": "123"},
payment_information=payment_info,
- connection_params=gateway_params)
+ connection_params=gateway_config.connection_params,
+ )
assert isinstance(form, RazorPaymentForm)
assert form.is_valid()
@@ -99,26 +122,26 @@ def test_check_payment_supported(razorpay_payment):
def test_check_payment_supported_non_supported(razorpay_payment):
- razorpay_payment.currency = 'USD'
+ razorpay_payment.currency = "USD"
payment_info = create_payment_information(razorpay_payment)
found_error = check_payment_supported(payment_info)
assert found_error
def test_get_amount_for_razorpay():
- assert get_amount_for_razorpay(Decimal('61.33')) == 6133
+ assert get_amount_for_razorpay(Decimal("61.33")) == 6133
def test_clean_razorpay_response():
- response = {'amount': 6133}
+ response = {"amount": 6133}
clean_razorpay_response(response)
- assert response['amount'] == Decimal('61.33')
+ assert response["amount"] == Decimal("61.33")
-@patch('razorpay.Client')
-def test_get_client(mocked_gateway, gateway_params):
- get_client(**gateway_params)
- mocked_gateway.assert_called_once_with(auth=('public', 'secret'))
+@patch("razorpay.Client")
+def test_get_client(mocked_gateway, gateway_config):
+ get_client(**gateway_config.connection_params)
+ mocked_gateway.assert_called_once_with(auth=("public", "secret"))
def test_get_client_token():
@@ -126,26 +149,23 @@ def test_get_client_token():
@pytest.mark.integration
-@patch('razorpay.Client')
+@patch("razorpay.Client")
def test_charge(
- mocked_gateway,
- razorpay_payment,
- razorpay_success_response,
- gateway_params):
+ mocked_gateway, razorpay_payment, razorpay_success_response, gateway_config
+):
# Data to be passed
- payment_token = '123'
+ payment_token = "123"
# Mock the gateway response to a success response
- mocked_gateway.return_value.payment.capture.return_value = (
- razorpay_success_response)
+ mocked_gateway.return_value.payment.capture.return_value = razorpay_success_response
payment_info = create_payment_information(
- razorpay_payment, payment_token=payment_token,
- amount=TRANSACTION_AMOUNT)
+ razorpay_payment, payment_token=payment_token, amount=TRANSACTION_AMOUNT
+ )
# Attempt charging
- response = capture(payment_info, gateway_params)
+ response = capture(payment_info, gateway_config)
# Ensure the was no error returned
assert not response.error
@@ -153,29 +173,28 @@ def test_charge(
assert response.kind == TransactionKind.CAPTURE
assert response.amount == TRANSACTION_AMOUNT
- assert response.currency == razorpay_success_response['currency']
+ assert response.currency == razorpay_success_response["currency"]
assert response.raw_response == razorpay_success_response
- assert response.transaction_id == razorpay_success_response['id']
+ assert response.transaction_id == razorpay_success_response["id"]
@pytest.mark.integration
-def test_charge_unsupported_currency(razorpay_payment, gateway_params):
+def test_charge_unsupported_currency(razorpay_payment, gateway_config):
# Set the payment currency to an unsupported currency
- razorpay_payment.currency = 'USD'
+ razorpay_payment.currency = "USD"
# Data to be passed
- payment_token = '123'
+ payment_token = "123"
payment_info = create_payment_information(
- razorpay_payment, payment_token=payment_token,
- amount=TRANSACTION_AMOUNT)
+ razorpay_payment, payment_token=payment_token, amount=TRANSACTION_AMOUNT
+ )
# Attempt charging
- response = capture(payment_info, gateway_params)
+ response = capture(payment_info, gateway_config)
# Ensure a error was returned
- assert response.error == (
- errors.UNSUPPORTED_CURRENCY % {'currency': 'USD'})
+ assert response.error == (errors.UNSUPPORTED_CURRENCY % {"currency": "USD"})
assert not response.is_success
# Ensure the response is correctly set
@@ -183,27 +202,25 @@ def test_charge_unsupported_currency(razorpay_payment, gateway_params):
assert response.transaction_id == payment_token
[email protected](logger, 'exception')
-@patch('razorpay.Client')
[email protected](logger, "exception")
+@patch("razorpay.Client")
def test_charge_invalid_request(
- mocked_gateway,
- mocked_logger,
- razorpay_payment,
- gateway_params):
+ mocked_gateway, mocked_logger, razorpay_payment, gateway_config
+):
# Data to be passed
- payment_token = '123'
+ payment_token = "123"
# Assign the side effect to the gateway's `capture()` method,
# that should trigger the expected error.
mocked_gateway.return_value.payment.capture.side_effect = BadRequestError()
payment_info = create_payment_information(
- razorpay_payment, payment_token=payment_token,
- amount=TRANSACTION_AMOUNT)
+ razorpay_payment, payment_token=payment_token, amount=TRANSACTION_AMOUNT
+ )
# Attempt charging
- response = capture(payment_info, gateway_params)
+ response = capture(payment_info, gateway_config)
# Ensure an error was returned
assert response.error == errors.INVALID_REQUEST
@@ -218,22 +235,20 @@ def test_charge_invalid_request(
@pytest.mark.integration
-@patch('razorpay.Client')
+@patch("razorpay.Client")
def test_refund(
- mocked_gateway,
- charged_payment,
- razorpay_success_response,
- gateway_params):
+ mocked_gateway, charged_payment, razorpay_success_response, gateway_config
+):
# Mock the gateway response to a success response
- mocked_gateway.return_value.payment.refund.return_value = (
- razorpay_success_response)
+ mocked_gateway.return_value.payment.refund.return_value = razorpay_success_response
payment_info = create_payment_information(
- charged_payment, amount=TRANSACTION_AMOUNT)
+ charged_payment, amount=TRANSACTION_AMOUNT
+ )
# Attempt charging
- response = refund(payment_info, gateway_params)
+ response = refund(payment_info, gateway_config)
# Ensure the was no error returned
assert not response.error
@@ -241,26 +256,25 @@ def test_refund(
assert response.kind == TransactionKind.REFUND
assert response.amount == TRANSACTION_AMOUNT
- assert response.currency == razorpay_success_response['currency']
+ assert response.currency == razorpay_success_response["currency"]
assert response.raw_response == razorpay_success_response
- assert response.transaction_id == razorpay_success_response['id']
+ assert response.transaction_id == razorpay_success_response["id"]
@pytest.mark.integration
-def test_refund_unsupported_currency(
- razorpay_payment, charged_payment, gateway_params):
+def test_refund_unsupported_currency(razorpay_payment, charged_payment, gateway_config):
# Set the payment currency to an unsupported currency
- razorpay_payment.currency = 'USD'
+ razorpay_payment.currency = "USD"
payment_info = create_payment_information(
- razorpay_payment, amount=TRANSACTION_AMOUNT)
+ razorpay_payment, amount=TRANSACTION_AMOUNT
+ )
# Attempt charging
- response = refund(payment_info, gateway_params)
+ response = refund(payment_info, gateway_config)
# Ensure a error was returned
- assert response.error == (
- errors.UNSUPPORTED_CURRENCY % {'currency': 'USD'})
+ assert response.error == (errors.UNSUPPORTED_CURRENCY % {"currency": "USD"})
assert not response.is_success
# Ensure the kind is correctly set
@@ -268,14 +282,15 @@ def test_refund_unsupported_currency(
@pytest.mark.integration
[email protected](logger, 'exception')
-@patch('razorpay.Client')
[email protected](logger, "exception")
+@patch("razorpay.Client")
def test_refund_invalid_data(
- mocked_gateway,
- mocked_logger,
- charged_payment,
- razorpay_success_response,
- gateway_params):
+ mocked_gateway,
+ mocked_logger,
+ charged_payment,
+ razorpay_success_response,
+ gateway_config,
+):
# Assign the side effect to the gateway's `refund()` method,
# that should trigger the expected error.
@@ -283,8 +298,9 @@ def test_refund_invalid_data(
# Attempt charging
payment_info = create_payment_information(
- charged_payment, amount=TRANSACTION_AMOUNT)
- response = refund(payment_info, gateway_params)
+ charged_payment, amount=TRANSACTION_AMOUNT
+ )
+ response = refund(payment_info, gateway_config)
# Ensure a error was returned
assert response.error == errors.SERVER_ERROR
diff --git a/tests/gateway/test_stripe.py b/tests/gateway/test_stripe.py
index a3a69ac03f..ceafffae03 100644
--- a/tests/gateway/test_stripe.py
+++ b/tests/gateway/test_stripe.py
@@ -8,40 +8,61 @@ from django_countries import countries
from saleor.payment import ChargeStatus
from saleor.payment.gateways.stripe import (
- TransactionKind, _create_response, _get_client,
- _get_error_response_from_exc, _get_stripe_charge_payload, authorize,
- capture, charge, create_form, get_amount_for_stripe,
- get_amount_from_stripe, get_client_token, get_currency_for_stripe,
- get_currency_from_stripe, refund, void)
+ TransactionKind,
+ _create_response,
+ _get_client,
+ _get_error_response_from_exc,
+ _get_stripe_charge_payload,
+ authorize,
+ capture,
+ create_form,
+ get_amount_for_stripe,
+ get_amount_from_stripe,
+ get_client_token,
+ get_currency_for_stripe,
+ get_currency_from_stripe,
+ refund,
+ void,
+)
from saleor.payment.gateways.stripe.errors import (
- ORDER_NOT_AUTHORIZED, ORDER_NOT_CHARGED)
+ ORDER_NOT_AUTHORIZED,
+ ORDER_NOT_CHARGED,
+)
from saleor.payment.gateways.stripe.forms import (
- StripeCheckoutWidget, StripePaymentModalForm)
+ StripeCheckoutWidget,
+ StripePaymentModalForm,
+)
from saleor.payment.gateways.stripe.utils import (
- get_payment_billing_fullname, shipping_to_stripe_dict)
-from saleor.payment.interface import AddressData
+ get_payment_billing_fullname,
+ shipping_to_stripe_dict,
+)
+from saleor.payment.interface import AddressData, ConfigData
from saleor.payment.utils import create_payment_information
TRANSACTION_AMOUNT = Decimal(42.42)
TRANSACTION_REFUND_AMOUNT = Decimal(24.24)
-TRANSACTION_CURRENCY = 'USD'
-TRANSACTION_TOKEN = 'fake-stripe-id'
-FAKE_TOKEN = 'fake-token'
-ERROR_MESSAGE = 'error-message'
+TRANSACTION_CURRENCY = "USD"
+TRANSACTION_TOKEN = "fake-stripe-id"
+FAKE_TOKEN = "fake-token"
+ERROR_MESSAGE = "error-message"
@pytest.fixture()
-def gateway_params():
- return {
- 'public_key': 'public',
- 'secret_key': 'secret',
- 'store_name': 'Saleor',
- 'store_image': 'image.gif',
- 'prefill': True,
- 'remember_me': True,
- 'locale': 'auto',
- 'enable_billing_address': False,
- 'enable_shipping_address': False}
+def gateway_config():
+ return ConfigData(
+ auto_capture=False,
+ connection_params={
+ "public_key": "public",
+ "secret_key": "secret",
+ "store_name": "Saleor",
+ "store_image": "image.gif",
+ "prefill": True,
+ "remember_me": True,
+ "locale": "auto",
+ "enable_billing_address": False,
+ "enable_shipping_address": False,
+ },
+ )
@pytest.fixture()
@@ -59,7 +80,7 @@ def stripe_payment(payment_dummy):
@pytest.fixture()
def stripe_authorized_payment(stripe_payment):
stripe_payment.charge_status = ChargeStatus.NOT_CHARGED
- stripe_payment.save(update_fields=['charge_status'])
+ stripe_payment.save(update_fields=["charge_status"])
return stripe_payment
@@ -68,115 +89,108 @@ def stripe_authorized_payment(stripe_payment):
def stripe_captured_payment(stripe_payment):
stripe_payment.captured_amount = stripe_payment.total
stripe_payment.charge_status = ChargeStatus.FULLY_CHARGED
- stripe_payment.save(update_fields=['captured_amount', 'charge_status'])
-
- return stripe_payment
-
-
-def stripe_charged_payment(stripe_payment):
- stripe_payment.captured_amount = stripe_payment.total
- stripe_payment.charge_status = ChargeStatus.FULLY_CHARGED
- stripe_payment.save(update_fields=['captured_amount', 'charge_status'])
-
+ stripe_payment.save(update_fields=["captured_amount", "charge_status"])
stripe_payment.transactions.create(
amount=stripe_payment.total,
- kind=TransactionKind.CHARGE,
+ kind=TransactionKind.CAPTURE,
gateway_response={},
- is_success=True)
+ is_success=True,
+ )
return stripe_payment
@pytest.fixture()
def stripe_charge_success_response():
return {
- 'id': TRANSACTION_TOKEN,
- 'amount': get_amount_for_stripe(
- TRANSACTION_AMOUNT, TRANSACTION_CURRENCY),
- 'amount_refunded': 0,
- 'currency': get_currency_for_stripe(TRANSACTION_CURRENCY),
- 'status': 'succeeded'}
+ "id": TRANSACTION_TOKEN,
+ "amount": get_amount_for_stripe(TRANSACTION_AMOUNT, TRANSACTION_CURRENCY),
+ "amount_refunded": 0,
+ "currency": get_currency_for_stripe(TRANSACTION_CURRENCY),
+ "status": "succeeded",
+ }
@pytest.fixture()
def stripe_partial_charge_success_response(stripe_charge_success_response):
response = stripe_charge_success_response.copy()
- response['amount_refunded'] = get_amount_for_stripe(
- TRANSACTION_REFUND_AMOUNT, TRANSACTION_CURRENCY)
+ response["amount_refunded"] = get_amount_for_stripe(
+ TRANSACTION_REFUND_AMOUNT, TRANSACTION_CURRENCY
+ )
return response
@pytest.fixture()
def stripe_refund_success_response(stripe_charge_success_response):
response = stripe_charge_success_response.copy()
- response.pop('amount_refunded')
- response['amount'] = get_amount_for_stripe(
- TRANSACTION_REFUND_AMOUNT, TRANSACTION_CURRENCY)
+ response.pop("amount_refunded")
+ response["amount"] = get_amount_for_stripe(
+ TRANSACTION_REFUND_AMOUNT, TRANSACTION_CURRENCY
+ )
return response
def test_get_amount_for_stripe():
- assert get_amount_for_stripe(Decimal(1), 'USD') == 100
- assert get_amount_for_stripe(Decimal(1), 'usd') == 100
+ assert get_amount_for_stripe(Decimal(1), "USD") == 100
+ assert get_amount_for_stripe(Decimal(1), "usd") == 100
- assert get_amount_for_stripe(Decimal(0.01), 'USD') == 1
- assert get_amount_for_stripe(Decimal(24.24), 'USD') == 2424
- assert get_amount_for_stripe(Decimal(42.42), 'USD') == 4242
+ assert get_amount_for_stripe(Decimal(0.01), "USD") == 1
+ assert get_amount_for_stripe(Decimal(24.24), "USD") == 2424
+ assert get_amount_for_stripe(Decimal(42.42), "USD") == 4242
- assert get_amount_for_stripe(Decimal(1), 'JPY') == 1
- assert get_amount_for_stripe(Decimal(1), 'jpy') == 1
+ assert get_amount_for_stripe(Decimal(1), "JPY") == 1
+ assert get_amount_for_stripe(Decimal(1), "jpy") == 1
def test_get_amount_from_stripe():
- assert get_amount_from_stripe(100, 'USD') == Decimal(1)
- assert get_amount_from_stripe(100, 'usd') == Decimal(1)
+ assert get_amount_from_stripe(100, "USD") == Decimal(1)
+ assert get_amount_from_stripe(100, "usd") == Decimal(1)
- assert isclose(
- get_amount_from_stripe(1, 'USD'), Decimal(0.01))
- assert isclose(
- get_amount_from_stripe(2424, 'USD'), Decimal(24.24))
- assert isclose(
- get_amount_from_stripe(4242, 'USD'), Decimal(42.42))
+ assert isclose(get_amount_from_stripe(1, "USD"), Decimal(0.01))
+ assert isclose(get_amount_from_stripe(2424, "USD"), Decimal(24.24))
+ assert isclose(get_amount_from_stripe(4242, "USD"), Decimal(42.42))
- assert get_amount_from_stripe(1, 'JPY') == Decimal(1)
- assert get_amount_from_stripe(1, 'jpy') == Decimal(1)
+ assert get_amount_from_stripe(1, "JPY") == Decimal(1)
+ assert get_amount_from_stripe(1, "jpy") == Decimal(1)
def test_get_currency_for_stripe():
- assert get_currency_for_stripe('USD') == 'usd'
- assert get_currency_for_stripe('usd') == 'usd'
- assert get_currency_for_stripe('uSd') == 'usd'
+ assert get_currency_for_stripe("USD") == "usd"
+ assert get_currency_for_stripe("usd") == "usd"
+ assert get_currency_for_stripe("uSd") == "usd"
def test_get_currency_from_stripe():
- assert get_currency_from_stripe('USD') == 'USD'
- assert get_currency_from_stripe('usd') == 'USD'
- assert get_currency_from_stripe('uSd') == 'USD'
+ assert get_currency_from_stripe("USD") == "USD"
+ assert get_currency_from_stripe("usd") == "USD"
+ assert get_currency_from_stripe("uSd") == "USD"
def test_get_payment_billing_fullname(payment_dummy):
payment_info = create_payment_information(payment_dummy)
- expected_fullname = '%s %s' % (
- payment_dummy.billing_last_name, payment_dummy.billing_first_name)
+ expected_fullname = "%s %s" % (
+ payment_dummy.billing_last_name,
+ payment_dummy.billing_first_name,
+ )
assert get_payment_billing_fullname(payment_info) == expected_fullname
def test_shipping_address_to_stripe_dict(address):
address_data = AddressData(**address.as_data())
expected_address_dict = {
- 'line1': address.street_address_1,
- 'line2': address.street_address_2,
- 'city': address.city,
- 'state': address.country_area,
- 'postal_code': address.postal_code,
- 'country': dict(countries).get(address.country, '')}
+ "line1": address.street_address_1,
+ "line2": address.street_address_2,
+ "city": address.city,
+ "state": address.country_area,
+ "postal_code": address.postal_code,
+ "country": dict(countries).get(address.country, ""),
+ }
assert shipping_to_stripe_dict(address_data) == expected_address_dict
-def test_widget_with_default_options(stripe_payment, gateway_params):
+def test_widget_with_default_options(stripe_payment, gateway_config):
payment_info = create_payment_information(stripe_payment)
- widget = StripeCheckoutWidget(payment_info, gateway_params)
+ widget = StripeCheckoutWidget(payment_info, gateway_config.connection_params)
assert widget.render() == (
'<script class="stripe-button" data-allow-remember-me="true" '
'data-amount="4242" data-billing-address="false" data-currency="USD" '
@@ -184,84 +198,96 @@ def test_widget_with_default_options(stripe_payment, gateway_params):
'data-image="image.gif" data-key="public" data-locale="auto" '
'data-name="Saleor" data-shipping-address="false" '
'data-zip-code="false" src="https://checkout.stripe.com/checkout.js">'
- '</script>')
+ "</script>"
+ )
-def test_widget_with_additional_attr(stripe_payment, gateway_params):
+def test_widget_with_additional_attr(stripe_payment, gateway_config):
payment_info = create_payment_information(stripe_payment)
widget = StripeCheckoutWidget(
- payment_info, gateway_params, attrs={'data-custom': 'custom-data'})
+ payment_info,
+ gateway_config.connection_params,
+ attrs={"data-custom": "custom-data"},
+ )
assert 'data-custom="custom-data"' in widget.render()
-def test_widget_with_prefill_option(stripe_payment, gateway_params):
+def test_widget_with_prefill_option(stripe_payment, gateway_config):
payment_info = create_payment_information(stripe_payment)
+ connection_params = gateway_config.connection_params
- gateway_params['prefill'] = True
- widget = StripeCheckoutWidget(payment_info, gateway_params)
+ connection_params["prefill"] = True
+ widget = StripeCheckoutWidget(payment_info, connection_params)
assert 'data-email="[email protected]"' in widget.render()
- gateway_params['prefill'] = False
- widget = StripeCheckoutWidget(payment_info, gateway_params)
+ connection_params["prefill"] = False
+ widget = StripeCheckoutWidget(payment_info, connection_params)
assert 'data-email="[email protected]"' not in widget.render()
-def test_widget_with_remember_me_option(stripe_payment, gateway_params):
+def test_widget_with_remember_me_option(stripe_payment, gateway_config):
payment_info = create_payment_information(stripe_payment)
+ connection_params = gateway_config.connection_params
- gateway_params['remember_me'] = True
- widget = StripeCheckoutWidget(payment_info, gateway_params)
+ connection_params["remember_me"] = True
+ widget = StripeCheckoutWidget(payment_info, connection_params)
assert 'data-allow-remember-me="true"' in widget.render()
- gateway_params['remember_me'] = False
- widget = StripeCheckoutWidget(payment_info, gateway_params)
+ connection_params["remember_me"] = False
+ widget = StripeCheckoutWidget(payment_info, connection_params)
assert 'data-allow-remember-me="false"' in widget.render()
-def test_widget_with_enable_billing_address_option(stripe_payment, gateway_params):
+def test_widget_with_enable_billing_address_option(stripe_payment, gateway_config):
payment_info = create_payment_information(stripe_payment, FAKE_TOKEN)
+ connection_params = gateway_config.connection_params
- gateway_params['enable_billing_address'] = True
- widget = StripeCheckoutWidget(payment_info, gateway_params)
+ connection_params["enable_billing_address"] = True
+ widget = StripeCheckoutWidget(payment_info, connection_params)
assert 'data-billing-address="true"' in widget.render()
assert 'data-zip-code="true"' in widget.render()
- gateway_params['enable_billing_address'] = False
- widget = StripeCheckoutWidget(payment_info, gateway_params)
+ connection_params["enable_billing_address"] = False
+ widget = StripeCheckoutWidget(payment_info, connection_params)
assert 'data-billing-address="false"' in widget.render()
assert 'data-zip-code="false"' in widget.render()
-def test_widget_with_enable_shipping_address_option(stripe_payment, gateway_params):
+def test_widget_with_enable_shipping_address_option(stripe_payment, gateway_config):
payment_info = create_payment_information(stripe_payment, FAKE_TOKEN)
+ connection_params = gateway_config.connection_params
- gateway_params['enable_shipping_address'] = True
- widget = StripeCheckoutWidget(payment_info, gateway_params)
+ connection_params["enable_shipping_address"] = True
+ widget = StripeCheckoutWidget(payment_info, connection_params)
assert 'data-shipping-address="true"' in widget.render()
- gateway_params['enable_shipping_address'] = False
- widget = StripeCheckoutWidget(payment_info, gateway_params)
+ connection_params["enable_shipping_address"] = False
+ widget = StripeCheckoutWidget(payment_info, connection_params)
assert 'data-shipping-address="false"' in widget.render()
-def test_stripe_payment_form(stripe_payment, gateway_params):
+def test_stripe_payment_form(stripe_payment, gateway_config):
payment_info = create_payment_information(stripe_payment, FAKE_TOKEN)
form = create_form(
- None, payment_information=payment_info,
- connection_params=gateway_params)
+ None,
+ payment_information=payment_info,
+ connection_params=gateway_config.connection_params,
+ )
assert isinstance(form, StripePaymentModalForm)
assert not form.is_valid()
form = create_form(
- data={'stripeToken': FAKE_TOKEN}, payment_information=payment_info,
- connection_params=gateway_params)
+ data={"stripeToken": FAKE_TOKEN},
+ payment_information=payment_info,
+ connection_params=gateway_config.connection_params,
+ )
assert isinstance(form, StripePaymentModalForm)
assert form.is_valid()
-def test_get_client(gateway_params):
- assert _get_client(**gateway_params).api_key == 'secret'
+def test_get_client(gateway_config):
+ assert _get_client(**gateway_config.connection_params).api_key == "secret"
def test_get_client_token():
@@ -269,13 +295,12 @@ def test_get_client_token():
def test_get_error_response_from_exc():
- stripe_error = stripe.error.StripeError(
- json_body={'message': ERROR_MESSAGE})
+ stripe_error = stripe.error.StripeError(json_body={"message": ERROR_MESSAGE})
invalid_request_error = stripe.error.InvalidRequestError(
- message=ERROR_MESSAGE, param=None)
+ message=ERROR_MESSAGE, param=None
+ )
- assert _get_error_response_from_exc(stripe_error) == {
- 'message': ERROR_MESSAGE}
+ assert _get_error_response_from_exc(stripe_error) == {"message": ERROR_MESSAGE}
assert _get_error_response_from_exc(invalid_request_error) == {}
@@ -283,15 +308,16 @@ def test_get_stripe_charge_payload_with_shipping(stripe_payment):
payment_info = create_payment_information(stripe_payment, FAKE_TOKEN)
billing_name = get_payment_billing_fullname(payment_info)
expected_payload = {
- 'capture': True,
- 'amount': get_amount_for_stripe(
- TRANSACTION_AMOUNT, TRANSACTION_CURRENCY),
- 'currency': get_currency_for_stripe(TRANSACTION_CURRENCY),
- 'source': FAKE_TOKEN,
- 'description': billing_name,
- 'shipping': {
- 'name': billing_name,
- 'address': shipping_to_stripe_dict(payment_info.shipping)}}
+ "capture": True,
+ "amount": get_amount_for_stripe(TRANSACTION_AMOUNT, TRANSACTION_CURRENCY),
+ "currency": get_currency_for_stripe(TRANSACTION_CURRENCY),
+ "source": FAKE_TOKEN,
+ "description": billing_name,
+ "shipping": {
+ "name": billing_name,
+ "address": shipping_to_stripe_dict(payment_info.shipping),
+ },
+ }
charge_payload = _get_stripe_charge_payload(payment_info, True)
@@ -303,12 +329,12 @@ def test_get_stripe_charge_payload_without_shipping(stripe_payment):
payment_info = create_payment_information(stripe_payment, FAKE_TOKEN)
billing_name = get_payment_billing_fullname(payment_info)
expected_payload = {
- 'capture': True,
- 'amount': get_amount_for_stripe(
- TRANSACTION_AMOUNT, TRANSACTION_CURRENCY),
- 'currency': get_currency_for_stripe(TRANSACTION_CURRENCY),
- 'source': FAKE_TOKEN,
- 'description': billing_name}
+ "capture": True,
+ "amount": get_amount_for_stripe(TRANSACTION_AMOUNT, TRANSACTION_CURRENCY),
+ "currency": get_currency_for_stripe(TRANSACTION_CURRENCY),
+ "source": FAKE_TOKEN,
+ "description": billing_name,
+ }
charge_payload = _get_stripe_charge_payload(payment_info, True)
@@ -316,13 +342,16 @@ def test_get_stripe_charge_payload_without_shipping(stripe_payment):
def test_create_transaction_with_charge_success_response(
- stripe_payment,
- stripe_charge_success_response):
+ stripe_payment, stripe_charge_success_response
+):
payment_info = create_payment_information(stripe_payment)
response = _create_response(
- payment_information=payment_info, kind='ANYKIND',
- response=stripe_charge_success_response, error=None)
+ payment_information=payment_info,
+ kind="ANYKIND",
+ response=stripe_charge_success_response,
+ error=None,
+ )
assert response.transaction_id == TRANSACTION_TOKEN
assert response.is_success is True
@@ -331,29 +360,34 @@ def test_create_transaction_with_charge_success_response(
def test_create_transaction_with_partial_charge_success_response(
- stripe_payment,
- stripe_partial_charge_success_response):
+ stripe_payment, stripe_partial_charge_success_response
+):
payment_info = create_payment_information(stripe_payment)
response = _create_response(
- payment_information=payment_info, kind='ANYKIND',
- response=stripe_partial_charge_success_response, error=None)
+ payment_information=payment_info,
+ kind="ANYKIND",
+ response=stripe_partial_charge_success_response,
+ error=None,
+ )
assert response.transaction_id == TRANSACTION_TOKEN
assert response.is_success is True
- assert isclose(
- response.amount, TRANSACTION_AMOUNT - TRANSACTION_REFUND_AMOUNT)
+ assert isclose(response.amount, TRANSACTION_AMOUNT - TRANSACTION_REFUND_AMOUNT)
assert response.currency == TRANSACTION_CURRENCY
def test_create_transaction_with_refund_success_response(
- stripe_payment,
- stripe_refund_success_response):
+ stripe_payment, stripe_refund_success_response
+):
payment_info = create_payment_information(stripe_payment)
response = _create_response(
- payment_information=payment_info, kind='ANYKIND',
- response=stripe_refund_success_response, error=None)
+ payment_information=payment_info,
+ kind="ANYKIND",
+ response=stripe_refund_success_response,
+ error=None,
+ )
assert response.transaction_id == TRANSACTION_TOKEN
assert response.is_success is True
@@ -367,8 +401,11 @@ def test_create_response_with_error_response(stripe_payment):
stripe_error_response = {}
response = _create_response(
- payment_information=payment_info, kind='ANYKIND',
- response=stripe_error_response, error=None)
+ payment_information=payment_info,
+ kind="ANYKIND",
+ response=stripe_error_response,
+ error=None,
+ )
assert response.transaction_id == FAKE_TOKEN
assert response.is_success is False
@@ -377,18 +414,16 @@ def test_create_response_with_error_response(stripe_payment):
@pytest.mark.integration
-@patch('stripe.Charge.create')
+@patch("stripe.Charge.create")
def test_authorize(
- mock_charge_create,
- stripe_payment,
- gateway_params,
- stripe_charge_success_response):
+ mock_charge_create, stripe_payment, gateway_config, stripe_charge_success_response
+):
payment = stripe_payment
payment_info = create_payment_information(payment, FAKE_TOKEN)
response = stripe_charge_success_response
mock_charge_create.return_value = response
- response = authorize(payment_info, gateway_params)
+ response = authorize(payment_info, gateway_config)
assert not response.error
assert response.transaction_id == TRANSACTION_TOKEN
@@ -400,18 +435,14 @@ def test_authorize(
@pytest.mark.integration
-@patch('stripe.Charge.create')
-def test_authorize_error_response(
- mock_charge_create,
- stripe_payment,
- gateway_params):
+@patch("stripe.Charge.create")
+def test_authorize_error_response(mock_charge_create, stripe_payment, gateway_config):
payment = stripe_payment
payment_info = create_payment_information(payment, FAKE_TOKEN)
- stripe_error = stripe.error.InvalidRequestError(
- message=ERROR_MESSAGE, param=None)
+ stripe_error = stripe.error.InvalidRequestError(message=ERROR_MESSAGE, param=None)
mock_charge_create.side_effect = stripe_error
- response = authorize(payment_info, gateway_params)
+ response = authorize(payment_info, gateway_config)
assert response.error == ERROR_MESSAGE
assert response.transaction_id == FAKE_TOKEN
@@ -423,20 +454,19 @@ def test_authorize_error_response(
@pytest.mark.integration
-@patch('stripe.Charge.retrieve')
+@patch("stripe.Charge.retrieve")
def test_capture(
- mock_charge_retrieve,
- stripe_authorized_payment,
- gateway_params,
- stripe_charge_success_response):
+ mock_charge_retrieve,
+ stripe_authorized_payment,
+ gateway_config,
+ stripe_charge_success_response,
+):
payment = stripe_authorized_payment
- payment_info = create_payment_information(
- payment, amount=TRANSACTION_AMOUNT)
+ payment_info = create_payment_information(payment, amount=TRANSACTION_AMOUNT)
response = stripe_charge_success_response
- mock_charge_retrieve.return_value = Mock(
- capture=Mock(return_value=response))
+ mock_charge_retrieve.return_value = Mock(capture=Mock(return_value=response))
- response = capture(payment_info, gateway_params)
+ response = capture(payment_info, gateway_config)
assert not response.error
assert response.transaction_id == TRANSACTION_TOKEN
@@ -448,45 +478,42 @@ def test_capture(
@pytest.mark.integration
-@patch('stripe.Charge.retrieve')
+@patch("stripe.Charge.retrieve")
def test_partial_capture(
- mock_charge_retrieve,
- stripe_authorized_payment,
- gateway_params,
- stripe_partial_charge_success_response):
+ mock_charge_retrieve,
+ stripe_authorized_payment,
+ gateway_config,
+ stripe_partial_charge_success_response,
+):
payment = stripe_authorized_payment
- payment_info = create_payment_information(
- payment, amount=TRANSACTION_AMOUNT)
+ payment_info = create_payment_information(payment, amount=TRANSACTION_AMOUNT)
response = stripe_partial_charge_success_response
- mock_charge_retrieve.return_value = Mock(
- capture=Mock(return_value=response))
+ mock_charge_retrieve.return_value = Mock(capture=Mock(return_value=response))
- response = capture(payment_info, gateway_params)
+ response = capture(payment_info, gateway_config)
assert not response.error
assert response.transaction_id == TRANSACTION_TOKEN
assert response.kind == TransactionKind.CAPTURE
assert response.is_success
- assert isclose(
- response.amount, TRANSACTION_AMOUNT - TRANSACTION_REFUND_AMOUNT)
+ assert isclose(response.amount, TRANSACTION_AMOUNT - TRANSACTION_REFUND_AMOUNT)
assert response.currency == TRANSACTION_CURRENCY
assert response.raw_response == stripe_partial_charge_success_response
@pytest.mark.integration
-@patch('stripe.Charge.retrieve')
+@patch("stripe.Charge.retrieve")
def test_capture_error_response(
- mock_charge_retrieve,
- stripe_authorized_payment,
- gateway_params):
+ mock_charge_retrieve, stripe_authorized_payment, gateway_config
+):
payment = stripe_authorized_payment
payment_info = create_payment_information(
- payment, TRANSACTION_TOKEN, amount=TRANSACTION_AMOUNT)
- stripe_error = stripe.error.InvalidRequestError(
- message=ERROR_MESSAGE, param=None)
+ payment, TRANSACTION_TOKEN, amount=TRANSACTION_AMOUNT
+ )
+ stripe_error = stripe.error.InvalidRequestError(message=ERROR_MESSAGE, param=None)
mock_charge_retrieve.side_effect = stripe_error
- response = capture(payment_info, gateway_params)
+ response = capture(payment_info, gateway_config)
assert response.error == ERROR_MESSAGE
assert response.transaction_id == TRANSACTION_TOKEN
@@ -498,70 +525,24 @@ def test_capture_error_response(
@pytest.mark.integration
-@patch('stripe.Charge.create')
-def test_charge(
- mock_charge_create,
- stripe_payment,
- gateway_params,
- stripe_charge_success_response):
- payment = stripe_payment
- payment_info = create_payment_information(
- payment, FAKE_TOKEN, TRANSACTION_AMOUNT)
- response = stripe_charge_success_response
- mock_charge_create.return_value = response
-
- response = charge(payment_info, gateway_params)
-
- assert not response.error
- assert response.transaction_id == TRANSACTION_TOKEN
- assert response.kind == TransactionKind.CHARGE
- assert response.is_success
- assert isclose(response.amount, TRANSACTION_AMOUNT)
- assert response.currency == TRANSACTION_CURRENCY
- assert response.raw_response == stripe_charge_success_response
-
-
-@patch('stripe.Charge.create')
-def test_charge_error_response(
- mock_charge_create,
- stripe_payment,
- gateway_params):
- payment = stripe_payment
- payment_info = create_payment_information(
- payment, FAKE_TOKEN, TRANSACTION_AMOUNT)
- stripe_error = stripe.error.InvalidRequestError(
- message=ERROR_MESSAGE, param=None)
- mock_charge_create.side_effect = stripe_error
-
- response = charge(payment_info, gateway_params)
-
- assert response.error == ERROR_MESSAGE
- assert response.transaction_id == FAKE_TOKEN
- assert response.kind == TransactionKind.CHARGE
- assert not response.is_success
- assert response.amount == payment.total
- assert response.currency == payment.currency
- assert response.raw_response == _get_error_response_from_exc(stripe_error)
-
-
-@patch('stripe.Refund.create')
-@patch('stripe.Charge.retrieve')
+@patch("stripe.Refund.create")
+@patch("stripe.Charge.retrieve")
def test_refund_charged(
- mock_charge_retrieve,
- mock_refund_create,
- stripe_charged_payment,
- gateway_params,
- stripe_refund_success_response):
- payment = stripe_charged_payment
+ mock_charge_retrieve,
+ mock_refund_create,
+ stripe_captured_payment,
+ gateway_config,
+ stripe_refund_success_response,
+):
+ payment = stripe_captured_payment
payment_info = create_payment_information(
- payment, TRANSACTION_TOKEN, amount=TRANSACTION_AMOUNT)
+ payment, TRANSACTION_TOKEN, amount=TRANSACTION_AMOUNT
+ )
response = stripe_refund_success_response
- mock_charge_retrieve.return_value = Mock(id='')
+ mock_charge_retrieve.return_value = Mock(id="")
mock_refund_create.return_value = response
- response = refund(payment_info, gateway_params)
+ response = refund(payment_info, gateway_config)
assert not response.error
assert response.transaction_id == TRANSACTION_TOKEN
@@ -573,22 +554,22 @@ def test_refund_charged(
@pytest.mark.integration
-@patch('stripe.Refund.create')
-@patch('stripe.Charge.retrieve')
+@patch("stripe.Refund.create")
+@patch("stripe.Charge.retrieve")
def test_refund_captured(
- mock_charge_retrieve,
- mock_refund_create,
- stripe_captured_payment,
- gateway_params,
- stripe_refund_success_response):
+ mock_charge_retrieve,
+ mock_refund_create,
+ stripe_captured_payment,
+ gateway_config,
+ stripe_refund_success_response,
+):
payment = stripe_captured_payment
- payment_info = create_payment_information(
- payment, amount=TRANSACTION_AMOUNT)
+ payment_info = create_payment_information(payment, amount=TRANSACTION_AMOUNT)
response = stripe_refund_success_response
- mock_charge_retrieve.return_value = Mock(id='')
+ mock_charge_retrieve.return_value = Mock(id="")
mock_refund_create.return_value = response
- response = refund(payment_info, gateway_params)
+ response = refund(payment_info, gateway_config)
assert not response.error
assert response.transaction_id == TRANSACTION_TOKEN
@@ -600,22 +581,20 @@ def test_refund_captured(
@pytest.mark.integration
-@patch('stripe.Refund.create')
-@patch('stripe.Charge.retrieve')
+@patch("stripe.Refund.create")
+@patch("stripe.Charge.retrieve")
def test_refund_error_response(
- mock_charge_retrieve,
- mock_refund_create,
- stripe_charged_payment,
- gateway_params):
- payment = stripe_charged_payment
+ mock_charge_retrieve, mock_refund_create, stripe_captured_payment, gateway_config
+):
+ payment = stripe_captured_payment
payment_info = create_payment_information(
- payment, TRANSACTION_TOKEN, amount=TRANSACTION_AMOUNT)
- mock_charge_retrieve.return_value = Mock(id='')
- stripe_error = stripe.error.InvalidRequestError(
- message=ERROR_MESSAGE, param=None)
+ payment, TRANSACTION_TOKEN, amount=TRANSACTION_AMOUNT
+ )
+ mock_charge_retrieve.return_value = Mock(id="")
+ stripe_error = stripe.error.InvalidRequestError(message=ERROR_MESSAGE, param=None)
mock_refund_create.side_effect = stripe_error
- response = refund(payment_info, gateway_params)
+ response = refund(payment_info, gateway_config)
assert response.error == ERROR_MESSAGE
assert response.transaction_id == TRANSACTION_TOKEN
@@ -627,21 +606,22 @@ def test_refund_error_response(
@pytest.mark.integration
-@patch('stripe.Refund.create')
-@patch('stripe.Charge.retrieve')
+@patch("stripe.Refund.create")
+@patch("stripe.Charge.retrieve")
def test_void(
- mock_charge_retrieve,
- mock_refund_create,
- stripe_authorized_payment,
- gateway_params,
- stripe_refund_success_response):
+ mock_charge_retrieve,
+ mock_refund_create,
+ stripe_authorized_payment,
+ gateway_config,
+ stripe_refund_success_response,
+):
payment = stripe_authorized_payment
payment_info = create_payment_information(payment, TRANSACTION_TOKEN)
response = stripe_refund_success_response
- mock_charge_retrieve.return_value = Mock(id='')
+ mock_charge_retrieve.return_value = Mock(id="")
mock_refund_create.return_value = response
- response = void(payment_info, gateway_params)
+ response = void(payment_info, gateway_config)
assert not response.error
assert response.transaction_id == TRANSACTION_TOKEN
@@ -653,21 +633,18 @@ def test_void(
@pytest.mark.integration
-@patch('stripe.Refund.create')
-@patch('stripe.Charge.retrieve')
+@patch("stripe.Refund.create")
+@patch("stripe.Charge.retrieve")
def test_void_error_response(
- mock_charge_retrieve,
- mock_refund_create,
- stripe_authorized_payment,
- gateway_params):
+ mock_charge_retrieve, mock_refund_create, stripe_authorized_payment, gateway_config
+):
payment = stripe_authorized_payment
payment_info = create_payment_information(payment, TRANSACTION_TOKEN)
- mock_charge_retrieve.return_value = Mock(id='')
- stripe_error = stripe.error.InvalidRequestError(
- message=ERROR_MESSAGE, param=None)
+ mock_charge_retrieve.return_value = Mock(id="")
+ stripe_error = stripe.error.InvalidRequestError(message=ERROR_MESSAGE, param=None)
mock_refund_create.side_effect = stripe_error
- response = void(payment_info, gateway_params)
+ response = void(payment_info, gateway_config)
assert response.error == ERROR_MESSAGE
assert response.transaction_id == TRANSACTION_TOKEN
diff --git a/tests/test_payment.py b/tests/test_payment.py
index b5dcba7f43..931f5891ff 100644
--- a/tests/test_payment.py
+++ b/tests/test_payment.py
@@ -9,58 +9,79 @@ from django.template.loader import get_template
from saleor.order import OrderEvents, OrderEventsEmails
from saleor.order.views import PAYMENT_TEMPLATE
from saleor.payment import (
- ChargeStatus, GatewayError, OperationType, PaymentError, TransactionKind,
- get_payment_gateway)
-from saleor.payment.interface import GatewayResponse
+ ChargeStatus,
+ GatewayError,
+ OperationType,
+ PaymentError,
+ TransactionKind,
+ get_payment_gateway,
+)
+from saleor.payment.interface import ConfigData, GatewayResponse
from saleor.payment.models import Payment
from saleor.payment.utils import (
- ALLOWED_GATEWAY_KINDS, call_gateway,
- clean_authorize, clean_capture, clean_mark_order_as_paid,
- create_payment, create_payment_information, create_transaction,
- gateway_authorize, gateway_capture,
- gateway_get_client_token, gateway_process_payment, gateway_refund,
- gateway_void, handle_fully_paid_order, mark_order_as_paid,
- require_active_payment, validate_gateway_response)
-
-NOT_ACTIVE_PAYMENT_ERROR = 'This payment is no longer active.'
-EXAMPLE_ERROR = 'Example dummy error'
+ ALLOWED_GATEWAY_KINDS,
+ call_gateway,
+ clean_authorize,
+ clean_capture,
+ clean_mark_order_as_paid,
+ create_payment,
+ create_payment_information,
+ create_transaction,
+ gateway_authorize,
+ gateway_capture,
+ gateway_get_client_token,
+ gateway_process_payment,
+ gateway_refund,
+ gateway_void,
+ handle_fully_paid_order,
+ mark_order_as_paid,
+ require_active_payment,
+ validate_gateway_response,
+)
+
+NOT_ACTIVE_PAYMENT_ERROR = "This payment is no longer active."
+EXAMPLE_ERROR = "Example dummy error"
@pytest.fixture
def gateway_response(settings):
return GatewayResponse(
is_success=True,
- transaction_id='transaction-token',
+ transaction_id="transaction-token",
amount=Decimal(14.50),
currency=settings.DEFAULT_CURRENCY,
kind=TransactionKind.CAPTURE,
error=None,
raw_response={
- 'credit_card_four': '1234',
- 'transaction-id': 'transaction-token',
- }
+ "credit_card_four": "1234",
+ "transaction-id": "transaction-token",
+ },
)
-
@pytest.fixture
def transaction_data(payment_dummy, gateway_response):
return {
- 'payment': payment_dummy,
- 'payment_information': create_payment_information(
- payment_dummy, 'payment-token'),
- 'kind': TransactionKind.CAPTURE,
- 'gateway_response': gateway_response}
+ "payment": payment_dummy,
+ "payment_information": create_payment_information(
+ payment_dummy, "payment-token"
+ ),
+ "kind": TransactionKind.CAPTURE,
+ "gateway_response": gateway_response,
+ }
@pytest.fixture
-def gateway_params():
- return {'secret-key': 'nobodylikesspanishinqusition'}
+def gateway_config():
+ return ConfigData(
+ auto_capture=True,
+ connection_params={"secret-key": "nobodylikesspanishinqusition"},
+ )
@pytest.fixture
def transaction_token():
- return 'transaction-token'
+ return "transaction-token"
@pytest.fixture
@@ -72,20 +93,20 @@ def dummy_response(payment_dummy, transaction_data, transaction_token):
amount=payment_dummy.total,
currency=payment_dummy.currency,
kind=TransactionKind.AUTH,
- raw_response=None
+ raw_response=None,
)
def test_get_payment_gateway_not_allowed_checkout_choice(settings):
- gateway = 'example-gateway'
+ gateway = "example-gateway"
settings.CHECKOUT_PAYMENT_GATEWAYS = {}
with pytest.raises(ValueError):
get_payment_gateway(gateway)
def test_get_payment_gateway_non_existing_name(settings):
- gateway = 'example-gateway'
- settings.CHECKOUT_PAYMENT_GATEWAYS = {gateway: 'Example gateway'}
+ gateway = "example-gateway"
+ settings.CHECKOUT_PAYMENT_GATEWAYS = {gateway: "Example gateway"}
with pytest.raises(ImproperlyConfigured):
get_payment_gateway(gateway)
@@ -93,16 +114,16 @@ def test_get_payment_gateway_non_existing_name(settings):
def test_get_payment_gateway(settings):
gateway_name = list(settings.PAYMENT_GATEWAYS.keys())[0]
gateway = settings.PAYMENT_GATEWAYS[gateway_name]
- gateway_module, gateway_params = get_payment_gateway(gateway_name)
- assert gateway_module.__name__ == gateway['module']
- assert gateway_params == gateway['connection_params']
+ gateway_module, gateway_config = get_payment_gateway(gateway_name)
+ assert gateway_module.__name__ == gateway["module"]
+ assert gateway_config.connection_params == gateway["config"]["connection_params"]
+ assert gateway_config.auto_capture == gateway["config"]["auto_capture"]
-@patch('saleor.order.emails.send_payment_confirmation.delay')
-def test_handle_fully_paid_order_no_email(
- mock_send_payment_confirmation, order):
+@patch("saleor.order.emails.send_payment_confirmation.delay")
+def test_handle_fully_paid_order_no_email(mock_send_payment_confirmation, order):
order.user = None
- order.user_email = ''
+ order.user_email = ""
handle_fully_paid_order(order)
event = order.events.get()
@@ -110,7 +131,7 @@ def test_handle_fully_paid_order_no_email(
assert not mock_send_payment_confirmation.called
-@patch('saleor.order.emails.send_payment_confirmation.delay')
+@patch("saleor.order.emails.send_payment_confirmation.delay")
def test_handle_fully_paid_order(mock_send_payment_confirmation, order):
handle_fully_paid_order(order)
event_order_paid, event_email_sent = order.events.all()
@@ -118,8 +139,9 @@ def test_handle_fully_paid_order(mock_send_payment_confirmation, order):
assert event_email_sent.type == OrderEvents.EMAIL_SENT.value
assert event_email_sent.parameters == {
- 'email': order.get_user_current_email(),
- 'email_type': OrderEventsEmails.PAYMENT.value}
+ "email": order.get_user_current_email(),
+ "email_type": OrderEventsEmails.PAYMENT.value,
+ }
mock_send_payment_confirmation.assert_called_once_with(order.pk)
@@ -139,13 +161,14 @@ def test_require_active_payment():
def test_create_payment(address, settings):
data = {
- 'gateway': settings.DUMMY,
- 'payment_token': 'token',
- 'total': 10,
- 'currency': settings.DEFAULT_CURRENCY,
- 'email': '[email protected]',
- 'billing_address': address,
- 'customer_ip_address': '127.0.0.1'}
+ "gateway": settings.DUMMY,
+ "payment_token": "token",
+ "total": 10,
+ "currency": settings.DEFAULT_CURRENCY,
+ "email": "[email protected]",
+ "billing_address": address,
+ "customer_ip_address": "127.0.0.1",
+ }
payment = create_payment(**data)
assert payment.gateway == settings.DUMMY
@@ -158,8 +181,7 @@ def test_mark_as_paid(admin_user, draft_order):
payment = draft_order.payments.last()
assert payment.charge_status == ChargeStatus.FULLY_CHARGED
assert payment.captured_amount == draft_order.total.gross.amount
- assert draft_order.events.last().type == (
- OrderEvents.ORDER_MARKED_AS_PAID.value)
+ assert draft_order.events.last().type == (OrderEvents.ORDER_MARKED_AS_PAID.value)
def test_clean_mark_order_as_paid(payment_txn_preauth):
@@ -171,8 +193,8 @@ def test_clean_mark_order_as_paid(payment_txn_preauth):
def test_create_transaction(transaction_data):
txn = create_transaction(**transaction_data)
- assert txn.payment == transaction_data['payment']
- gateway_response = transaction_data['gateway_response']
+ assert txn.payment == transaction_data["payment"]
+ gateway_response = transaction_data["gateway_response"]
assert txn.kind == gateway_response.kind
assert txn.amount == gateway_response.amount
assert txn.currency == gateway_response.currency
@@ -182,88 +204,108 @@ def test_create_transaction(transaction_data):
def test_create_transaction_no_gateway_response(transaction_data):
- transaction_data.pop('gateway_response')
+ transaction_data.pop("gateway_response")
txn = create_transaction(**transaction_data)
assert txn.gateway_response == {}
-@patch('saleor.payment.utils.get_payment_gateway')
-def test_gateway_get_client_token(get_payment_gateway_mock, gateway_params):
- get_client_token_mock = Mock(return_value='client-token')
+@patch("saleor.payment.utils.get_payment_gateway")
+def test_gateway_get_client_token(get_payment_gateway_mock, gateway_config):
+ get_client_token_mock = Mock(return_value="client-token")
get_payment_gateway_mock.return_value = (
- Mock(get_client_token=get_client_token_mock), gateway_params)
+ Mock(get_client_token=get_client_token_mock),
+ gateway_config,
+ )
- token = gateway_get_client_token('some-gateway')
+ token = gateway_get_client_token("some-gateway")
- assert token == 'client-token'
- get_client_token_mock.assert_called_once_with(
- connection_params=gateway_params)
+ assert token == "client-token"
+ get_client_token_mock.assert_called_once_with(config=gateway_config)
def test_gateway_get_client_token_not_allowed_gateway(settings):
- gateway = 'example-gateway'
+ gateway = "example-gateway"
settings.CHECKOUT_PAYMENT_GATEWAYS = {}
with pytest.raises(ValueError):
gateway_get_client_token(gateway)
def test_gateway_get_client_token_not_existing_gateway(settings):
- gateway = 'example-gateway'
- settings.CHECKOUT_PAYMENT_GATEWAYS = {gateway: 'Example gateway'}
+ gateway = "example-gateway"
+ settings.CHECKOUT_PAYMENT_GATEWAYS = {gateway: "Example gateway"}
with pytest.raises(ImproperlyConfigured):
gateway_get_client_token(gateway)
@pytest.mark.parametrize(
- 'func', [gateway_authorize, gateway_capture, gateway_refund, gateway_void])
+ "func", [gateway_authorize, gateway_capture, gateway_refund, gateway_void]
+)
def test_payment_needs_to_be_active_for_any_action(func, payment_dummy):
payment_dummy.is_active = False
with pytest.raises(PaymentError) as exc:
- func(payment_dummy, 'token')
+ func(payment_dummy, "token")
assert exc.value.message == NOT_ACTIVE_PAYMENT_ERROR
-@patch('saleor.payment.utils.get_payment_gateway')
+@patch("saleor.payment.utils.get_payment_gateway")
def test_gateway_process_payment(
- mock_get_payment_gateway, payment_txn_preauth, gateway_params,
- transaction_token, dummy_response):
+ mock_get_payment_gateway,
+ payment_txn_preauth,
+ gateway_config,
+ transaction_token,
+ dummy_response,
+):
payment_token = transaction_token
payment = payment_txn_preauth
mock_process_payment = Mock(return_value=dummy_response)
mock_get_payment_gateway.return_value = (
- Mock(process_payment=mock_process_payment), gateway_params)
+ Mock(process_payment=mock_process_payment),
+ gateway_config,
+ )
payment_info = create_payment_information(payment, payment_token)
gateway_process_payment(payment, payment_token)
mock_get_payment_gateway.assert_called_with(payment.gateway)
mock_process_payment.assert_called_once_with(
- payment_information=payment_info, connection_params=gateway_params)
+ payment_information=payment_info, config=gateway_config
+ )
-@patch('saleor.payment.utils.get_payment_gateway')
+@patch("saleor.payment.utils.get_payment_gateway")
def test_gateway_authorize(
- mock_get_payment_gateway, payment_txn_preauth, gateway_params,
- transaction_token, dummy_response):
+ mock_get_payment_gateway,
+ payment_txn_preauth,
+ gateway_config,
+ transaction_token,
+ dummy_response,
+):
payment = payment_txn_preauth
payment_token = transaction_token
mock_authorize = Mock(return_value=dummy_response)
mock_get_payment_gateway.return_value = (
- Mock(authorize=mock_authorize), gateway_params)
+ Mock(authorize=mock_authorize),
+ gateway_config,
+ )
payment_info = create_payment_information(payment, payment_token)
gateway_authorize(payment, payment_token)
mock_get_payment_gateway.assert_called_once_with(payment.gateway)
mock_authorize.assert_called_once_with(
- payment_information=payment_info, connection_params=gateway_params)
+ payment_information=payment_info, config=gateway_config
+ )
-@patch('saleor.payment.utils.get_payment_gateway')
+@patch("saleor.payment.utils.get_payment_gateway")
def test_gateway_authorize_failed(
- mock_get_payment_gateway, payment_txn_preauth, gateway_params,
- transaction_token, dummy_response):
+ mock_get_payment_gateway,
+ payment_txn_preauth,
+ gateway_config,
+ transaction_token,
+ dummy_response,
+):
payment_token = transaction_token
txn = payment_txn_preauth.transactions.first()
txn.is_success = False
@@ -272,7 +314,9 @@ def test_gateway_authorize_failed(
dummy_response.is_success = False
mock_authorize = Mock(return_value=dummy_response)
mock_get_payment_gateway.return_value = (
- Mock(authorize=mock_authorize), gateway_params)
+ Mock(authorize=mock_authorize),
+ gateway_config,
+ )
with pytest.raises(PaymentError) as exc:
gateway_authorize(payment, payment_token)
assert exc.value.message == EXAMPLE_ERROR
@@ -281,31 +325,34 @@ def test_gateway_authorize_failed(
def test_gateway_authorize_errors(payment_dummy):
payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED
with pytest.raises(PaymentError) as exc:
- gateway_authorize(payment_dummy, 'payment-token')
- assert exc.value.message == (
- 'Charged transactions cannot be authorized again.')
+ gateway_authorize(payment_dummy, "payment-token")
+ assert exc.value.message == ("Charged transactions cannot be authorized again.")
-@patch('saleor.payment.gateways.dummy.SUPPORTS_AUTHORIZATION', new=True)
-@patch('saleor.payment.utils.handle_fully_paid_order')
-@patch('saleor.payment.utils.get_payment_gateway')
+@patch("saleor.payment.utils.handle_fully_paid_order")
+@patch("saleor.payment.utils.get_payment_gateway")
def test_gateway_capture(
- mock_get_payment_gateway, mock_handle_fully_paid_order, payment_txn_preauth,
- gateway_params, dummy_response):
+ mock_get_payment_gateway,
+ mock_handle_fully_paid_order,
+ payment_txn_preauth,
+ gateway_config,
+ dummy_response,
+):
payment = payment_txn_preauth
+ gateway_config.auto_capture = True
assert not payment.captured_amount
amount = payment.total
dummy_response.kind = TransactionKind.CAPTURE
mock_capture = Mock(return_value=dummy_response)
- mock_get_payment_gateway.return_value = (
- Mock(capture=mock_capture), gateway_params)
+ mock_get_payment_gateway.return_value = (Mock(capture=mock_capture), gateway_config)
- payment_info = create_payment_information(payment, '', amount)
+ payment_info = create_payment_information(payment, "", amount)
gateway_capture(payment, amount)
mock_capture.assert_called_once_with(
- payment_information=payment_info, connection_params=gateway_params)
+ payment_information=payment_info, config=gateway_config
+ )
payment.refresh_from_db()
assert payment.charge_status == ChargeStatus.FULLY_CHARGED
@@ -313,14 +360,18 @@ def test_gateway_capture(
mock_handle_fully_paid_order.assert_called_once_with(payment.order)
-@patch('saleor.payment.gateways.dummy.SUPPORTS_AUTHORIZATION', new=True)
-@patch('saleor.payment.utils.handle_fully_paid_order')
-@patch('saleor.payment.utils.get_payment_gateway')
+@patch("saleor.payment.utils.handle_fully_paid_order")
+@patch("saleor.payment.utils.get_payment_gateway")
def test_gateway_capture_partial_capture(
- mock_get_payment_gateway, mock_handle_fully_paid_order,
- payment_txn_preauth, gateway_params, settings, dummy_response):
+ mock_get_payment_gateway,
+ mock_handle_fully_paid_order,
+ payment_txn_preauth,
+ gateway_config,
+ settings,
+ dummy_response,
+):
payment = payment_txn_preauth
- amount = payment.total * Decimal('0.5')
+ amount = payment.total * Decimal("0.5")
txn = payment.transactions.first()
txn.amount = amount
txn.currency = settings.DEFAULT_CURRENCY
@@ -328,8 +379,7 @@ def test_gateway_capture_partial_capture(
dummy_response.kind = TransactionKind.CAPTURE
dummy_response.amount = amount
mock_capture = Mock(return_value=dummy_response)
- mock_get_payment_gateway.return_value = (
- Mock(capture=mock_capture), gateway_params)
+ mock_get_payment_gateway.return_value = (Mock(capture=mock_capture), gateway_config)
gateway_capture(payment, amount)
@@ -340,12 +390,15 @@ def test_gateway_capture_partial_capture(
assert not mock_handle_fully_paid_order.called
-@patch('saleor.payment.gateways.dummy.SUPPORTS_AUTHORIZATION', new=True)
-@patch('saleor.payment.utils.handle_fully_paid_order')
-@patch('saleor.payment.utils.get_payment_gateway')
+@patch("saleor.payment.utils.handle_fully_paid_order")
+@patch("saleor.payment.utils.get_payment_gateway")
def test_gateway_capture_failed(
- mock_get_payment_gateway, mock_handle_fully_paid_order,
- payment_txn_preauth, gateway_params, dummy_response):
+ mock_get_payment_gateway,
+ mock_handle_fully_paid_order,
+ payment_txn_preauth,
+ gateway_config,
+ dummy_response,
+):
txn = payment_txn_preauth.transactions.first()
txn.is_success = False
@@ -355,8 +408,7 @@ def test_gateway_capture_failed(
dummy_response.is_success = False
dummy_response.kind = TransactionKind.CAPTURE
mock_capture = Mock(return_value=dummy_response)
- mock_get_payment_gateway.return_value = (
- Mock(capture=mock_capture), gateway_params)
+ mock_get_payment_gateway.return_value = (Mock(capture=mock_capture), gateway_config)
with pytest.raises(PaymentError) as exc:
gateway_capture(payment, amount)
assert exc.value.message == EXAMPLE_ERROR
@@ -366,62 +418,35 @@ def test_gateway_capture_failed(
assert not mock_handle_fully_paid_order.called
-@patch('saleor.payment.gateways.dummy.SUPPORTS_AUTHORIZATION', new=True)
def test_gateway_capture_errors(payment_txn_preauth):
with pytest.raises(PaymentError) as exc:
- gateway_capture(payment_txn_preauth, Decimal('0'))
- assert exc.value.message == 'Amount should be a positive number.'
+ gateway_capture(payment_txn_preauth, Decimal("0"))
+ assert exc.value.message == "Amount should be a positive number."
payment_txn_preauth.charge_status = ChargeStatus.FULLY_REFUNDED
with pytest.raises(PaymentError) as exc:
- gateway_capture(payment_txn_preauth, Decimal('10'))
- assert exc.value.message == 'This payment cannot be captured.'
+ gateway_capture(payment_txn_preauth, Decimal("10"))
+ assert exc.value.message == "This payment cannot be captured."
payment_txn_preauth.charge_status = ChargeStatus.NOT_CHARGED
with pytest.raises(PaymentError) as exc:
- gateway_capture(payment_txn_preauth, Decimal('1000000'))
- assert exc.value.message == (
- 'Unable to capture more than authorized amount.')
-
-
-@patch('saleor.payment.gateways.dummy.SUPPORTS_AUTHORIZATION', new=False)
-@patch('saleor.payment.utils.handle_fully_paid_order')
-@patch('saleor.payment.utils.get_payment_gateway')
-def test_gateway_can_capture_when_authorization_unsupported(
- mock_get_payment_gateway, mock_handle_fully_paid_order,
- payment_txn_preauth, gateway_params, transaction_token,
- dummy_response):
- payment_token = transaction_token
- payment = payment_txn_preauth
- assert not payment.captured_amount
- amount = payment.total
+ gateway_capture(payment_txn_preauth, Decimal("1000000"))
+ assert exc.value.message == ("Unable to charge more than un-captured amount.")
- dummy_response.kind = TransactionKind.CAPTURE
- mock_capture = Mock(return_value=dummy_response)
- mock_get_payment_gateway.return_value = (
- Mock(capture=mock_capture), gateway_params)
- payment_info = create_payment_information(payment, payment_token, amount)
- gateway_capture(payment, amount)
-
- mock_capture.assert_called_once_with(
- payment_information=payment_info, connection_params=gateway_params)
-
- payment.refresh_from_db()
- assert payment.charge_status == ChargeStatus.FULLY_CHARGED
- assert payment.captured_amount == payment.total
- mock_handle_fully_paid_order.assert_called_once_with(payment.order)
-
-
-@patch('saleor.payment.gateways.dummy.SUPPORTS_AUTHORIZATION', new=True)
-@patch('saleor.payment.utils.handle_fully_paid_order')
-@patch('saleor.payment.utils.get_payment_gateway')
+@patch("saleor.payment.utils.handle_fully_paid_order")
+@patch("saleor.payment.utils.get_payment_gateway")
def test_gateway_capture_partial_charge(
- mock_get_payment_gateway, mock_handle_fully_paid_order,
- payment_txn_preauth, gateway_params, transaction_token, settings,
- dummy_response):
+ mock_get_payment_gateway,
+ mock_handle_fully_paid_order,
+ payment_txn_preauth,
+ gateway_config,
+ transaction_token,
+ settings,
+ dummy_response,
+):
payment = payment_txn_preauth
- amount = payment.total * Decimal('0.5')
+ amount = payment.total * Decimal("0.5")
txn = payment.transactions.first()
txn.amount = amount
txn.currency = settings.DEFAULT_CURRENCY
@@ -429,8 +454,7 @@ def test_gateway_capture_partial_charge(
dummy_response.kind = TransactionKind.CAPTURE
dummy_response.amount = amount
mock_charge = Mock(return_value=dummy_response)
- mock_get_payment_gateway.return_value = (
- Mock(capture=mock_charge), gateway_params)
+ mock_get_payment_gateway.return_value = (Mock(capture=mock_charge), gateway_config)
gateway_capture(payment, amount)
@@ -441,13 +465,16 @@ def test_gateway_capture_partial_charge(
assert not mock_handle_fully_paid_order.called
-@patch('saleor.payment.gateways.dummy.SUPPORTS_AUTHORIZATION', new=True)
-@patch('saleor.payment.utils.handle_fully_paid_order')
-@patch('saleor.payment.utils.get_payment_gateway')
+@patch("saleor.payment.utils.handle_fully_paid_order")
+@patch("saleor.payment.utils.get_payment_gateway")
def test_gateway_charge_failed(
- mock_get_payment_gateway, mock_handle_fully_paid_order,
- payment_txn_preauth, gateway_params, transaction_token,
- dummy_response):
+ mock_get_payment_gateway,
+ mock_handle_fully_paid_order,
+ payment_txn_preauth,
+ gateway_config,
+ transaction_token,
+ dummy_response,
+):
txn = payment_txn_preauth.transactions.first()
txn.is_success = False
@@ -457,8 +484,7 @@ def test_gateway_charge_failed(
dummy_response.is_success = False
dummy_response.kind = TransactionKind.CAPTURE
mock_charge = Mock(return_value=dummy_response)
- mock_get_payment_gateway.return_value = (
- Mock(capture=mock_charge), gateway_params)
+ mock_get_payment_gateway.return_value = (Mock(capture=mock_charge), gateway_config)
with pytest.raises(PaymentError) as exc:
gateway_capture(payment, amount)
assert exc.value.message == EXAMPLE_ERROR
@@ -468,53 +494,53 @@ def test_gateway_charge_failed(
assert not mock_handle_fully_paid_order.called
-@patch('saleor.payment.gateways.dummy.SUPPORTS_AUTHORIZATION', new=False)
-def test_gateway_charge_errors(payment_dummy, transaction_token):
+def test_gateway_charge_errors(payment_dummy, transaction_token, settings):
payment = payment_dummy
+ settings.PAYMENT_GATEWAYS = {payment.gateway: {"config": {"auto_capture": False}}}
with pytest.raises(PaymentError) as exc:
- gateway_capture(payment, Decimal('0'))
- assert exc.value.message == 'Amount should be a positive number.'
+ gateway_capture(payment, Decimal("0"))
+ assert exc.value.message == "Amount should be a positive number."
payment.charge_status = ChargeStatus.FULLY_REFUNDED
with pytest.raises(PaymentError) as exc:
- gateway_capture(payment, Decimal('10'))
- assert exc.value.message == 'This payment cannot be captured.'
+ gateway_capture(payment, Decimal("10"))
+ assert exc.value.message == "This payment cannot be captured."
payment.charge_status = ChargeStatus.NOT_CHARGED
with pytest.raises(PaymentError) as exc:
- gateway_capture(payment, Decimal('1000000'))
- assert exc.value.message == (
- 'Unable to charge more than un-captured amount.')
+ gateway_capture(payment, Decimal("1000000"))
+ assert exc.value.message == ("Unable to charge more than un-captured amount.")
-@patch('saleor.payment.utils.get_payment_gateway')
+@patch("saleor.payment.utils.get_payment_gateway")
def test_gateway_void(
- mock_get_payment_gateway, payment_txn_preauth,
- gateway_params, dummy_response):
+ mock_get_payment_gateway, payment_txn_preauth, gateway_config, dummy_response
+):
txn = payment_txn_preauth.transactions.first()
payment = payment_txn_preauth
assert payment.is_active
dummy_response.kind = TransactionKind.VOID
mock_void = Mock(return_value=dummy_response)
- mock_get_payment_gateway.return_value = (Mock(void=mock_void), gateway_params)
+ mock_get_payment_gateway.return_value = (Mock(void=mock_void), gateway_config)
payment_info = create_payment_information(payment, txn.token)
gateway_void(payment)
mock_get_payment_gateway.assert_called_once_with(payment.gateway)
mock_void.assert_called_once_with(
- payment_information=payment_info, connection_params=gateway_params)
+ payment_information=payment_info, config=gateway_config
+ )
payment.refresh_from_db()
assert payment.is_active == False
-@patch('saleor.payment.utils.get_payment_gateway')
+@patch("saleor.payment.utils.get_payment_gateway")
def test_gateway_void_failed(
- mock_get_payment_gateway, payment_txn_preauth, gateway_params,
- dummy_response):
+ mock_get_payment_gateway, payment_txn_preauth, gateway_config, dummy_response
+):
txn = payment_txn_preauth.transactions.first()
txn.is_success = False
payment = payment_txn_preauth
@@ -522,7 +548,7 @@ def test_gateway_void_failed(
dummy_response.kind = TransactionKind.VOID
dummy_response.is_success = False
mock_void = Mock(return_value=dummy_response)
- mock_get_payment_gateway.return_value = (Mock(void=mock_void), gateway_params)
+ mock_get_payment_gateway.return_value = (Mock(void=mock_void), gateway_config)
with pytest.raises(PaymentError) as exc:
gateway_void(payment)
assert exc.value.message == EXAMPLE_ERROR
@@ -535,41 +561,44 @@ def test_gateway_void_errors(payment_dummy):
payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED
with pytest.raises(PaymentError) as exc:
gateway_void(payment_dummy)
- assert (
- exc.value.message == 'Only pre-authorized transactions can be voided.')
+ assert exc.value.message == "Only pre-authorized transactions can be voided."
-@patch('saleor.payment.utils.get_payment_gateway')
+@patch("saleor.payment.utils.get_payment_gateway")
def test_gateway_refund(
- mock_get_payment_gateway, payment_txn_captured, gateway_params,
- dummy_response):
+ mock_get_payment_gateway, payment_txn_captured, gateway_config, dummy_response
+):
txn = payment_txn_captured.transactions.first()
payment = payment_txn_captured
amount = payment.total
dummy_response.kind = TransactionKind.REFUND
mock_refund = Mock(return_value=dummy_response)
- mock_get_payment_gateway.return_value = (
- Mock(refund=mock_refund), gateway_params)
+ mock_get_payment_gateway.return_value = (Mock(refund=mock_refund), gateway_config)
payment_info = create_payment_information(payment, txn.token, amount)
gateway_refund(payment, amount)
mock_get_payment_gateway.assert_called_once_with(payment.gateway)
mock_refund.assert_called_once_with(
- payment_information=payment_info, connection_params=gateway_params)
+ payment_information=payment_info, config=gateway_config
+ )
payment.refresh_from_db()
assert payment.charge_status == ChargeStatus.FULLY_REFUNDED
assert not payment.captured_amount
-@patch('saleor.payment.utils.get_payment_gateway')
+@patch("saleor.payment.utils.get_payment_gateway")
def test_gateway_refund_partial_refund(
- mock_get_payment_gateway, payment_txn_captured, gateway_params,
- settings, dummy_response):
+ mock_get_payment_gateway,
+ payment_txn_captured,
+ gateway_config,
+ settings,
+ dummy_response,
+):
payment = payment_txn_captured
- amount = payment.total * Decimal('0.5')
+ amount = payment.total * Decimal("0.5")
txn = payment_txn_captured.transactions.first()
txn.amount = amount
txn.currency = settings.DEFAULT_CURRENCY
@@ -577,8 +606,7 @@ def test_gateway_refund_partial_refund(
dummy_response.kind = TransactionKind.REFUND
dummy_response.amount = amount
mock_refund = Mock(return_value=dummy_response)
- mock_get_payment_gateway.return_value = (
- Mock(refund=mock_refund), gateway_params)
+ mock_get_payment_gateway.return_value = (Mock(refund=mock_refund), gateway_config)
gateway_refund(payment, amount)
@@ -587,10 +615,14 @@ def test_gateway_refund_partial_refund(
assert payment.captured_amount == payment.total - amount
-@patch('saleor.payment.utils.get_payment_gateway')
+@patch("saleor.payment.utils.get_payment_gateway")
def test_gateway_refund_failed(
- mock_get_payment_gateway, payment_txn_captured, gateway_params,
- settings, dummy_response):
+ mock_get_payment_gateway,
+ payment_txn_captured,
+ gateway_config,
+ settings,
+ dummy_response,
+):
txn = payment_txn_captured.transactions.first()
payment = payment_txn_captured
captured_before = payment.captured_amount
@@ -599,11 +631,10 @@ def test_gateway_refund_failed(
dummy_response.kind = TransactionKind.REFUND
dummy_response.is_success = False
mock_refund = Mock(return_value=dummy_response)
- mock_get_payment_gateway.return_value = (
- Mock(refund=mock_refund), gateway_params)
+ mock_get_payment_gateway.return_value = (Mock(refund=mock_refund), gateway_config)
with pytest.raises(PaymentError) as exc:
- gateway_refund(payment, Decimal('10.00'))
+ gateway_refund(payment, Decimal("10.00"))
assert exc.value.message == EXAMPLE_ERROR
payment.refresh_from_db()
assert payment.captured_amount == captured_before
@@ -612,20 +643,20 @@ def test_gateway_refund_failed(
def test_gateway_refund_errors(payment_txn_captured):
payment = payment_txn_captured
with pytest.raises(PaymentError) as exc:
- gateway_refund(payment, Decimal('1000000'))
- assert exc.value.message == 'Cannot refund more than captured'
+ gateway_refund(payment, Decimal("1000000"))
+ assert exc.value.message == "Cannot refund more than captured"
with pytest.raises(PaymentError) as exc:
- gateway_refund(payment, Decimal('0'))
- assert exc.value.message == 'Amount should be a positive number.'
+ gateway_refund(payment, Decimal("0"))
+ assert exc.value.message == "Amount should be a positive number."
payment.charge_status = ChargeStatus.NOT_CHARGED
with pytest.raises(PaymentError) as exc:
- gateway_refund(payment, Decimal('1'))
- assert exc.value.message == 'This payment cannot be refunded.'
+ gateway_refund(payment, Decimal("1"))
+ assert exc.value.message == "This payment cannot be refunded."
[email protected]('gateway_name', dj_settings.PAYMENT_GATEWAYS.keys())
[email protected]("gateway_name", dj_settings.PAYMENT_GATEWAYS.keys())
def test_payment_gateway_templates_exists(gateway_name):
"""Test if for each payment gateway there's a corresponding
template for the old checkout.
@@ -634,16 +665,16 @@ def test_payment_gateway_templates_exists(gateway_name):
get_template(template)
[email protected]('gateway_name', dj_settings.PAYMENT_GATEWAYS.keys())
[email protected]("gateway_name", dj_settings.PAYMENT_GATEWAYS.keys())
def test_payment_gateway_form_exists(gateway_name, payment_dummy):
"""Test if for each payment gateway there's a corresponding
form for the old checkout.
An error will be raised if it's missing.
"""
- payment_gateway, gateway_params = get_payment_gateway(gateway_name)
+ payment_gateway, gateway_config = get_payment_gateway(gateway_name)
payment_info = create_payment_information(payment_dummy)
- payment_gateway.create_form(None, payment_info, gateway_params)
+ payment_gateway.create_form(None, payment_info, gateway_config.connection_params)
def test_clean_authorize():
@@ -658,30 +689,32 @@ def test_clean_authorize():
def test_clean_capture():
# Amount should be a positive number
payment = Mock()
- amount = Decimal('0.00')
+ amount = Decimal("0.00")
with pytest.raises(PaymentError):
clean_capture(payment, amount)
# Payment cannot be captured
payment = Mock(can_capture=Mock(return_value=False))
- amount = Decimal('1.00')
+ amount = Decimal("1.00")
with pytest.raises(PaymentError):
clean_capture(payment, amount)
# Amount is larger than payment's total
payment = Mock(
can_capture=Mock(return_value=True),
- total=Decimal('1.00'),
- captured_amount=Decimal('0.00'))
- amount = Decimal('2.00')
+ total=Decimal("1.00"),
+ captured_amount=Decimal("0.00"),
+ )
+ amount = Decimal("2.00")
with pytest.raises(PaymentError):
clean_capture(payment, amount)
- amount = Decimal('2.00')
+ amount = Decimal("2.00")
payment = Mock(
can_capture=Mock(return_value=True),
total=amount,
- captured_amount=Decimal('0.00'))
+ captured_amount=Decimal("0.00"),
+ )
clean_capture(payment, amount)
@@ -768,7 +801,8 @@ def test_payment_get_authorized_amount(payment_txn_preauth):
amount=payment.total,
kind=TransactionKind.CAPTURE,
gateway_response={},
- is_success=True)
+ is_success=True,
+ )
assert payment.get_authorized_amount().amount == Decimal(0)
payment.transactions.all().delete()
@@ -780,43 +814,46 @@ def test_validate_gateway_response(gateway_response):
def test_validate_gateway_response_incorrect_transaction_kind(gateway_response):
- gateway_response.kind = 'incorrect-kind'
+ gateway_response.kind = "incorrect-kind"
with pytest.raises(GatewayError) as e:
validate_gateway_response(gateway_response)
assert str(e.value) == (
- 'Gateway response kind must be one of {}'.format(
- sorted(ALLOWED_GATEWAY_KINDS)))
+ "Gateway response kind must be one of {}".format(sorted(ALLOWED_GATEWAY_KINDS))
+ )
def test_validate_gateway_response_not_json_serializable(gateway_response):
class CustomClass(object):
pass
+
gateway_response.raw_response = CustomClass()
with pytest.raises(GatewayError) as e:
validate_gateway_response(gateway_response)
- assert str(e.value) == 'Gateway response needs to be json serializable'
+ assert str(e.value) == "Gateway response needs to be json serializable"
-@patch('saleor.payment.utils.get_payment_gateway')
-def test_call_gateway_invalid_response(
- mock_get_payment_gateway, payment_dummy):
+@patch("saleor.payment.utils.get_payment_gateway")
+def test_call_gateway_invalid_response(mock_get_payment_gateway, payment_dummy):
mock_get_payment_gateway.return_value = (
- Mock(auth=Mock(return_value=('wrong', 'response'))), {})
+ Mock(auth=Mock(return_value=("wrong", "response"))),
+ {},
+ )
with pytest.raises(PaymentError) as e:
call_gateway(
operation_type=OperationType.AUTH,
- payment=payment_dummy, payment_token='token')
- assert str(e.value) == 'Gateway response validation failed'
+ payment=payment_dummy,
+ payment_token="token",
+ )
+ assert str(e.value) == "Gateway response validation failed"
-@patch('saleor.payment.utils.get_payment_gateway')
-def test_call_gateway_function_not_implemented(
- mock_get_payment_gateway, payment_dummy):
+@patch("saleor.payment.utils.get_payment_gateway")
+def test_call_gateway_function_not_implemented(mock_get_payment_gateway, payment_dummy):
class CustomClass:
pass
@@ -825,19 +862,23 @@ def test_call_gateway_function_not_implemented(
with pytest.raises(PaymentError) as e:
call_gateway(
operation_type=OperationType.AUTH,
- payment=payment_dummy, payment_token='token')
- assert str(e.value) == 'Gateway doesn\'t implement AUTH operation'
+ payment=payment_dummy,
+ payment_token="token",
+ )
+ assert str(e.value) == "Gateway doesn't implement AUTH operation"
-@patch('saleor.payment.utils.get_payment_gateway')
-def test_call_gateway_generic_error(
- mock_get_payment_gateway, payment_dummy):
+@patch("saleor.payment.utils.get_payment_gateway")
+def test_call_gateway_generic_error(mock_get_payment_gateway, payment_dummy):
mock_get_payment_gateway.return_value = (
- Mock(authorize=Mock(
- side_effect=Exception('something went wrong'))), {})
+ Mock(authorize=Mock(side_effect=Exception("something went wrong"))),
+ {},
+ )
with pytest.raises(PaymentError) as e:
call_gateway(
operation_type=OperationType.AUTH,
- payment=payment_dummy, payment_token='token')
- assert str(e.value) == 'Gateway encountered an error'
+ payment=payment_dummy,
+ payment_token="token",
+ )
+ assert str(e.value) == "Gateway encountered an error"