Skip to content

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

Improve validation, documentations, make response more consistent

Michał Jelonek076af3828533
diff --git a/docs/guides/payments.rst b/docs/guides/payments.rst
index b5974d04ef..cb7295bb23 100644
--- a/docs/guides/payments.rst
+++ b/docs/guides/payments.rst
@@ -217,11 +217,53 @@ Parameters
+-------------------------+----------+------------------------------------------------------------------------------------+
| name | type | description |
+-------------------------+----------+------------------------------------------------------------------------------------+
-| ``payment_information`` | ``dict`` | Payment information, containing the tokens, amount, currency and billing. |
+| ``payment_information`` | ``dict`` | Payment information, containing the token, amount, currency and billing. |
+-------------------------+----------+------------------------------------------------------------------------------------+
| ``connection_params`` | ``dict`` | List of parameters used for connecting to the payment's gateway. |
+-------------------------+----------+------------------------------------------------------------------------------------+
+Example
+"""""""
+
+.. code-block:: python
+
+ payment_information = {
+ 'token': 'token-used-for-transaction', # provided by gateway
+ 'amount': Decimal('174.32'), # amount to be authorized/captured/charged/refunded
+ 'currency': 'USD', # ISO 4217 currency code
+ 'billing': { # billing information
+ 'first_name': 'Joe',
+ 'last_name': 'Doe',
+ 'company_name': 'JoeDoe Inc.',
+ 'street_address_1': '3417 Bridge Street'
+ 'street_address_2': '',
+ 'city': 'Pryor',
+ 'city_area': '',
+ 'postal_code': '74361',
+ 'country': 'US',
+ 'country_area': 'OK'
+ 'phone': '+19188249023'},
+ 'shipping': { # shipping information
+ 'first_name': 'Dollie',
+ 'last_name': 'Sullivan',
+ 'company_name': '',
+ 'street_address_1': '2003 Progress Way'
+ 'street_address_2': '',
+ 'city': 'Waterloo',
+ 'city_area': '',
+ 'postal_code': '50797',
+ 'country': 'US',
+ 'country_area': 'IA'
+ 'phone': '+19188249023'},
+ 'order': 117, # order id
+ 'customer_ip_address': '10.0.0.1', # ip address of the customer
+ 'customer_email': '[email protected]', # email of the customer
+ }
+
+ connection_params = {
+
+ }
+
Returns
^^^^^^^
@@ -233,6 +275,46 @@ Returns
| ``client_token`` | ``str`` | Unique client's token that will be used as his indentifier in the payment process. |
+----------------------+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------+
+
+Gateway response fields
+"""""""""""""""""""""""
+
++----------------+-------------+--------------------------------------------------------------------------+
+| name | type | description |
++----------------+-------------+--------------------------------------------------------------------------+
+| transaction_id | ``str`` | Transaction ID as returned by the gateway. |
++----------------+-------------+--------------------------------------------------------------------------+
+| kind | ``str`` | Transaction kind, one of: auth, capture, charge, refund, void. |
++----------------+-------------+--------------------------------------------------------------------------+
+| is_success | ``bool`` | Status whether the transaction was successful or not. |
++----------------+-------------+--------------------------------------------------------------------------+
+| amount | ``Decimal`` | Amount that the gateway actually charged or authorized. |
++----------------+-------------+--------------------------------------------------------------------------+
+| currency | ``str`` | Currency in which the gateway charged, needs to be an ISO 4217 code. |
++----------------+-------------+--------------------------------------------------------------------------+
+| error | ``str`` | An error message if one occured. Should be ``None`` if no error occured. |
++----------------+-------------+--------------------------------------------------------------------------+
+
+Additional fields can be sent for logging/debug purposes. The only requirement is that they're serializable by
+``DjangoJSONEncoder``. They will be saved in ``gateway_response`` field on Transaction model.
+
+
+Example
+=======
+
+.. code-block: python
+
+ response = {
+ 'transaction_id': 'token-from-gateway',
+ 'kind': 'auth',
+ 'is_success': True,
+ 'amount': Decimal(14.50),
+ 'currency': 'USD',
+ 'error': None,
+ 'extra_field': 'additional information',
+ 'raw_response': raw_gateway_response_as_dict}
+
+
Handling errors
---------------
diff --git a/saleor/payment/gateways/braintree/__init__.py b/saleor/payment/gateways/braintree/__init__.py
index e17d41fc59..e83cf9f26a 100644
--- a/saleor/payment/gateways/braintree/__init__.py
+++ b/saleor/payment/gateways/braintree/__init__.py
@@ -31,6 +31,14 @@ ERROR_CODES_WHITELIST = {
}
+class TransactionKind:
+ AUTH = 'auth'
+ CAPTURE = 'capture'
+ CHARGE = 'charge'
+ REFUND = 'refund'
+ VOID = 'void'
+
+
def get_customer_data(payment_information: Dict) -> Dict:
billing = payment_information['billing']
return {
@@ -115,18 +123,6 @@ def get_client_token(**connection_params: Dict) -> str:
return client_token
-def process_payment(
- payment_information: Dict, **connection_params: Dict) -> Dict:
- auth_resp = authorize(payment_information, **connection_params)
- payment_information['token'] = auth_resp['transaction_id']
-
- try:
- assert auth_resp['is_success']
- return [auth_resp, capture(payment_information, **connection_params)]
- except Exception:
- return [auth_resp, void(payment_information, **connection_params)]
-
-
def authorize(payment_information: Dict, **connection_params: Dict) -> Dict:
gateway = get_braintree_gateway(**connection_params)
@@ -147,10 +143,13 @@ def authorize(payment_information: Dict, **connection_params: Dict) -> Dict:
return {
'is_success': result.is_success,
- 'kind': 'auth',
- 'amount': gateway_response.get('amount'),
- 'currency': gateway_response.get('currency'),
- 'transaction_id': gateway_response.get('transaction_id'),
+ 'kind': TransactionKind.AUTH,
+ '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']),
'error': error,
'raw_response': gateway_response}
@@ -170,10 +169,13 @@ def capture(payment_information: Dict, **connection_params: Dict) -> Dict:
return {
'is_success': result.is_success,
- 'kind': 'capture',
- 'amount': gateway_response.get('amount'),
- 'currency': gateway_response.get('currency'),
- 'transaction_id': gateway_response.get('transaction_id'),
+ 'kind': TransactionKind.CAPTURE,
+ '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']),
'error': error,
'raw_response': gateway_response}
@@ -192,10 +194,13 @@ def void(payment_information: Dict, **connection_params: Dict) -> Dict:
return {
'is_success': result.is_success,
- 'kind': 'void',
- 'amount': gateway_response.get('amount'),
- 'currency': gateway_response.get('currency'),
- 'transaction_id': gateway_response.get('transaction_id'),
+ 'kind': TransactionKind.VOID,
+ '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']),
'error': error,
'raw_response': gateway_response}
@@ -215,9 +220,21 @@ def refund(payment_information: Dict, **connection_params: Dict) -> Dict:
return {
'is_success': result.is_success,
- 'kind': 'refund',
- 'amount': gateway_response.get('amount'),
- 'currency': gateway_response.get('currency'),
- 'transaction_id': gateway_response.get('transaction_id'),
+ 'kind': TransactionKind.REFUND,
+ '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']),
'error': error,
'raw_response': gateway_response}
+
+
+def process_payment(
+ 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)]
diff --git a/saleor/payment/gateways/braintree/errors.py b/saleor/payment/gateways/braintree/errors.py
index 32e9932c56..86583fb70e 100644
--- a/saleor/payment/gateways/braintree/errors.py
+++ b/saleor/payment/gateways/braintree/errors.py
@@ -122,5 +122,4 @@ class BraintreeException(Exception):
def __init__(self, *args, **kwargs):
if args or kwargs:
super().__init__(*args, **kwargs)
- else:
- super().__init__(DEFAULT_ERROR_MESSAGE)
+ super().__init__(DEFAULT_ERROR_MESSAGE)
diff --git a/saleor/payment/gateways/dummy/__init__.py b/saleor/payment/gateways/dummy/__init__.py
index 274a36ef96..552aef28ac 100644
--- a/saleor/payment/gateways/dummy/__init__.py
+++ b/saleor/payment/gateways/dummy/__init__.py
@@ -8,6 +8,14 @@ from prices import Money
from .forms import DummyPaymentForm
+class TransactionKind:
+ AUTH = 'auth'
+ CAPTURE = 'capture'
+ CHARGE = 'charge'
+ REFUND = 'refund'
+ VOID = 'void'
+
+
def dummy_success():
return True
@@ -27,7 +35,7 @@ def get_form_class():
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 auth_resp['error']:
+ if not auth_resp['is_success']:
return auth_resp
return [auth_resp, capture(payment_information, **connection_params)]
@@ -39,7 +47,7 @@ def authorize(payment_information: Dict, **connection_params) -> Dict:
error = 'Unable to authorize transaction'
return {
'is_success': success,
- 'kind': 'auth',
+ 'kind': TransactionKind.AUTH,
'amount': payment_information['amount'],
'currency': payment_information['currency'],
'transaction_id': payment_information['token'],
@@ -53,7 +61,7 @@ def void(payment_information: Dict, **connection_params) -> Dict:
error = 'Unable to void the transaction.'
return {
'is_success': success,
- 'kind': 'void',
+ 'kind': TransactionKind.VOID,
'amount': payment_information['amount'],
'currency': payment_information['currency'],
'transaction_id': payment_information['token'],
@@ -67,7 +75,7 @@ def capture(payment_information: Dict, **connection_params: Dict) -> Dict:
error = 'Unable to process capture'
return {
'is_success': success,
- 'kind': 'capture',
+ 'kind': TransactionKind.CAPTURE,
'amount': payment_information['amount'],
'currency': payment_information['currency'],
'transaction_id': payment_information['token'],
@@ -81,7 +89,7 @@ def refund(payment_information: Dict, **connection_params: Dict):
error = 'Unable to process refund'
return {
'is_success': success,
- 'kind': 'refund',
+ 'kind': TransactionKind.REFUND,
'amount': payment_information['amount'],
'currency': payment_information['currency'],
'transaction_id': payment_information['token'],
@@ -91,6 +99,6 @@ def refund(payment_information: Dict, **connection_params: Dict):
def charge(payment_information: Dict, **connection_params):
"""Performs Authorize and Capture transactions in a single run."""
auth_resp = authorize(payment_information, **connection_params)
- if auth_resp['error']:
+ if not auth_resp['is_success']:
return auth_resp
return [auth_resp, capture(payment_information, **connection_params)]
diff --git a/saleor/payment/gateways/razorpay/__init__.py b/saleor/payment/gateways/razorpay/__init__.py
index 273f9af084..ce987f5415 100644
--- a/saleor/payment/gateways/razorpay/__init__.py
+++ b/saleor/payment/gateways/razorpay/__init__.py
@@ -26,14 +26,22 @@ RAZORPAY_EXCEPTIONS = (
logger = logging.getLogger(__name__)
+class TransactionKind:
+ AUTH = 'auth'
+ CAPTURE = 'capture'
+ CHARGE = 'charge'
+ REFUND = 'refund'
+ VOID = 'void'
+
+
def _generate_response(
payment_information: Dict,
kind: str,
*,
is_success=True,
**data) -> Dict:
- """Creates a transaction from a Razorpay's success payload
- or from passed data."""
+ """Generate Saleor transaction information from
+ Razorpay's success payload or from passed data."""
return {
'transaction_id': data.get('id', payment_information['token']),
'kind': kind,
@@ -87,10 +95,6 @@ def get_client_token(**_):
return str(uuid.uuid4())
-def process_payment(payment_information: Dict, **connection_params) -> Dict:
- return charge(payment_information=payment_information, **connection_params)
-
-
def charge(payment_information: Dict, **connection_params: Dict) -> Dict:
"""Charge a authorized payment using the razorpay client.
@@ -121,7 +125,8 @@ def charge(payment_information: Dict, **connection_params: Dict) -> Dict:
id=payment_information['token'])
return _generate_response(
- payment_information=payment_information, kind='charge', **response)
+ payment_information=payment_information,
+ kind=TransactionKind.CHARGE, **response)
def refund(payment_information: Dict, **connection_params) -> Dict:
@@ -153,4 +158,9 @@ def refund(payment_information: Dict, **connection_params) -> Dict:
payment_information['amount'], error=error)
return _generate_response(
- payment_information=payment_information, kind='refund', **response)
+ payment_information=payment_information,
+ kind=TransactionKind.REFUND, **response)
+
+
+def process_payment(payment_information: Dict, **connection_params) -> Dict:
+ return charge(payment_information=payment_information, **connection_params)
diff --git a/saleor/payment/gateways/stripe/__init__.py b/saleor/payment/gateways/stripe/__init__.py
index 12e1a188cb..999aa9e136 100644
--- a/saleor/payment/gateways/stripe/__init__.py
+++ b/saleor/payment/gateways/stripe/__init__.py
@@ -11,6 +11,14 @@ from .utils import (
shipping_to_stripe_dict)
+class TransactionKind:
+ AUTH = 'auth'
+ CAPTURE = 'capture'
+ CHARGE = 'charge'
+ REFUND = 'refund'
+ VOID = 'void'
+
+
def get_client_token(**_):
"""Not implemented for stripe gateway currently. The client token can be
generated by Stripe's checkout.js or stripe.js automatically.
@@ -18,10 +26,6 @@ def get_client_token(**_):
return
-def process_payment(payment_information, **connection_params):
- return charge(payment_information, **connection_params)
-
-
def authorize(payment_information, **connection_params):
client, error = _get_client(**connection_params), None
@@ -37,7 +41,7 @@ def authorize(payment_information, **connection_params):
# Create response
return _create_response(
payment_information=payment_information,
- kind='auth', response=response, error=error)
+ kind=TransactionKind.AUTH, response=response, error=error)
def capture(payment_information, **connection_params):
@@ -59,7 +63,7 @@ def capture(payment_information, **connection_params):
# Create response
return _create_response(
payment_information=payment_information,
- kind='capture', response=response, error=error)
+ kind=TransactionKind.CAPTURE, response=response, error=error)
def charge(payment_information, **connection_params):
@@ -77,7 +81,7 @@ def charge(payment_information, **connection_params):
# Create response
return _create_response(
payment_information=payment_information,
- kind='charge', response=response, error=error)
+ kind=TransactionKind.CHARGE, response=response, error=error)
def refund(payment_information, **connection_params):
@@ -100,7 +104,7 @@ def refund(payment_information, **connection_params):
# Create response
return _create_response(
payment_information=payment_information,
- kind='refund', response=response, error=error)
+ kind=TransactionKind.REFUND, response=response, error=error)
def void(payment_information, **connection_params):
@@ -117,7 +121,11 @@ def void(payment_information, **connection_params):
# Create response
return _create_response(
payment_information=payment_information,
- kind='void', response=response, error=error)
+ kind=TransactionKind.VOID, response=response, error=error)
+
+
+def process_payment(payment_information, **connection_params):
+ return charge(payment_information, **connection_params)
def get_template():
@@ -187,7 +195,7 @@ def _create_response(payment_information, kind, response, error):
amount = get_amount_from_stripe(stripe_amount, currency)
# Get token, which is an empty string for error responses
- token = response.get('id', '')
+ token = response.get('id', payment_information['token'])
# Check if the response's status is flagged as succeeded
is_success = (response.get('status') == 'succeeded')
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 60982e9005..de9d3a8563 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -108,6 +108,8 @@ def create_transaction(
if gateway_response is None:
gateway_response = {}
+ # 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(
payment=payment,
kind=gateway_response.get('kind', kind),
@@ -119,8 +121,7 @@ def create_transaction(
'currency', payment_information['currency']),
error=gateway_response.get('error', error_msg),
gateway_response=gateway_response)
- return txn # returns last created transaction
-
+ return txn
def gateway_get_client_token(gateway_name: str):
"""Gets client token, that will be used as a customer's identificator for
@@ -213,17 +214,35 @@ def validate_gateway_response(responses):
if not isinstance(responses, list):
responses = [responses]
+ field_types = {
+ 'amount': Decimal,
+ 'currency': str,
+ 'is_success': bool,
+ 'kind': str,
+ 'transaction_id': str,
+ 'error': (type(None), str),
+ }
+
for response in responses:
if not REQUIRED_GATEWAY_KEYS.issubset(response):
raise GatewayError(
'Gateway response needs to contain following keys: {}'.format(
sorted(REQUIRED_GATEWAY_KEYS)))
+ for name, value in response.items():
+ if name in field_types:
+ if not isinstance(value, field_types[name]):
+ raise GatewayError('{} must be of type {}, was {}'.format(
+ name, field_types[name], type(value)))
+
if response['kind'] not in ALLOWED_GATEWAY_KINDS:
raise GatewayError(
'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.')
+
try:
json.dumps(response, cls=DjangoJSONEncoder)
except (TypeError, ValueError):
diff --git a/tests/gateway/test_braintree.py b/tests/gateway/test_braintree.py
index deff5c8d82..732334dedb 100644
--- a/tests/gateway/test_braintree.py
+++ b/tests/gateway/test_braintree.py
@@ -11,10 +11,10 @@ from braintree.validation_error import ValidationError
from django.core.exceptions import ImproperlyConfigured
from prices import Money
-from saleor.payment import TransactionKind, get_payment_gateway
+from saleor.payment import get_payment_gateway
from saleor.payment.gateways.braintree import (
- CONFIRM_MANUALLY, THREE_D_SECURE_REQUIRED, authorize, capture,
- extract_gateway_response, get_braintree_gateway, get_client_token,
+ 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)
from saleor.payment.gateways.braintree.errors import (
DEFAULT_ERROR_MESSAGE, BraintreeException)
diff --git a/tests/gateway/test_dummy.py b/tests/gateway/test_dummy.py
index fa42dd2900..b8b48ca2a3 100644
--- a/tests/gateway/test_dummy.py
+++ b/tests/gateway/test_dummy.py
@@ -129,7 +129,7 @@ def test_void_gateway_error(payment_txn_preauth, monkeypatch):
@pytest.mark.parametrize('amount', [80, 70])
def test_capture_success(amount, payment_txn_preauth):
- txn = gateway_capture(payment=payment_txn_preauth, amount=amount)
+ txn = gateway_capture(payment=payment_txn_preauth, amount=Decimal(amount))
assert txn.is_success
assert txn.payment == payment_txn_preauth
payment_txn_preauth.refresh_from_db()
@@ -178,7 +178,7 @@ def test_refund_success(
payment.charge_status = ChargeStatus.CHARGED
payment.captured_amount = initial_captured_amount
payment.save()
- txn = gateway_refund(payment=payment, amount=refund_amount)
+ txn = gateway_refund(payment=payment, amount=Decimal(refund_amount))
assert txn.kind == TransactionKind.REFUND
assert txn.is_success
assert txn.payment == payment
@@ -200,7 +200,7 @@ def test_refund_failed(
payment.captured_amount = Decimal(initial_captured_amount)
payment.save()
with pytest.raises(PaymentError):
- txn = gateway_refund(payment=payment, amount=refund_amount)
+ txn = gateway_refund(payment=payment, amount=Decimal(refund_amount))
assert txn is None
diff --git a/tests/gateway/test_razorpay.py b/tests/gateway/test_razorpay.py
index 18891b7589..7cf1c593e6 100644
--- a/tests/gateway/test_razorpay.py
+++ b/tests/gateway/test_razorpay.py
@@ -4,11 +4,11 @@ from unittest.mock import patch
import pytest
from razorpay.errors import BadRequestError, ServerError
-from saleor.payment import ChargeStatus, TransactionKind
+from saleor.payment import ChargeStatus
from 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)
+ logger, refund, TransactionKind)
from saleor.payment.gateways.razorpay.forms import (
RazorPayCheckoutWidget, RazorPaymentForm)
from saleor.payment.utils import create_payment_information
diff --git a/tests/gateway/test_stripe.py b/tests/gateway/test_stripe.py
index bd5711674e..ef4f825369 100644
--- a/tests/gateway/test_stripe.py
+++ b/tests/gateway/test_stripe.py
@@ -6,13 +6,13 @@ import pytest
import stripe
from django_countries import countries
-from saleor.payment import ChargeStatus, TransactionKind
+from saleor.payment import ChargeStatus
from 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)
+ void, TransactionKind)
from saleor.payment.gateways.stripe.errors import (
ORDER_NOT_AUTHORIZED, ORDER_NOT_CHARGED)
from saleor.payment.gateways.stripe.forms import (
@@ -362,14 +362,14 @@ def test_create_transaction_with_refund_success_response(
def test_create_response_with_error_response(stripe_payment):
payment = stripe_payment
- payment_info = create_payment_information(payment)
+ payment_info = create_payment_information(payment, FAKE_TOKEN)
stripe_error_response = {}
response = _create_response(
payment_information=payment_info, kind='ANYKIND',
response=stripe_error_response, error=None)
- assert response['transaction_id'] == ''
+ assert response['transaction_id'] == FAKE_TOKEN
assert response['is_success'] is False
assert response['amount'] == payment.total
assert response['currency'] == payment.currency
@@ -413,7 +413,7 @@ def test_authorize_error_response(
response = authorize(payment_info, **gateway_params)
assert response['error'] == ERROR_MESSAGE
- assert response['transaction_id'] == ''
+ assert response['transaction_id'] == FAKE_TOKEN
assert response['kind'] == TransactionKind.AUTH
assert not response['is_success']
assert response['amount'] == payment.total
@@ -480,7 +480,7 @@ def test_capture_error_response(
gateway_params):
payment = stripe_authorized_payment
payment_info = create_payment_information(
- payment, amount=TRANSACTION_AMOUNT)
+ payment, TRANSACTION_TOKEN, amount=TRANSACTION_AMOUNT)
stripe_error = stripe.error.InvalidRequestError(
message=ERROR_MESSAGE, param=None)
mock_charge_retrieve.side_effect = stripe_error
@@ -488,7 +488,7 @@ def test_capture_error_response(
response = capture(payment_info, **gateway_params)
assert response['error'] == ERROR_MESSAGE
- assert response['transaction_id'] == ''
+ assert response['transaction_id'] == TRANSACTION_TOKEN
assert response['kind'] == TransactionKind.CAPTURE
assert not response['is_success']
assert response['amount'] == payment.total
@@ -537,7 +537,7 @@ def test_charge_error_response(
response = charge(payment_info, **gateway_params)
assert response['error'] == ERROR_MESSAGE
- assert response['transaction_id'] == ''
+ assert response['transaction_id'] == FAKE_TOKEN
assert response['kind'] == TransactionKind.CHARGE
assert not response['is_success']
assert response['amount'] == payment.total
@@ -557,7 +557,7 @@ def test_refund_charged(
stripe_refund_success_response):
payment = stripe_charged_payment
payment_info = create_payment_information(
- payment, amount=TRANSACTION_AMOUNT)
+ payment, TRANSACTION_TOKEN, amount=TRANSACTION_AMOUNT)
response = stripe_refund_success_response
mock_charge_retrieve.return_value = Mock(id='')
mock_refund_create.return_value = response
@@ -610,7 +610,7 @@ def test_refund_error_response(
gateway_params):
payment = stripe_charged_payment
payment_info = create_payment_information(
- payment, amount=TRANSACTION_AMOUNT)
+ payment, TRANSACTION_TOKEN, amount=TRANSACTION_AMOUNT)
mock_charge_retrieve.return_value = Mock(id='')
stripe_error = stripe.error.InvalidRequestError(
message=ERROR_MESSAGE, param=None)
@@ -619,7 +619,7 @@ def test_refund_error_response(
response = refund(payment_info, **gateway_params)
assert response['error'] == ERROR_MESSAGE
- assert response['transaction_id'] == ''
+ assert response['transaction_id'] == TRANSACTION_TOKEN
assert response['kind'] == TransactionKind.REFUND
assert not response['is_success']
assert response['amount'] == payment.total
@@ -638,7 +638,7 @@ def test_void(
gateway_params,
stripe_refund_success_response):
payment = stripe_authorized_payment
- payment_info = create_payment_information(payment)
+ payment_info = create_payment_information(payment, TRANSACTION_TOKEN)
response = stripe_refund_success_response
mock_charge_retrieve.return_value = Mock(id='')
mock_refund_create.return_value = response
@@ -663,7 +663,7 @@ def test_void_error_response(
stripe_authorized_payment,
gateway_params):
payment = stripe_authorized_payment
- payment_info = create_payment_information(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)
@@ -672,7 +672,7 @@ def test_void_error_response(
response = void(payment_info, **gateway_params)
assert response['error'] == ERROR_MESSAGE
- assert response['transaction_id'] == ''
+ assert response['transaction_id'] == TRANSACTION_TOKEN
assert response['kind'] == TransactionKind.VOID
assert not response['is_success']
assert response['amount'] == payment.total
diff --git a/tests/test_payment.py b/tests/test_payment.py
index fdf2ef720a..df9377025e 100644
--- a/tests/test_payment.py
+++ b/tests/test_payment.py
@@ -834,6 +834,16 @@ def test_validate_gateway_response_not_json_serializable(gateway_response):
assert str(e.value) == 'Gateway response needs to be json serializable'
+def test_validate_gateway_response_incorrect_field_type(gateway_response):
+ gateway_response['amount'] = 'should-be-decimal'
+
+ with pytest.raises(GatewayError) as e:
+ validate_gateway_response(gateway_response)
+
+ assert str(e.value) == 'amount must be of type {}, was {}'.format(
+ Decimal, str)
+
+
@patch('saleor.payment.utils.get_payment_gateway')
def test_call_gateway_invalid_response(
mock_get_payment_gateway, payment_dummy):