Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Improvements
Michał Jelonekd66465b1eb38
diff --git a/docs/guides/payments.rst b/docs/guides/payments.rstindex f7165e62ff..63df8d4ba3 100644--- a/docs/guides/payments.rst+++ b/docs/guides/payments.rst@@ -17,8 +17,8 @@ Your changes should live under theAfter completing those steps you will also need to integrate your paymentgateway into your SPA Storefront's workflow.-get_client_token(\*\*connection_params)-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^+get_client_token(connection_params)+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^A client token is a signed data blob that includes configuration andauthorization information required by the payment gateway.@@ -31,13 +31,13 @@ Example.. code-block:: python- def get_client_token(**connection_params: Dict) -> str:+ def get_client_token(connection_params: Dict) -> str:gateway = get_payment_gateway(**connection_params)client_token = gateway.client_token.generate()return client_token-authorize(payment_information, \*\*connection_params)-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^+authorize(payment_information, connection_params)+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^A process of reserving the amount of money against the customer's fundingsource. Money does not change hands until the authorization is captured.@@ -49,7 +49,7 @@ Exampledef authorize(payment_information: Dict,- **connection_params: Dict) -> Dict:+ connection_params: Dict) -> Dict:# Handle connecting to the gateway and sending the auth request hereresponse = gateway.authorize(token=payment_information['token'])@@ -66,8 +66,8 @@ Example'raw_response': get_payment_gateway_response(response),}-refund(payment_information, \*\*connection_params)-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^+refund(payment_information, connection_params)+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Full or partial return of captured funds to the customer.@@ -95,8 +95,8 @@ Example'raw_response': get_payment_gateway_response(response),}-capture(payment_information, \*\*connection_params)-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^+capture(payment_information, connection_params)+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^A transfer of the money that was reserved during the authorization stage.@@ -107,7 +107,7 @@ Exampledef capture(payment_information: Dict,- **connection_params: Dict) -> Dict:+ connection_params: Dict) -> Dict:# Handle connecting to the gateway and sending the capture request hereresponse = gateway.capture(token=payment_information['token'])@@ -124,8 +124,8 @@ Example'raw_response': get_payment_gateway_response(response),}-void(payment_information, \*\*connection_params)-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^+void(payment_information, connection_params)+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^A cancellation of a pending authorization or capture.@@ -136,7 +136,7 @@ Exampledef void(payment_information: Dict,- **connection_params: Dict) -> Dict:+ connection_params: Dict) -> Dict:# Handle connecting to the gateway and sending the void request hereresponse = gateway.void(token=payment_information['token'])@@ -153,8 +153,8 @@ Example'raw_response': get_payment_gateway_response(response),}-charge(payment_information, \*\*connection_params)-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^+charge(payment_information, connection_params)+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Authorization and capture in a single step.@@ -165,7 +165,7 @@ Exampledef charge(payment_information: Dict,- **connection_params: Dict) -> Dict:+ connection_params: Dict) -> Dict:# Handle connecting to the gateway and sending the charge request hereresponse = gateway.charge(@@ -184,8 +184,8 @@ Example'raw_response': get_payment_gateway_response(response),}-process_payment(payment_information, \*\*connection_params)-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^+process_payment(payment_information, connection_params)+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Used for the checkout process, it should perform all the necessarysteps to process a payment. It should use already defined functions,@@ -198,15 +198,15 @@ Exampledef process_payment(payment_information: Dict,- **connection_params: Dict) -> Dict:+ connection_params: Dict) -> Dict:# Authorize, update the token, then captureauthorize_response = authorize(- payment_information, **connection_params)+ payment_information, connection_params)payment_information['token'] = authorize_response['transaction_id']capture_response = capture(- payment_information, **connection_params)+ payment_information, connection_params)# Return a list of responses, each response must be json serializablereturn [authorize_response, capture_response]@@ -347,8 +347,8 @@ Exampledef get_payment_token(self):return self.cleaned_data['payment_method_nonce']-Implement get_form_class()-^^^^^^^^^^^^^^^^^^^^^^^^^^+Implement create_form(data, payment_information, connection_params)+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Should return the form that will be used for the checkout process.@@ -360,22 +360,22 @@ Example.. code-block:: python- def get_form_class():- return BraintreePaymentForm+ def create_form(data, payment_information, connection_params):+ return BraintreePaymentForm(+ data, payment_information, connection_params)-Implement get_template()-^^^^^^^^^^^^^^^^^^^^^^^^+Implement TEMPLATE_PATH+^^^^^^^^^^^^^^^^^^^^^^^-Should return a path to a template that will be rendered for the checkout.+Should specify a path to a template that will be rendered for the checkout.Example""""""".. code-block:: python- def get_template():- return 'order/payment/braintree.html'+ TEMPLATE_PATH = 'order/payment/braintree.html'Add template^^^^^^^^^^^^diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.pyindex 43b85c099a..82aa9d0e3f 100644--- a/saleor/graphql/order/mutations/orders.py+++ b/saleor/graphql/order/mutations/orders.py@@ -44,13 +44,6 @@ def clean_order_update_shipping(order, method, errors):return errors-def try_payment_action(action, payment, amount, errors):- try:- action(payment, amount)- except (PaymentError, ValueError) as e:- errors.append(Error(field='payment', message=str(e)))--def clean_order_cancel(order, errors):if order and not order.can_cancel():errors.append(@@ -322,7 +315,12 @@ class OrderCapture(BaseMutation):# FIXME adjust to multiple payments in the futurepayment = order.get_last_payment()clean_order_capture(payment, amount, errors)- try_payment_action(gateway_capture, payment, amount, errors)++ try:+ gateway_capture(payment, amount)+ except PaymentError as e:+ errors.append(Error(field='payment', message=str(e)))+if errors:return OrderCapture(errors=errors)@@ -384,7 +382,11 @@ class OrderRefund(BaseMutation):if order:payment = order.get_last_payment()clean_refund_payment(payment, amount, errors)- try_payment_action(gateway_refund, payment, amount, errors)+ try:+ gateway_refund(payment, amount)+ except PaymentError as e:+ errors.append(Error(field='payment', message=str(e)))+if errors:return OrderRefund(errors=errors)diff --git a/saleor/order/views.py b/saleor/order/views.pyindex 99172986e0..c11ac8037f 100644--- a/saleor/order/views.py+++ b/saleor/order/views.py@@ -108,12 +108,13 @@ def start_payment(request, order, gateway):or payment.charge_status == ChargeStatus.FULLY_REFUNDED):return redirect(order.get_absolute_url())- payment_gateway, gateway_params = get_payment_gateway(payment.gateway)- client_token = payment_gateway.get_client_token(**gateway_params)+ payment_gateway, connection_params = get_payment_gateway(+ payment.gateway)+ client_token = payment_gateway.get_client_token(connection_params)payment_info = create_payment_information(payment)- form = payment_gateway.get_form_class()(+ form = payment_gateway.create_form(data=request.POST or None, payment_information=payment_info,- gateway_params=gateway_params)+ connection_params=connection_params)if form.is_valid():try:gateway_process_payment(@@ -126,7 +127,7 @@ def start_payment(request, order, gateway):ctx = {'form': form, 'payment': payment,'client_token': client_token, 'order': order}- return TemplateResponse(request, payment_gateway.get_template(), ctx)+ return TemplateResponse(request, payment_gateway.TEMPLATE_PATH, ctx)@check_order_statusdiff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.pyindex 01b4333f93..91d10f0678 100644--- a/saleor/payment/__init__.py+++ b/saleor/payment/__init__.py@@ -1,7 +1,8 @@import importlibfrom enum import Enum-from django.core.exceptions import ImproperlyConfigured+from django.conf import settings+from django.core.exceptions import ImproperlyConfiguredfrom django.utils.translation import pgettext_lazy@@ -12,7 +13,7 @@ class PaymentError(Exception):self.message = message-class GatewayError(Exception):+class GatewayError(IOError):pass@@ -23,6 +24,15 @@ class CustomPaymentChoices:(MANUAL, pgettext_lazy('Custom payment choice type', 'Manual'))]+class OperationType(Enum):+ PROCESS_PAYMENT = 'process_payment'+ AUTH = 'authorize'+ CAPTURE = 'capture'+ CHARGE = 'charge'+ VOID = 'void'+ REFUND = 'refund'++class TransactionError(Enum):INCORRECT_NUMBER = 'incorrect_number'INVALID_NUMBER = 'invalid_number'diff --git a/saleor/payment/gateways/braintree/__init__.py b/saleor/payment/gateways/braintree/__init__.pyindex e83cf9f26a..cb8febc8ef 100644--- a/saleor/payment/gateways/braintree/__init__.py+++ b/saleor/payment/gateways/braintree/__init__.py@@ -8,11 +8,13 @@ from django.core.exceptions import ImproperlyConfiguredfrom django.utils.translation import pgettext_lazyfrom prices import Money+from .errors import DEFAULT_ERROR_MESSAGE, BraintreeExceptionfrom .forms import BraintreePaymentForm-from .errors import BraintreeExceptionlogger = logging.getLogger(__name__)+TEMPLATE_PATH = 'order/payment/braintree.html'+# FIXME: Move to SiteSettings# If this option is checked, then one needs to authorize the amount paid@@ -93,12 +95,9 @@ def extract_gateway_response(braintree_result) -> Dict:'errors': errors}-def get_template():- return 'order/payment/braintree.html'---def get_form_class():- return BraintreePaymentForm+def create_form(data, payment_information, connection_params):+ return BraintreePaymentForm(+ data=data, payment_information=payment_information)def get_braintree_gateway(sandbox_mode, merchant_id, public_key, private_key):@@ -117,13 +116,13 @@ def get_braintree_gateway(sandbox_mode, merchant_id, public_key, private_key):return gateway-def get_client_token(**connection_params: Dict) -> str:+def get_client_token(connection_params: Dict) -> str:gateway = get_braintree_gateway(**connection_params)client_token = gateway.client_token.generate()return client_token-def authorize(payment_information: Dict, **connection_params: Dict) -> Dict:+def authorize(payment_information: Dict, connection_params: Dict) -> Dict:gateway = get_braintree_gateway(**connection_params)try:@@ -136,7 +135,7 @@ def authorize(payment_information: Dict, **connection_params: Dict) -> Dict:'required': THREE_D_SECURE_REQUIRED}},**get_customer_data(payment_information)})except braintree_sdk.exceptions.NotFoundError:- raise BraintreeException+ raise BraintreeException(DEFAULT_ERROR_MESSAGE)gateway_response = extract_gateway_response(result)error = get_error_for_client(gateway_response['errors'])@@ -154,7 +153,7 @@ def authorize(payment_information: Dict, **connection_params: Dict) -> Dict:'raw_response': gateway_response}-def capture(payment_information: Dict, **connection_params: Dict) -> Dict:+def capture(payment_information: Dict, connection_params: Dict) -> Dict:gateway = get_braintree_gateway(**connection_params)try:@@ -162,7 +161,7 @@ def capture(payment_information: Dict, **connection_params: Dict) -> Dict:transaction_id=payment_information['token'],amount=str(payment_information['amount']))except braintree_sdk.exceptions.NotFoundError:- raise BraintreeException+ raise BraintreeException(DEFAULT_ERROR_MESSAGE)gateway_response = extract_gateway_response(result)error = get_error_for_client(gateway_response['errors'])@@ -180,14 +179,14 @@ def capture(payment_information: Dict, **connection_params: Dict) -> Dict:'raw_response': gateway_response}-def void(payment_information: Dict, **connection_params: Dict) -> Dict:+def void(payment_information: Dict, connection_params: Dict) -> Dict:gateway = get_braintree_gateway(**connection_params)try:result = gateway.transaction.void(transaction_id=payment_information['token'])except braintree_sdk.exceptions.NotFoundError:- raise BraintreeException+ raise BraintreeException(DEFAULT_ERROR_MESSAGE)gateway_response = extract_gateway_response(result)error = get_error_for_client(gateway_response['errors'])@@ -205,7 +204,7 @@ def void(payment_information: Dict, **connection_params: Dict) -> Dict:'raw_response': gateway_response}-def refund(payment_information: Dict, **connection_params: Dict) -> Dict:+def refund(payment_information: Dict, connection_params: Dict) -> Dict:gateway = get_braintree_gateway(**connection_params)try:@@ -213,7 +212,7 @@ def refund(payment_information: Dict, **connection_params: Dict) -> Dict:transaction_id=payment_information['token'],amount_or_options=str(payment_information['amount']))except braintree_sdk.exceptions.NotFoundError:- raise BraintreeException+ raise BraintreeException(DEFAULT_ERROR_MESSAGE)gateway_response = extract_gateway_response(result)error = get_error_for_client(gateway_response['errors'])@@ -232,9 +231,9 @@ def refund(payment_information: Dict, **connection_params: Dict) -> Dict:def process_payment(- payment_information: Dict, **connection_params: Dict) -> Dict:- auth_resp = authorize(payment_information, **connection_params)+ payment_information: Dict, connection_params: Dict) -> Dict:+ auth_resp = authorize(payment_information, connection_params)if auth_resp['is_success']:payment_information['token'] = auth_resp['transaction_id']- return [auth_resp, capture(payment_information, **connection_params)]- return [auth_resp, void(payment_information, **connection_params)]+ return [auth_resp, capture(payment_information, connection_params)]+ return [auth_resp, void(payment_information, connection_params)]diff --git a/saleor/payment/gateways/braintree/errors.py b/saleor/payment/gateways/braintree/errors.pyindex 32e9932c56..2842a66ae8 100644--- a/saleor/payment/gateways/braintree/errors.py+++ b/saleor/payment/gateways/braintree/errors.py@@ -118,9 +118,4 @@ DEFAULT_ERROR_MESSAGE = (class BraintreeException(Exception):-- def __init__(self, *args, **kwargs):- if args or kwargs:- super().__init__(*args, **kwargs)- else:- super().__init__(DEFAULT_ERROR_MESSAGE)+ passdiff --git a/saleor/payment/gateways/braintree/forms.py b/saleor/payment/gateways/braintree/forms.pyindex 9749a24b11..52d6a45631 100644--- a/saleor/payment/gateways/braintree/forms.py+++ b/saleor/payment/gateways/braintree/forms.py@@ -13,9 +13,8 @@ class BraintreePaymentForm(forms.Form):# responsepayment_method_nonce = forms.CharField()- def __init__(self, payment_information, gateway_params, *args, **kwargs):+ def __init__(self, payment_information, *args, **kwargs):super().__init__(*args, **kwargs)- self.gateway_params = gateway_paramsself.payment_information = payment_informationself.fields['amount'].initial = payment_information['amount']diff --git a/saleor/payment/gateways/dummy/__init__.py b/saleor/payment/gateways/dummy/__init__.pyindex 552aef28ac..03412044aa 100644--- a/saleor/payment/gateways/dummy/__init__.py+++ b/saleor/payment/gateways/dummy/__init__.py@@ -7,6 +7,8 @@ from prices import Moneyfrom .forms import DummyPaymentForm+TEMPLATE_PATH = 'order/payment/dummy.html'+class TransactionKind:AUTH = 'auth'@@ -20,27 +22,15 @@ def dummy_success():return True-def get_client_token(**connection_params):+def get_client_token(**_):return str(uuid.uuid4())-def get_template():- return 'order/payment/dummy.html'---def get_form_class():- return DummyPaymentForm-+def create_form(data, payment_information, connection_params):+ return DummyPaymentForm(data=data)-def process_payment(payment_information: Dict, **connection_params) -> Dict:- """Process the whole payment, by calling authorize and capture."""- auth_resp = authorize(payment_information, **connection_params)- if not auth_resp['is_success']:- return auth_resp- return [auth_resp, capture(payment_information, **connection_params)]--def authorize(payment_information: Dict, **connection_params) -> Dict:+def authorize(payment_information: Dict, connection_params) -> Dict:success = dummy_success()error = Noneif not success:@@ -54,7 +44,7 @@ def authorize(payment_information: Dict, **connection_params) -> Dict:'error': error}-def void(payment_information: Dict, **connection_params) -> Dict:+def void(payment_information: Dict, connection_params) -> Dict:error = Nonesuccess = dummy_success()if not success:@@ -68,7 +58,7 @@ def void(payment_information: Dict, **connection_params) -> Dict:'error': error}-def capture(payment_information: Dict, **connection_params: Dict) -> Dict:+def capture(payment_information: Dict, connection_params: Dict) -> Dict:error = Nonesuccess = dummy_success()if not success:@@ -82,7 +72,7 @@ def capture(payment_information: Dict, **connection_params: Dict) -> Dict:'error': error}-def refund(payment_information: Dict, **connection_params: Dict):+def refund(payment_information: Dict, connection_params: Dict):error = Nonesuccess = dummy_success()if not success:@@ -96,9 +86,17 @@ def refund(payment_information: Dict, **connection_params: Dict):'error': error}-def charge(payment_information: Dict, **connection_params):+def charge(payment_information: Dict, connection_params):"""Performs Authorize and Capture transactions in a single run."""- auth_resp = authorize(payment_information, **connection_params)+ auth_resp = authorize(payment_information, connection_params)+ if not auth_resp['is_success']:+ return auth_resp+ return [auth_resp, capture(payment_information, connection_params)]+++def process_payment(payment_information: Dict, connection_params) -> Dict:+ """Process the whole payment, by calling authorize and capture."""+ auth_resp = authorize(payment_information, connection_params)if not auth_resp['is_success']:return auth_resp- return [auth_resp, capture(payment_information, **connection_params)]+ return [auth_resp, capture(payment_information, connection_params)]diff --git a/saleor/payment/gateways/dummy/forms.py b/saleor/payment/gateways/dummy/forms.pyindex ac4658a6ff..8a7add4ed3 100644--- a/saleor/payment/gateways/dummy/forms.py+++ b/saleor/payment/gateways/dummy/forms.py@@ -12,10 +12,5 @@ class DummyPaymentForm(forms.Form):choices=ChargeStatus.CHOICES, initial=ChargeStatus.NOT_CHARGED,widget=forms.RadioSelect)- def __init__(self, payment_information, gateway_params, *args, **kwargs):- self.payment_information = payment_information- self.gateway_params = gateway_params- super().__init__(*args, **kwargs)-def get_payment_token(self):return str(uuid.uuid4())diff --git a/saleor/payment/gateways/razorpay/__init__.py b/saleor/payment/gateways/razorpay/__init__.pyindex db9a9ed50e..da5f9929db 100644--- a/saleor/payment/gateways/razorpay/__init__.py+++ b/saleor/payment/gateways/razorpay/__init__.py@@ -10,6 +10,8 @@ from . import errorsfrom .forms import RazorPaymentFormfrom .utils import get_amount_for_razorpay, get_error_response+TEMPLATE_PATH = 'order/payment/razorpay.html'+# The list of currencies supported by razorpaySUPPORTED_CURRENCIES = 'INR',@@ -34,11 +36,7 @@ class TransactionKind:def _generate_response(- payment_information: Dict,- kind: str,- *,- is_success=True,- **data) -> Dict:+ payment_information: Dict, kind: str, data: Dict) -> Dict:"""Generate Saleor transaction information fromRazorpay's success payload or from passed data."""return {@@ -47,7 +45,7 @@ def _generate_response('amount': data.get('amount', payment_information['amount']),'currency': data.get('currency', payment_information['currency']),'error': data.get('error', None),- 'is_success': is_success,+ 'is_success': data.get('is_success', True),'raw_response': data}@@ -74,13 +72,12 @@ def clean_razorpay_response(response: dict):response['amount'] = Decimal(response['amount']) / 100-def get_template():- return 'order/payment/razorpay.html'---def get_form_class():+def create_form(data, payment_information, connection_params):"""Return the associated razorpay payment form."""- return RazorPaymentForm+ return RazorPaymentForm(+ data=data, payment_information=payment_information,+ connection_params=connection_params,+ )def get_client(public_key: str, secret_key: str, **_):@@ -94,7 +91,7 @@ def get_client_token(**_):return str(uuid.uuid4())-def charge(payment_information: Dict, **connection_params: Dict) -> Dict:+def charge(payment_information: Dict, connection_params: Dict) -> Dict:"""Charge a authorized payment using the razorpay client.But it first check if the given payment instance is supported@@ -125,10 +122,10 @@ def charge(payment_information: Dict, **connection_params: Dict) -> Dict:return _generate_response(payment_information=payment_information,- kind=TransactionKind.CHARGE, **response)+ kind=TransactionKind.CHARGE, data=response)-def refund(payment_information: Dict, **connection_params) -> Dict:+def refund(payment_information: Dict, connection_params) -> Dict:"""Refund a payment using the razorpay client.But it first check if the given payment instance is supported@@ -158,8 +155,10 @@ def refund(payment_information: Dict, **connection_params) -> Dict:return _generate_response(payment_information=payment_information,- kind=TransactionKind.REFUND, **response)+ kind=TransactionKind.REFUND, data=response)-def process_payment(payment_information: Dict, **connection_params) -> Dict:- return charge(payment_information=payment_information, **connection_params)+def process_payment(payment_information: Dict, connection_params) -> Dict:+ return charge(+ payment_information=payment_information,+ connection_params=connection_params)diff --git a/saleor/payment/gateways/razorpay/forms.py b/saleor/payment/gateways/razorpay/forms.pyindex 21f45ee065..b6665f2612 100644--- a/saleor/payment/gateways/razorpay/forms.py+++ b/saleor/payment/gateways/razorpay/forms.py@@ -60,10 +60,11 @@ class RazorPaymentForm(forms.Form):razorpay_payment_id = forms.CharField(required=True, widget=forms.HiddenInput)- def __init__(self, payment_information, gateway_params, *args, **kwargs):+ def __init__(+ self, payment_information, connection_params, *args, **kwargs):super().__init__(*args, **kwargs)widget = RazorPayCheckoutWidget(- payment_information=payment_information, **gateway_params)+ payment_information=payment_information, **connection_params)self.fields['razorpay'] = forms.CharField(widget=widget, required=False)diff --git a/saleor/payment/gateways/stripe/__init__.py b/saleor/payment/gateways/stripe/__init__.pyindex f31a4a4f82..ad40cf9762 100644--- a/saleor/payment/gateways/stripe/__init__.py+++ b/saleor/payment/gateways/stripe/__init__.py@@ -10,6 +10,8 @@ from .utils import (get_currency_from_stripe, get_payment_billing_fullname,shipping_to_stripe_dict)+TEMPLATE_PATH = 'order/payment/stripe.html'+class TransactionKind:AUTH = 'auth'@@ -26,7 +28,7 @@ def get_client_token(**_):return-def authorize(payment_information, **connection_params):+def authorize(payment_information, connection_params):client, error = _get_client(**connection_params), Nonetry:@@ -44,7 +46,7 @@ def authorize(payment_information, **connection_params):kind=TransactionKind.AUTH, response=response, error=error)-def capture(payment_information, **connection_params):+def capture(payment_information, connection_params):client, error = _get_client(**connection_params), None# Get amount from argument or payment, and convert to stripe's amount@@ -66,7 +68,7 @@ def capture(payment_information, **connection_params):kind=TransactionKind.CAPTURE, response=response, error=error)-def charge(payment_information, **connection_params):+def charge(payment_information, connection_params):client, error = _get_client(**connection_params), Nonetry:@@ -84,7 +86,7 @@ def charge(payment_information, **connection_params):kind=TransactionKind.CHARGE, response=response, error=error)-def refund(payment_information, **connection_params):+def refund(payment_information, connection_params):client, error = _get_client(**connection_params), None# Get amount from payment, and convert to stripe's amount@@ -107,7 +109,7 @@ def refund(payment_information, **connection_params):kind=TransactionKind.REFUND, response=response, error=error)-def void(payment_information, **connection_params):+def void(payment_information, connection_params):client, error = _get_client(**connection_params), Nonetry:@@ -124,16 +126,14 @@ def void(payment_information, **connection_params):kind=TransactionKind.VOID, response=response, error=error)-def process_payment(payment_information, **connection_params):- return charge(payment_information, **connection_params)---def get_template():- return 'order/payment/stripe.html'+def process_payment(payment_information, connection_params):+ return charge(payment_information, connection_params)-def get_form_class():- return StripePaymentModalForm+def create_form(data, payment_information, connection_params):+ return StripePaymentModalForm(+ data=data, payment_information=payment_information,+ gateway_params=connection_params)def _get_client(**connection_params):diff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex 635be684b5..d1c750c94b 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -11,7 +11,7 @@ from django.forms.models import model_to_dictfrom prices import Moneyfrom . import (- ChargeStatus, GatewayError, PaymentError, TransactionKind,+ ChargeStatus, GatewayError, OperationType, PaymentError, TransactionKind,get_payment_gateway)from ..core import analyticsfrom ..order import OrderEvents, OrderEventsEmails@@ -26,6 +26,22 @@ REQUIRED_GATEWAY_KEYS = {ALLOWED_GATEWAY_KINDS = {choices[0] for choices in TransactionKind.CHOICES}+def get_gateway_operation_func(gateway, operation_type):+ """Return gateway method based on the operation type to be performed."""+ if operation_type == OperationType.PROCESS_PAYMENT:+ return gateway.process_payment+ if operation_type == OperationType.AUTH:+ return gateway.authorize+ if operation_type == OperationType.CAPTURE:+ return gateway.capture+ if operation_type == OperationType.CHARGE:+ return gateway.charge+ if operation_type == OperationType.VOID:+ return gateway.void+ if operation_type == OperationType.REFUND:+ return gateway.refund++def get_billing_data(order):"""Extracts order's billing address into payment-friendly billing data."""data = {}@@ -110,7 +126,7 @@ def create_transaction(# Default values for token, amount, currency are only used in cases where# response from gateway was invalid or an exception occured- txn, _ = Transaction.objects.get_or_create(+ txn = Transaction.objects.create(payment=payment,kind=gateway_response.get('kind', kind),token=gateway_response.get(@@ -161,11 +177,12 @@ def clean_authorize(payment: Payment):def call_gateway(- func_name, transaction_kind, payment, payment_token, **extra_params):+ operation_type, transaction_kind,+ payment, payment_token, **extra_params):"""Helper that calls the passed gateway function and handles exceptions.Additionally does validation of the returned gateway response."""- gateway, gateway_params = get_payment_gateway(payment.gateway)+ gateway, connection_params = get_payment_gateway(payment.gateway)gateway_response = Noneerror_msg = None@@ -174,12 +191,18 @@ def call_gateway()try:- gateway_response = getattr(gateway, func_name)(- payment_information=payment_information, **gateway_params)- validate_gateway_response(gateway_response)+ func = get_gateway_operation_func(gateway, operation_type)except AttributeError:- error_msg = 'Gateway doesn\'t implement {}'.format(func_name)+ error_msg = 'Gateway doesn\'t implement {} operation'.format(+ operation_type.name)logger.exception(error_msg)+ raise PaymentError(error_msg)++ try:+ gateway_response = func(+ payment_information=payment_information,+ connection_params=connection_params)+ validate_gateway_response(gateway_response)except GatewayError:error_msg = 'Gateway response validation failed'logger.exception(error_msg)@@ -256,16 +279,16 @@ def gateway_process_payment(payment: Payment, payment_token: str) -> Transaction:"""Performs whole payment process on a gateway."""transaction = call_gateway(- func_name='process_payment', transaction_kind=TransactionKind.CAPTURE,+ operation_type=OperationType.PROCESS_PAYMENT,+ transaction_kind=TransactionKind.CAPTURE,payment=payment, payment_token=payment_token, amount=payment.total)- if transaction.is_success:- payment.charge_status = ChargeStatus.CHARGED- payment.captured_amount += transaction.amount- payment.save(update_fields=['charge_status', 'captured_amount'])- order = payment.order- if order and order.is_fully_paid():- handle_fully_paid_order(order)+ payment.charge_status = ChargeStatus.CHARGED+ payment.captured_amount += transaction.amount+ payment.save(update_fields=['charge_status', 'captured_amount'])+ order = payment.order+ if order and order.is_fully_paid():+ handle_fully_paid_order(order)return transaction@@ -288,16 +311,16 @@ def gateway_charge(clean_charge(payment, amount)transaction = call_gateway(- func_name='charge', transaction_kind=TransactionKind.CHARGE,+ operation_type=OperationType.CHARGE,+ transaction_kind=TransactionKind.CHARGE,payment=payment, payment_token=payment_token, amount=amount)- if transaction.is_success:- payment.charge_status = ChargeStatus.CHARGED- payment.captured_amount += transaction.amount- payment.save(update_fields=['charge_status', 'captured_amount'])- order = payment.order- if order and order.is_fully_paid():- handle_fully_paid_order(order)+ payment.charge_status = ChargeStatus.CHARGED+ payment.captured_amount += transaction.amount+ payment.save(update_fields=['charge_status', 'captured_amount'])+ order = payment.order+ if order and order.is_fully_paid():+ handle_fully_paid_order(order)return transaction@@ -312,7 +335,8 @@ def gateway_authorize(payment: Payment, payment_token: str) -> Transaction:clean_authorize(payment)return call_gateway(- func_name='authorize', transaction_kind=TransactionKind.AUTH,+ operation_type=OperationType.AUTH,+ transaction_kind=TransactionKind.AUTH,payment=payment, payment_token=payment_token)@@ -330,16 +354,16 @@ def gateway_capture(payment: Payment, amount: Decimal = None) -> Transaction:payment_token = auth_transaction.tokentransaction = call_gateway(- func_name='capture', transaction_kind=TransactionKind.CAPTURE,+ operation_type=OperationType.CAPTURE,+ transaction_kind=TransactionKind.CAPTURE,payment=payment, payment_token=payment_token, amount=amount)- if transaction.is_success:- payment.charge_status = ChargeStatus.CHARGED- payment.captured_amount += transaction.amount- payment.save(update_fields=['charge_status', 'captured_amount'])- order = payment.order- if order and order.is_fully_paid():- handle_fully_paid_order(order)+ payment.charge_status = ChargeStatus.CHARGED+ payment.captured_amount += transaction.amount+ payment.save(update_fields=['charge_status', 'captured_amount'])+ order = payment.order+ if order and order.is_fully_paid():+ handle_fully_paid_order(order)return transaction@@ -356,12 +380,12 @@ def gateway_void(payment) -> Transaction:payment_token = auth_transaction.tokentransaction = call_gateway(- func_name='void', transaction_kind=TransactionKind.VOID,+ operation_type=OperationType.VOID,+ transaction_kind=TransactionKind.VOID,payment=payment, payment_token=payment_token)- if transaction.is_success:- payment.is_active = False- payment.save(update_fields=['is_active'])+ payment.is_active = False+ payment.save(update_fields=['is_active'])return transaction@@ -391,16 +415,16 @@ def gateway_refund(payment, amount: Decimal = None) -> Transaction:payment_token = transaction.tokentransaction = call_gateway(- func_name='refund', transaction_kind=TransactionKind.REFUND,+ operation_type=OperationType.REFUND,+ transaction_kind=TransactionKind.REFUND,payment=payment, payment_token=payment_token, amount=amount)- if transaction.is_success:- changed_fields = ['captured_amount']- payment.captured_amount -= transaction.amount- if not payment.captured_amount:- payment.charge_status = ChargeStatus.FULLY_REFUNDED- payment.is_active = False- changed_fields += ['charge_status', 'is_active']- payment.save(update_fields=changed_fields)+ changed_fields = ['captured_amount']+ payment.captured_amount -= transaction.amount+ if not payment.captured_amount:+ payment.charge_status = ChargeStatus.FULLY_REFUNDED+ payment.is_active = False+ changed_fields += ['charge_status', 'is_active']+ payment.save(update_fields=changed_fields)return transactiondiff --git a/tests/gateway/test_braintree.py b/tests/gateway/test_braintree.pyindex 732334dedb..aa0ac26588 100644--- a/tests/gateway/test_braintree.py+++ b/tests/gateway/test_braintree.py@@ -14,8 +14,9 @@ from prices import Moneyfrom saleor.payment import get_payment_gatewayfrom saleor.payment.gateways.braintree import (CONFIRM_MANUALLY, THREE_D_SECURE_REQUIRED, TransactionKind, authorize,- capture, extract_gateway_response, get_braintree_gateway, get_client_token,- get_customer_data, get_error_for_client, process_payment, refund, void)+ 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)from saleor.payment.gateways.braintree.forms import BraintreePaymentForm@@ -185,7 +186,7 @@ def test_get_client_token(mock_gateway, gateway_config):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)+ result = get_client_token(gateway_config)mock_gateway.assert_called_once_with(**gateway_config)mock_generate.assert_called_once_with()assert result == client_token@@ -194,14 +195,14 @@ def test_get_client_token(mock_gateway, gateway_config):@pytest.mark.integration@patch('saleor.payment.gateways.braintree.get_braintree_gateway')def test_process_payment_error_response(- mock_gateway, payment_dummy, braintree_error_response):+ mock_gateway, payment_dummy, braintree_error_response, gateway_config):payment = payment_dummypayment_token = 'payment-token'mock_response = Mock(return_value=braintree_error_response)mock_gateway.return_value = Mock(transaction=Mock(sale=mock_response))payment_info = create_payment_information(payment, payment_token)- response = process_payment(payment_info)+ response = process_payment(payment_info, gateway_config)assert isinstance(response, list)auth_resp, void_resp = response@@ -213,14 +214,15 @@ def test_process_payment_error_response(@pytest.mark.integration@patch('saleor.payment.gateways.braintree.get_braintree_gateway')def test_process_payment(- mock_gateway, payment_dummy, braintree_success_response):+ mock_gateway, payment_dummy, braintree_success_response,+ gateway_config):payment = payment_dummypayment_token = 'payment-token'mock_response = Mock(return_value=braintree_success_response)mock_gateway.return_value = Mock(transaction=Mock(sale=mock_response))payment_info = create_payment_information(payment, payment_token)- response = process_payment(payment_info)+ response = process_payment(payment_info, gateway_config)assert isinstance(response, list)auth_resp, capture_resp = response@@ -231,14 +233,14 @@ def test_process_payment(@pytest.mark.integration@patch('saleor.payment.gateways.braintree.get_braintree_gateway')def test_authorize_error_response(- mock_gateway, payment_dummy, braintree_error_response):+ mock_gateway, payment_dummy, braintree_error_response, gateway_config):payment = payment_dummypayment_token = 'payment-token'mock_response = Mock(return_value=braintree_error_response)mock_gateway.return_value = Mock(transaction=Mock(sale=mock_response))payment_info = create_payment_information(payment, payment_token)- response = authorize(payment_info)+ response = authorize(payment_info, gateway_config)assert response['raw_response'] == extract_gateway_response(braintree_error_response)assert not response['is_success']@@ -248,7 +250,8 @@ def test_authorize_error_response(@pytest.mark.integration@patch('saleor.payment.gateways.braintree.get_braintree_gateway')def test_authorize_incorrect_token(- mock_gateway, payment_dummy, braintree_not_found_error):+ mock_gateway, payment_dummy, braintree_not_found_error,+ gateway_config):payment = payment_dummypayment_token = 'payment-token'mock_response = Mock(side_effect=braintree_not_found_error)@@ -256,20 +259,21 @@ def test_authorize_incorrect_token(payment_info = create_payment_information(payment, payment_token)with pytest.raises(BraintreeException) as e:- authorize(payment_info)+ authorize(payment_info, gateway_config)assert str(e.value) == DEFAULT_ERROR_MESSAGE@pytest.mark.integration@patch('saleor.payment.gateways.braintree.get_braintree_gateway')def test_authorize(- mock_gateway, payment_dummy, braintree_success_response):+ mock_gateway, payment_dummy, braintree_success_response,+ gateway_config):payment = payment_dummymock_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')- response = authorize(payment_info)+ response = authorize(payment_info, gateway_config)assert not response['error']assert response['kind'] == TransactionKind.AUTH@@ -292,14 +296,14 @@ def test_authorize(@patch('saleor.payment.gateways.braintree.get_braintree_gateway')def test_refund(mock_gateway, payment_txn_captured, braintree_success_response,- settings):+ settings, gateway_config):payment = payment_txn_capturedamount = 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)- response = refund(payment_info)+ response = refund(payment_info, gateway_config)assert not response['error']assert response['kind'] == TransactionKind.REFUND@@ -314,7 +318,8 @@ def test_refund(@pytest.mark.integration@patch('saleor.payment.gateways.braintree.get_braintree_gateway')def test_refund_incorrect_token(- mock_gateway, payment_txn_captured, braintree_not_found_error):+ mock_gateway, payment_txn_captured, braintree_not_found_error,+ gateway_config):payment = payment_txn_capturedamount = Decimal('10.00')@@ -323,21 +328,22 @@ def test_refund_incorrect_token(payment_info = create_payment_information(payment, 'token', amount)with pytest.raises(BraintreeException) as e:- refund(payment_info)+ refund(payment_info, gateway_config)assert str(e.value) == DEFAULT_ERROR_MESSAGE@pytest.mark.integration@patch('saleor.payment.gateways.braintree.get_braintree_gateway')def test_refund_error_response(- mock_gateway, payment_txn_captured, braintree_error_response):+ mock_gateway, payment_txn_captured, braintree_error_response,+ gateway_config):payment = payment_txn_capturedamount = 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)- response = refund(payment_info)+ response = refund(payment_info, gateway_config)assert response['raw_response'] == extract_gateway_response(braintree_error_response)@@ -349,7 +355,7 @@ def test_refund_error_response(@patch('saleor.payment.gateways.braintree.get_braintree_gateway')def test_capture(mock_gateway, payment_txn_preauth, braintree_success_response,- settings):+ settings, gateway_config):payment = payment_txn_preauthamount = Decimal('10.00')mock_response = Mock(return_value=braintree_success_response)@@ -357,7 +363,7 @@ def test_capture(transaction=Mock(submit_for_settlement=mock_response))payment_info = create_payment_information(payment, 'token', amount)- response = capture(payment_info)+ response = capture(payment_info, gateway_config)assert not response['error']assert response['kind'] == TransactionKind.CAPTURE@@ -373,7 +379,8 @@ def test_capture(@pytest.mark.integration@patch('saleor.payment.gateways.braintree.get_braintree_gateway')def test_capture_incorrect_token(- mock_gateway, payment_txn_preauth, braintree_not_found_error):+ mock_gateway, payment_txn_preauth, braintree_not_found_error,+ gateway_config):payment = payment_txn_preauthamount = Decimal('10.00')mock_response = Mock(side_effect=braintree_not_found_error)@@ -382,14 +389,15 @@ def test_capture_incorrect_token(payment_info = create_payment_information(payment)with pytest.raises(BraintreeException) as e:- capture(payment_info)+ capture(payment_info, gateway_config)assert str(e.value) == DEFAULT_ERROR_MESSAGE@pytest.mark.integration@patch('saleor.payment.gateways.braintree.get_braintree_gateway')def test_capture_error_response(- mock_gateway, payment_txn_preauth, braintree_error_response):+ mock_gateway, payment_txn_preauth, braintree_error_response,+ gateway_config):payment = payment_txn_preauthamount = Decimal('10.00')mock_response = Mock(return_value=braintree_error_response)@@ -397,7 +405,7 @@ def test_capture_error_response(transaction=Mock(submit_for_settlement=mock_response))payment_info = create_payment_information(payment, 'token')- response = capture(payment_info)+ response = capture(payment_info, gateway_config)assert response['raw_response'] == extract_gateway_response(braintree_error_response)@@ -408,13 +416,14 @@ def test_capture_error_response(@pytest.mark.integration@patch('saleor.payment.gateways.braintree.get_braintree_gateway')def test_void(- mock_gateway, payment_txn_preauth, braintree_success_response):+ mock_gateway, payment_txn_preauth, braintree_success_response,+ gateway_config):payment = payment_txn_preauthmock_response = Mock(return_value=braintree_success_response)mock_gateway.return_value = Mock(transaction=Mock(void=mock_response))payment_info = create_payment_information(payment, 'token')- response = void(payment_info)+ response = void(payment_info, gateway_config)assert not response['error']assert response['kind'] == TransactionKind.VOID@@ -428,7 +437,8 @@ def test_void(@pytest.mark.integration@patch('saleor.payment.gateways.braintree.get_braintree_gateway')def test_void_incorrect_token(- mock_gateway, payment_txn_preauth, braintree_not_found_error):+ mock_gateway, payment_txn_preauth, braintree_not_found_error,+ gateway_config):payment = payment_txn_preauthmock_response = Mock(side_effect=braintree_not_found_error)@@ -436,19 +446,20 @@ def test_void_incorrect_token(payment_info = create_payment_information(payment)with pytest.raises(BraintreeException) as e:- void(payment_info)+ void(payment_info, gateway_config)assert str(e.value) == DEFAULT_ERROR_MESSAGE@pytest.mark.integration@patch('saleor.payment.gateways.braintree.get_braintree_gateway')def test_void_error_response(- mock_gateway, payment_txn_preauth, braintree_error_response):+ mock_gateway, payment_txn_preauth, braintree_error_response,+ gateway_config):payment = payment_txn_preauthmock_response = Mock(return_value=braintree_error_response)mock_gateway.return_value = Mock(transaction=Mock(void=mock_response))payment_info = create_payment_information(payment)- response = void(payment_info)+ response = void(payment_info, gateway_config)assert response['raw_response'] == extract_gateway_response(braintree_error_response)@@ -462,28 +473,20 @@ def test_braintree_payment_form_incorrect_amount(payment_dummy):assert amount != payment_dummy.totalpayment_info = create_payment_information(payment_dummy)- form = BraintreePaymentForm(- data=data, payment_information=payment_info,- gateway_params={'secret': '123'})-+ form = BraintreePaymentForm(data=data, payment_information=payment_info)assert not form.is_valid()assert form.non_field_errors-def test_braintree_payment_form(settings, payment_dummy):+def test_braintree_payment_form(payment_dummy):payment = payment_dummy- payment.gateway = settings.BRAINTREEdata = {'amount': payment.total, 'payment_method_nonce': 'fake-nonce'}payment_info = create_payment_information(payment)- form = BraintreePaymentForm(+ form = create_form(data=data, payment_information=payment_info,- gateway_params={'secret': '123'})+ connection_params={'secret': '123'})+ assert isinstance(form, BraintreePaymentForm)assert form.is_valid()---def test_get_form_class(settings):- payment_gateway, gateway_params = get_payment_gateway(settings.BRAINTREE)- assert payment_gateway.get_form_class() == BraintreePaymentFormdiff --git a/tests/gateway/test_dummy.py b/tests/gateway/test_dummy.pyindex e9a7753857..40e3c50d57 100644--- a/tests/gateway/test_dummy.py+++ b/tests/gateway/test_dummy.py@@ -237,16 +237,11 @@ def test_dummy_payment_form(kind, charge_status, settings, payment_dummy):payment_gateway, gateway_params = get_payment_gateway(payment.gateway)payment_info = create_payment_information(payment)- form = DummyPaymentForm(+ form = payment_gateway.create_form(data=data, payment_information=payment_info,- gateway_params=gateway_params)+ connection_params=gateway_params)assert form.is_valid()gateway_process_payment(payment=payment, payment_token=form.get_payment_token())payment.refresh_from_db()assert payment.transactions.last().kind == kind---def test_get_form_class(settings):- payment_gateway, gateway_params = get_payment_gateway(settings.DUMMY)- assert payment_gateway.get_form_class() == DummyPaymentFormdiff --git a/tests/gateway/test_razorpay.py b/tests/gateway/test_razorpay.pyindex 7cf1c593e6..97b498f7f2 100644--- a/tests/gateway/test_razorpay.py+++ b/tests/gateway/test_razorpay.py@@ -6,9 +6,9 @@ from razorpay.errors import BadRequestError, ServerErrorfrom saleor.payment import ChargeStatusfrom saleor.payment.gateways.razorpay import (- charge, check_payment_supported, clean_razorpay_response, errors,- get_amount_for_razorpay, get_client, get_client_token, get_form_class,- logger, refund, TransactionKind)+ TransactionKind, charge, 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)from saleor.payment.utils import create_payment_information@@ -83,10 +83,12 @@ def test_checkout_widget_render_with_prefill(razorpay_payment, gateway_params):def test_checkout_form(razorpay_payment, gateway_params):payment_info = create_payment_information(razorpay_payment)- form = RazorPaymentForm(+ form = create_form(data={'razorpay_payment_id': '123'},payment_information=payment_info,- gateway_params=gateway_params)+ connection_params=gateway_params)++ assert isinstance(form, RazorPaymentForm)assert form.is_valid()@@ -123,10 +125,6 @@ def test_get_client_token():assert get_client_token()-def test_get_form_class():- assert get_form_class() == RazorPaymentForm--@pytest.mark.integration@patch('razorpay.Client')def test_charge(@@ -147,7 +145,7 @@ def test_charge(amount=TRANSACTION_AMOUNT)# Attempt charging- response = charge(payment_info, **gateway_params)+ response = charge(payment_info, gateway_params)# Ensure the was no error returnedassert not response['error']@@ -173,7 +171,7 @@ def test_charge_unsupported_currency(razorpay_payment, gateway_params):amount=TRANSACTION_AMOUNT)# Attempt charging- response = charge(payment_info, **gateway_params)+ response = charge(payment_info, gateway_params)# Ensure a error was returnedassert response['error'] == (@@ -205,7 +203,7 @@ def test_charge_invalid_request(amount=TRANSACTION_AMOUNT)# Attempt charging- response = charge(payment_info, **gateway_params)+ response = charge(payment_info, gateway_params)# Ensure an error was returnedassert response['error'] == errors.INVALID_REQUEST@@ -235,7 +233,7 @@ def test_refund(charged_payment, amount=TRANSACTION_AMOUNT)# Attempt charging- response = refund(payment_info, **gateway_params)+ response = refund(payment_info, gateway_params)# Ensure the was no error returnedassert not response['error']@@ -258,7 +256,7 @@ def test_refund_unsupported_currency(razorpay_payment, amount=TRANSACTION_AMOUNT)# Attempt charging- response = refund(payment_info, **gateway_params)+ response = refund(payment_info, gateway_params)# Ensure a error was returnedassert response['error'] == (@@ -286,7 +284,7 @@ def test_refund_invalid_data(# Attempt chargingpayment_info = create_payment_information(charged_payment, amount=TRANSACTION_AMOUNT)- response = refund(payment_info, **gateway_params)+ response = refund(payment_info, gateway_params)# Ensure a error was returnedassert response['error'] == errors.SERVER_ERRORdiff --git a/tests/gateway/test_stripe.py b/tests/gateway/test_stripe.pyindex ef4f825369..6040c51e20 100644--- a/tests/gateway/test_stripe.py+++ b/tests/gateway/test_stripe.py@@ -8,11 +8,11 @@ from django_countries import countriesfrom saleor.payment import ChargeStatusfrom saleor.payment.gateways.stripe import (- _create_response, _get_client, _get_error_response_from_exc,- _get_stripe_charge_payload, authorize, capture, charge,- get_amount_for_stripe, get_amount_from_stripe, get_client_token,- get_currency_for_stripe, get_currency_from_stripe, get_form_class, refund,- void, TransactionKind)+ 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)from saleor.payment.gateways.stripe.errors import (ORDER_NOT_AUTHORIZED, ORDER_NOT_CHARGED)from saleor.payment.gateways.stripe.forms import (@@ -245,20 +245,19 @@ def test_widget_with_enable_shipping_address_option(stripe_payment, gateway_paradef test_stripe_payment_form(stripe_payment, gateway_params):payment_info = create_payment_information(stripe_payment, FAKE_TOKEN)- form = StripePaymentModalForm(- payment_information=payment_info, gateway_params=gateway_params)+ form = create_form(+ None, payment_information=payment_info,+ connection_params=gateway_params)+ assert isinstance(form, StripePaymentModalForm)assert not form.is_valid()- form = StripePaymentModalForm(+ form = create_form(data={'stripeToken': FAKE_TOKEN}, payment_information=payment_info,- gateway_params=gateway_params)+ connection_params=gateway_params)+ assert isinstance(form, StripePaymentModalForm)assert form.is_valid()-def test_get_form_class():- assert get_form_class() == StripePaymentModalForm--def test_get_client(gateway_params):assert _get_client(**gateway_params).api_key == 'secret'@@ -387,7 +386,7 @@ def test_authorize(response = stripe_charge_success_responsemock_charge_create.return_value = response- response = authorize(payment_info, **gateway_params)+ response = authorize(payment_info, gateway_params)assert not response['error']assert response['transaction_id'] == TRANSACTION_TOKEN@@ -410,7 +409,7 @@ def test_authorize_error_response(message=ERROR_MESSAGE, param=None)mock_charge_create.side_effect = stripe_error- response = authorize(payment_info, **gateway_params)+ response = authorize(payment_info, gateway_params)assert response['error'] == ERROR_MESSAGEassert response['transaction_id'] == FAKE_TOKEN@@ -436,7 +435,7 @@ def test_capture(mock_charge_retrieve.return_value = Mock(capture=Mock(return_value=response))- response = capture(payment_info, **gateway_params)+ response = capture(payment_info, gateway_params)assert not response['error']assert response['transaction_id'] == TRANSACTION_TOKEN@@ -461,7 +460,7 @@ def test_partial_capture(mock_charge_retrieve.return_value = Mock(capture=Mock(return_value=response))- response = capture(payment_info, **gateway_params)+ response = capture(payment_info, gateway_params)assert not response['error']assert response['transaction_id'] == TRANSACTION_TOKEN@@ -485,7 +484,7 @@ def test_capture_error_response(message=ERROR_MESSAGE, param=None)mock_charge_retrieve.side_effect = stripe_error- response = capture(payment_info, **gateway_params)+ response = capture(payment_info, gateway_params)assert response['error'] == ERROR_MESSAGEassert response['transaction_id'] == TRANSACTION_TOKEN@@ -510,7 +509,7 @@ def test_charge(response = stripe_charge_success_responsemock_charge_create.return_value = response- response = charge(payment_info, **gateway_params)+ response = charge(payment_info, gateway_params)assert not response['error']assert response['transaction_id'] == TRANSACTION_TOKEN@@ -534,7 +533,7 @@ def test_charge_error_response(message=ERROR_MESSAGE, param=None)mock_charge_create.side_effect = stripe_error- response = charge(payment_info, **gateway_params)+ response = charge(payment_info, gateway_params)assert response['error'] == ERROR_MESSAGEassert response['transaction_id'] == FAKE_TOKEN@@ -562,7 +561,7 @@ def test_refund_charged(mock_charge_retrieve.return_value = Mock(id='')mock_refund_create.return_value = response- response = refund(payment_info, **gateway_params)+ response = refund(payment_info, gateway_params)assert not response['error']assert response['transaction_id'] == TRANSACTION_TOKEN@@ -589,7 +588,7 @@ def test_refund_captured(mock_charge_retrieve.return_value = Mock(id='')mock_refund_create.return_value = response- response = refund(payment_info, **gateway_params)+ response = refund(payment_info, gateway_params)assert not response['error']assert response['transaction_id'] == TRANSACTION_TOKEN@@ -616,7 +615,7 @@ def test_refund_error_response(message=ERROR_MESSAGE, param=None)mock_refund_create.side_effect = stripe_error- response = refund(payment_info, **gateway_params)+ response = refund(payment_info, gateway_params)assert response['error'] == ERROR_MESSAGEassert response['transaction_id'] == TRANSACTION_TOKEN@@ -643,7 +642,7 @@ def test_void(mock_charge_retrieve.return_value = Mock(id='')mock_refund_create.return_value = response- response = void(payment_info, **gateway_params)+ response = void(payment_info, gateway_params)assert not response['error']assert response['transaction_id'] == TRANSACTION_TOKEN@@ -669,7 +668,7 @@ def test_void_error_response(message=ERROR_MESSAGE, param=None)mock_refund_create.side_effect = stripe_error- response = void(payment_info, **gateway_params)+ response = void(payment_info, gateway_params)assert response['error'] == ERROR_MESSAGEassert response['transaction_id'] == TRANSACTION_TOKENdiff --git a/tests/test_payment.py b/tests/test_payment.pyindex df9377025e..7ad39cf328 100644--- a/tests/test_payment.py+++ b/tests/test_payment.py@@ -10,7 +10,7 @@ from django.template.loader import get_templatefrom saleor.order import OrderEvents, OrderEventsEmailsfrom saleor.order.views import PAYMENT_TEMPLATEfrom saleor.payment import (- ChargeStatus, GatewayError, PaymentError, TransactionKind,+ ChargeStatus, GatewayError, OperationType, PaymentError, TransactionKind,get_payment_gateway)from saleor.payment.models import Paymentfrom saleor.payment.utils import (@@ -174,9 +174,6 @@ def test_create_transaction(transaction_data):assert txn.is_success == transaction_data['gateway_response']['is_success']assert txn.gateway_response == transaction_data['gateway_response']- same_txn = create_transaction(**transaction_data)- assert txn == same_txn-def test_create_transaction_no_gateway_response(transaction_data):transaction_data.pop('gateway_response')@@ -231,7 +228,7 @@ def test_gateway_process_payment(mock_get_payment_gateway.assert_called_with(payment.gateway)mock_process_payment.assert_called_once_with(- payment_information=payment_info, **gateway_params)+ payment_information=payment_info, connection_params=gateway_params)@patch('saleor.payment.utils.get_payment_gateway')@@ -250,7 +247,7 @@ def test_gateway_authorize(mock_get_payment_gateway.assert_called_once_with(payment.gateway)mock_authorize.assert_called_once_with(- payment_information=payment_info, **gateway_params)+ payment_information=payment_info, connection_params=gateway_params)@patch('saleor.payment.utils.get_payment_gateway')@@ -299,7 +296,7 @@ def test_gateway_capture(mock_get_payment_gateway.assert_called_once_with(payment.gateway)mock_capture.assert_called_once_with(- payment_information=payment_info, **gateway_params)+ payment_information=payment_info, connection_params=gateway_params)payment.refresh_from_db()assert payment.charge_status == ChargeStatus.CHARGED@@ -396,7 +393,7 @@ def test_gateway_charge(mock_get_payment_gateway.assert_called_once_with(payment.gateway)mock_charge.assert_called_once_with(- payment_information=payment_info, **gateway_params)+ payment_information=payment_info, connection_params=gateway_params)payment.refresh_from_db()assert payment.charge_status == ChargeStatus.CHARGED@@ -494,7 +491,7 @@ def test_gateway_void(mock_get_payment_gateway.assert_called_once_with(payment.gateway)mock_void.assert_called_once_with(- payment_information=payment_info, **gateway_params)+ payment_information=payment_info, connection_params=gateway_params)payment.refresh_from_db()assert payment.is_active == False@@ -545,7 +542,7 @@ def test_gateway_refund(mock_get_payment_gateway.assert_called_once_with(payment.gateway)mock_refund.assert_called_once_with(- payment_information=payment_info, **gateway_params)+ payment_information=payment_info, connection_params=gateway_params)payment.refresh_from_db()assert payment.charge_status == ChargeStatus.FULLY_REFUNDED@@ -629,9 +626,9 @@ def test_payment_gateway_form_exists(gateway_name, payment_dummy):An error will be raised if it's missing."""- payment_gateway, gateway_params = get_payment_gateway(- gateway_name)- payment_gateway.get_form_class()+ payment_gateway, gateway_params = get_payment_gateway(gateway_name)+ payment_info = create_payment_information(payment_dummy)+ payment_gateway.create_form(None, payment_info, gateway_params)def test_clean_authorize():@@ -852,7 +849,7 @@ def test_call_gateway_invalid_response(with pytest.raises(PaymentError) as e:call_gateway(- func_name='auth', transaction_kind='auth',+ operation_type=OperationType.AUTH, transaction_kind='auth',payment=payment_dummy, payment_token='token')assert str(e.value) == 'Gateway response validation failed'@@ -867,19 +864,20 @@ def test_call_gateway_function_not_implemented(with pytest.raises(PaymentError) as e:call_gateway(- func_name='func', transaction_kind='auth',+ operation_type=OperationType.AUTH, transaction_kind='auth',payment=payment_dummy, payment_token='token')- assert str(e.value) == 'Gateway doesn\'t implement func'+ 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):mock_get_payment_gateway.return_value = (- Mock(auth=Mock(side_effect=Exception('something went wrong'))), {})+ Mock(authorize=Mock(+ side_effect=Exception('something went wrong'))), {})with pytest.raises(PaymentError) as e:call_gateway(- func_name='auth', transaction_kind='auth',+ operation_type=OperationType.AUTH, transaction_kind='auth',payment=payment_dummy, payment_token='token')assert str(e.value) == 'Gateway encountered an error'