Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Support multiple transactions
Michał Jeloneka0d8b7b13cdf
diff --git a/saleor/payment/gateways/dummy/__init__.py b/saleor/payment/gateways/dummy/__init__.pyindex c8a23e3202..1803875af7 100644--- a/saleor/payment/gateways/dummy/__init__.py+++ b/saleor/payment/gateways/dummy/__init__.py@@ -5,9 +5,6 @@ from typing import Dictfrom django.conf import settingsfrom prices import Money-from ... import TransactionKind-from ...models import Payment-from ...utils import create_transactionfrom .forms import DummyPaymentForm@@ -31,9 +28,9 @@ def process_payment(payment: Dict, payment_token: str, amount: Decimal,**connection_params):auth_resp = authorize(payment, payment_token)- if auth_resp['errors']:+ if auth_resp['error']:return auth_resp- return capture(payment, payment_token, amount)+ return [auth_resp, capture(payment, payment_token, amount)]def authorize(payment: Dict, payment_token: str, **connection_params):@@ -43,10 +40,11 @@ def authorize(payment: Dict, payment_token: str, **connection_params):error = 'Unable to authorize transaction'return {'is_success': success,+ 'kind': 'auth',+ 'amount': payment['total'],+ 'currency': payment['currency'],'transaction_id': payment_token,- 'gateway_response': {},- 'errors': error,- }+ 'error': error}def void(payment: Dict, payment_token: str, **connection_params: Dict):@@ -56,10 +54,11 @@ def void(payment: Dict, payment_token: str, **connection_params: Dict):error = 'Unable to void the transaction.'return {'is_success': success,+ 'kind': 'void',+ 'amount': payment['total'],+ 'currency': payment['currency'],'transaction_id': payment_token,- 'gateway_response': {},- 'errors': error,- }+ 'error': error}def capture(@@ -71,10 +70,11 @@ def capture(error = 'Unable to process capture'return {'is_success': success,+ 'kind': 'capture',+ 'amount': amount,+ 'currency': payment['currency'],'transaction_id': payment_token,- 'gateway_response': {},- 'errors': error,- }+ 'error': error}def refund(@@ -86,10 +86,11 @@ def refund(error = 'Unable to process refund'return {'is_success': success,+ 'kind': 'refund',+ 'amount': amount,+ 'currency': payment['currency'],'transaction_id': payment_token,- 'gateway_response': {},- 'errors': error,- }+ 'error': error}def charge(@@ -97,6 +98,8 @@ def charge(**connection_params):"""Performs Authorize and Capture transactions in a single run."""auth_resp = authorize(payment, payment_token)- if auth_resp['errors']:+ if auth_resp['error']:return auth_resp- return capture(payment, payment_token, amount)+ capture_resp = capture(payment, payment_token, amount)+ capture_resp['kind'] = 'charge'+ return [auth_resp, capture_resp]diff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex b7ccd57b3c..644d7776d8 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -1,7 +1,7 @@import loggingfrom decimal import Decimalfrom functools import wraps-from typing import Dict, Optional+from typing import Dict, List, Optionalfrom django.conf import settingsfrom django.db import transaction@@ -78,15 +78,17 @@ def create_transaction(payment: Payment, kind: str, payment_token: str,"""Creates a Transaction based on transaction kind and gateway response."""if gateway_response is None:gateway_response = {}+txn, _ = Transaction.objects.get_or_create(payment=payment,- kind=kind,+ kind=gateway_response.get('kind', kind),token=gateway_response.get('transaction_id', payment_token),is_success=gateway_response.get('is_success', False),- amount=extra_params.get('amount', payment.total),- currency=payment.currency,+ amount=gateway_response.get('amount', payment.total),+ currency=gateway_response.get('currency', payment.currency),+ error=gateway_response.get('error'),gateway_response=gateway_response)- return txn+ return txn # returns last created transactiondef gateway_get_client_token(gateway_name: str):@@ -145,34 +147,42 @@ def call_gateway(logger.exception('Gateway doesn\'t implement %s', func_name)except GatewayError:logger.exception('Gateway response validation failed')- gateway_response = None # set response none as the validation failed+ gateway_response = None # set response empty as the validation failedexcept Exception:logger.exception('Gateway encountered an error')finally:- transaction = create_transaction(- payment=payment,- kind=transaction_kind,- payment_token=payment_token,- gateway_response=gateway_response,- **extra_params)+ if not isinstance(gateway_response, list):+ gateway_response = [gateway_response]+ for response in gateway_response:+ transaction = create_transaction(+ payment=payment,+ kind=transaction_kind,+ payment_token=payment_token,+ gateway_response=response)if not transaction.is_success:# attempt to get errors from response, if none raise a generic one- raise PaymentError(gateway_response.get(- 'errors', GENERIC_TRANSACTION_ERROR))+ raise PaymentError(transaction.error or GENERIC_TRANSACTION_ERROR)return transaction-def validate_gateway_response(response):+def validate_gateway_response(responses):"""Validates response to be a correct format for Saleor to process."""- if not isinstance(response, dict):- raise GatewayError('Gateway needs to return a dictionary')- required_fields = {'transaction_id', 'is_success', 'errors'}- if not required_fields.issubset(response):- raise GatewayError(- 'Gateway response needs to contain following keys: {}'.format(- required_fields - response.keys()))+ if not isinstance(responses, (dict, list)):+ raise GatewayError('Gateway needs to return a dictionary or a list')+ if not isinstance(responses, list):+ responses = [responses]++ required_fields = {+ 'transaction_id', 'is_success', 'kind', 'error', 'amount', 'currency'}+ for response in responses:+ if not required_fields.issubset(response):+ raise GatewayError(+ 'Gateway response needs to contain following keys: {}'.format(+ required_fields - response.keys()))+ #TODO: check if response is json serializable+ #TODO: check if response['kind'] is an allowed choice of TransactionKind@validate_payment@@ -248,6 +258,8 @@ def gateway_capture(payment: Payment, amount: Decimal=None) -> Transaction: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.tokentransaction = call_gateway('capture',@@ -272,6 +284,8 @@ def gateway_void(payment) -> Transaction:auth_transaction = payment.transactions.filter(kind=TransactionKind.AUTH, is_success=True).first()+ if auth_transaction is None:+ raise PaymentError('Cannot void unauthorized transaction')payment_token = auth_transaction.tokentransaction = call_gateway('void', transaction_kind=TransactionKind.VOID,@@ -304,6 +318,8 @@ def gateway_refund(payment, amount: Decimal=None) -> Transaction:transaction = payment.transactions.filter(kind__in=[TransactionKind.CAPTURE, TransactionKind.CHARGE],is_success=True).first()+ if transaction is None:+ raise PaymentError('Cannot refund uncaptured/uncharged transaction')payment_token = transaction.tokentransaction = call_gateway('refund',diff --git a/tests/api/test_payment.py b/tests/api/test_payment.pyindex 3401a7fa7f..1e250ea788 100644--- a/tests/api/test_payment.py+++ b/tests/api/test_payment.py@@ -283,9 +283,10 @@ def test_payment_charge_success(assert not data['errors']payment.refresh_from_db()assert payment.charge_status == ChargeStatus.CHARGED- assert payment.transactions.count() == 1- txn = payment.transactions.last()- assert txn.kind == TransactionKind.CHARGE+ assert payment.transactions.count() == 2+ charge_txn, auth_txn = payment.transactions.all()+ assert auth_txn.kind == TransactionKind.AUTH+ assert charge_txn.kind == TransactionKind.CHARGEdef test_payment_charge_gateway_error(@@ -314,7 +315,7 @@ def test_payment_charge_gateway_error(assert payment.charge_status == ChargeStatus.NOT_CHARGEDassert payment.transactions.count() == 1txn = payment.transactions.last()- assert txn.kind == TransactionKind.CHARGE+ assert txn.kind == TransactionKind.AUTHassert not txn.is_successdiff --git a/tests/test_order.py b/tests/test_order.pyindex 1a22014772..b1654e9a2d 100644--- a/tests/test_order.py+++ b/tests/test_order.py@@ -476,8 +476,9 @@ def test_order_payment_flow(payment = order.payments.all()[0]assert payment.total == order.total.gross.amountassert payment.currency == order.total.gross.currency- assert payment.transactions.count() == 1- assert payment.transactions.first().kind == 'capture'+ assert payment.transactions.count() == 2+ assert payment.transactions.first().kind == 'auth'+ assert payment.transactions.last().kind == 'capture'def test_create_user_after_order(order, client):diff --git a/tests/test_payment.py b/tests/test_payment.pyindex ce18c7ab9a..f813a3aab7 100644--- a/tests/test_payment.py+++ b/tests/test_payment.py@@ -28,11 +28,12 @@ def transaction_data(payment_dummy, settings):'payment': payment_dummy,'payment_token': 'token','kind': TransactionKind.CAPTURE,- 'amount': Decimal(14.50),'gateway_response': {'is_success': True,'transaction_id': 'token','errors': None,+ 'amount': Decimal(14.50),+ 'currency': 'USD','raw_response': {'credit_card': '4321','transaction': 'token'}}}@@ -48,6 +49,18 @@ def transaction_token():return 'transaction-token'+def dummy_response(payment_dummy, transaction_data, transaction_token):+ return {+ 'is_success': True,+ 'transaction_id': transaction_token,+ 'error': EXAMPLE_ERROR,+ 'amount': payment_dummy.total,+ 'currency': payment_dummy.currency,+ 'kind': TransactionKind.AUTH,+ }++def test_get_billing_data(order):assert order.billing_addressresult = get_billing_data(order)@@ -143,7 +156,8 @@ def test_create_transaction(transaction_data):assert txn.payment == transaction_data['payment']assert txn.kind == transaction_data['kind']- assert txn.amount == transaction_data['amount']+ assert txn.amount == transaction_data['gateway_response']['amount']+ assert txn.currency == transaction_data['gateway_response']['currency']assert txn.token == transaction_data['gateway_response']['transaction_id']assert txn.is_success == transaction_data['gateway_response']['is_success']assert txn.gateway_response == transaction_data['gateway_response']@@ -193,15 +207,12 @@ def test_payment_needs_to_be_active_for_any_action(func, payment_dummy):@patch('saleor.payment.utils.get_payment_gateway')def test_gateway_authorize(mock_get_payment_gateway, payment_txn_preauth, gateway_params,- transaction_token):+ transaction_token, dummy_response):payment_token = transaction_tokentxn = payment_txn_preauth.transactions.first()payment = payment_txn_preauth- mock_authorize = Mock(return_value={- 'is_success': True,- 'transaction_id': 'token',- 'errors': None})+ mock_authorize = Mock(return_value=dummy_response)mock_get_payment_gateway.return_value = (Mock(authorize=mock_authorize), gateway_params)@@ -215,16 +226,14 @@ def test_gateway_authorize(@patch('saleor.payment.utils.get_payment_gateway')def test_gateway_authorize_failed(mock_get_payment_gateway, payment_txn_preauth, gateway_params,- transaction_token):+ transaction_token, dummy_response):payment_token = transaction_tokentxn = payment_txn_preauth.transactions.first()txn.is_success = Falsepayment = payment_txn_preauth- mock_authorize = Mock(return_value={- 'is_success': False,- 'transaction_id': 'token',- 'errors': EXAMPLE_ERROR})+ dummy_response['is_success'] = False+ mock_authorize = Mock(return_value=dummy_response)mock_get_payment_gateway.return_value = (Mock(authorize=mock_authorize), gateway_params)with pytest.raises(PaymentError) as exc:@@ -244,15 +253,13 @@ def test_gateway_authorize_errors(payment_dummy):@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):+ gateway_params, dummy_response):payment = payment_txn_preauthassert not payment.captured_amountamount = payment.total- mock_capture = Mock(return_value={- 'is_success': True,- 'transaction_id': 'token',- 'errors': None})+ dummy_response['kind'] = TransactionKind.CAPTURE+ mock_capture = Mock(return_value=dummy_response)mock_get_payment_gateway.return_value = (Mock(capture=mock_capture), gateway_params)@@ -272,17 +279,16 @@ def test_gateway_capture(@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):+ gateway_params, settings, dummy_response):payment = payment_txn_preauthamount = payment.total * Decimal('0.5')txn = payment.transactions.first()txn.amount = amounttxn.currency = settings.DEFAULT_CURRENCY- mock_capture = Mock(return_value={- 'is_success': True,- 'transaction_id': 'token',- 'errors': None})+ 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)@@ -299,17 +305,16 @@ def test_gateway_capture_partial_capture(@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):+ gateway_params, dummy_response):txn = payment_txn_preauth.transactions.first()txn.is_success = Falsepayment = payment_txn_preauthamount = payment.total- mock_capture = Mock(return_value={- 'is_success': False,- 'transaction_id': 'token',- 'errors': EXAMPLE_ERROR})+ 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)with pytest.raises(PaymentError) as exc:@@ -342,17 +347,15 @@ def test_gateway_capture_errors(payment_txn_preauth):@patch('saleor.payment.utils.get_payment_gateway')def test_gateway_charge(mock_get_payment_gateway, mock_handle_fully_paid_order, payment_txn_preauth,- gateway_params, transaction_token):+ gateway_params, transaction_token, dummy_response):payment_token = transaction_tokentxn = payment_txn_preauth.transactions.first()payment = payment_txn_preauthassert not payment.captured_amountamount = payment.total- mock_charge = Mock(return_value={- 'is_success': True,- 'transaction_id': 'token',- 'errors': None})+ dummy_response['kind'] = TransactionKind.CHARGE+ mock_charge = Mock(return_value=dummy_response)mock_get_payment_gateway.return_value = (Mock(charge=mock_charge), gateway_params)@@ -373,7 +376,7 @@ def test_gateway_charge(@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):+ gateway_params, transaction_token, settings, dummy_response):payment_token = transaction_tokenpayment = payment_txn_preauthamount = payment.total * Decimal('0.5')@@ -381,10 +384,9 @@ def test_gateway_capture_partial_charge(txn.amount = amounttxn.currency = settings.DEFAULT_CURRENCY- mock_charge = Mock(return_value={- 'is_success': True,- 'transaction_id': 'token',- 'errors': None})+ dummy_response['kind'] = TransactionKind.CAPTURE+ dummy_response['amount'] = amount+ mock_charge = Mock(return_value=dummy_response)mock_get_payment_gateway.return_value = (Mock(charge=mock_charge), gateway_params)@@ -401,7 +403,7 @@ def test_gateway_capture_partial_charge(@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):+ gateway_params, transaction_token, dummy_response):payment_token = transaction_tokentxn = payment_txn_preauth.transactions.first()txn.is_success = False@@ -409,10 +411,9 @@ def test_gateway_charge_failed(payment = payment_txn_preauthamount = payment.total- mock_charge = Mock(return_value={- 'is_success': False,- 'transaction_id': 'token',- 'errors': EXAMPLE_ERROR})+ dummy_response['is_success'] = False+ dummy_response['kind'] = TransactionKind.CAPTURE+ mock_charge = Mock(return_value=dummy_response)mock_get_payment_gateway.return_value = (Mock(charge=mock_charge), gateway_params)with pytest.raises(PaymentError) as exc:@@ -445,15 +446,15 @@ def test_gateway_charge_errors(payment_dummy, transaction_token):@patch('saleor.payment.utils.get_payment_gateway')-def test_gateway_void(mock_get_payment_gateway, payment_txn_preauth, gateway_params):+def test_gateway_void(+ mock_get_payment_gateway, payment_txn_preauth,+ gateway_params, dummy_response):txn = payment_txn_preauth.transactions.first()payment = payment_txn_preauthassert payment.is_active- mock_void = Mock(return_value={- 'is_success': True,- 'transaction_id': 'token',- 'errors': None})+ dummy_response['kind'] = TransactionKind.VOID+ mock_void = Mock(return_value=dummy_response)mock_get_payment_gateway.return_value = (Mock(void=mock_void), gateway_params)payment_info = model_to_dict(payment)@@ -468,15 +469,15 @@ def test_gateway_void(mock_get_payment_gateway, payment_txn_preauth, gateway_par@patch('saleor.payment.utils.get_payment_gateway')def test_gateway_void_failed(- mock_get_payment_gateway, payment_txn_preauth, gateway_params):+ mock_get_payment_gateway, payment_txn_preauth, gateway_params,+ dummy_response):txn = payment_txn_preauth.transactions.first()txn.is_success = Falsepayment = payment_txn_preauth- mock_void = Mock(return_value={- 'is_success': False,- 'transaction_id': 'token',- 'errors': EXAMPLE_ERROR})+ 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)with pytest.raises(PaymentError) as exc:gateway_void(payment)@@ -495,15 +496,14 @@ def test_gateway_void_errors(payment_dummy):@patch('saleor.payment.utils.get_payment_gateway')def test_gateway_refund(- mock_get_payment_gateway, payment_txn_captured, gateway_params):+ mock_get_payment_gateway, payment_txn_captured, gateway_params,+ dummy_response):txn = payment_txn_captured.transactions.first()payment = payment_txn_capturedamount = payment.total- mock_refund = Mock(return_value={- 'is_success': True,- 'transaction_id': 'token',- 'errors': None})+ dummy_response['kind'] = TransactionKind.REFUND+ mock_refund = Mock(return_value=dummy_response)mock_get_payment_gateway.return_value = (Mock(refund=mock_refund), gateway_params)@@ -521,17 +521,17 @@ def test_gateway_refund(@patch('saleor.payment.utils.get_payment_gateway')def test_gateway_refund_partial_refund(- mock_get_payment_gateway, payment_txn_captured, gateway_params, settings):+ mock_get_payment_gateway, payment_txn_captured, gateway_params,+ settings, dummy_response):payment = payment_txn_capturedamount = payment.total * Decimal('0.5')txn = payment_txn_captured.transactions.first()txn.amount = amounttxn.currency = settings.DEFAULT_CURRENCY- mock_refund = Mock(return_value={- 'is_success': True,- 'transaction_id': 'token',- 'errors': None})+ 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)@@ -544,16 +544,16 @@ def test_gateway_refund_partial_refund(@patch('saleor.payment.utils.get_payment_gateway')def test_gateway_refund_failed(- mock_get_payment_gateway, payment_txn_captured, gateway_params, settings):+ mock_get_payment_gateway, payment_txn_captured, gateway_params,+ settings, dummy_response):txn = payment_txn_captured.transactions.first()payment = payment_txn_capturedcaptured_before = payment.captured_amounttxn.is_success = False- mock_refund = Mock(return_value={- 'is_success': False,- 'transaction_id': 'token',- 'errors': EXAMPLE_ERROR})+ 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)