python-redsys 1.2.1__tar.gz → 1.2.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,122 @@
1
+ Metadata-Version: 2.4
2
+ Name: python-redsys
3
+ Version: 1.2.3
4
+ Summary: A simple, lightweight client to handle payments through the RedSys platform.
5
+ License: MIT
6
+ License-File: LICENSE
7
+ Author: David Díaz
8
+ Author-email: d.diazp@gmail.com
9
+ Requires-Python: >=3.8,<4.0
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.8
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Programming Language :: Python :: 3.15
22
+ Requires-Dist: pycryptodome (>=3.19.1,<4.0.0)
23
+ Project-URL: Homepage, https://github.com/ddiazpinto/python-redsys
24
+ Description-Content-Type: text/markdown
25
+
26
+ # Welcome to python-redsys!
27
+
28
+ [![CI](https://github.com/ddiazpinto/python-redsys/actions/workflows/python-app.yml/badge.svg?branch=release/1.x)](https://github.com/ddiazpinto/python-redsys/actions/workflows/python-app.yml?query=branch%3Arelease%2F1.x) [![PyPI](https://img.shields.io/pypi/v/python-redsys.svg)](https://pypi.org/project/python-redsys/) ![Python 3.8+](https://img.shields.io/badge/python-3.8%2B-blue.svg) [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/ddiazpinto/python-redsys/blob/release/1.x/LICENSE)
29
+
30
+ A simple, lightweight client to handle payments through the RedSys platform, using its *redirect connection* (browser form POST).
31
+
32
+ The library only builds the signed request and verifies/parses the response. It makes no network or browser calls of its own: the payment form is submitted from the cardholder's browser.
33
+
34
+ ## Installation
35
+
36
+ ```bash
37
+ pip install "python-redsys>=1.2,<2"
38
+
39
+ # or with Poetry
40
+ poetry add "python-redsys@^1.2"
41
+ ```
42
+
43
+ Requires Python 3.8+. Runtime dependency: `pycryptodome`.
44
+
45
+ ## Usage
46
+
47
+ The client prepares a request from a dict of parameters and verifies the response. Parameter values are validated on construction (`ValueError` on an unknown parameter or an invalid value, `TypeError` when `amount` is not a `Decimal`); `order` has 12 characters (4 digits followed by 8 alphanumerics), and `amount` is a `Decimal`, serialized to integer minor units on the wire. The allowed values for `currency`, `transaction_type` and `consumer_language` are in `redsys.constants`.
48
+
49
+ ## Using *redirect connection*
50
+
51
+ ### 1. Build a signed request
52
+
53
+ ```python
54
+ from decimal import Decimal, ROUND_HALF_UP
55
+ from redsys.client import RedirectClient
56
+ from redsys.constants import EUR, STANDARD_PAYMENT
57
+
58
+ client = RedirectClient(secret_key="sq7HjrUOBfKmC576ILgskD5srU870gJ7")
59
+
60
+ post_parameters = client.prepare_request({
61
+ "merchant_code": "999008881",
62
+ "terminal": "1",
63
+ "transaction_type": STANDARD_PAYMENT,
64
+ "currency": EUR,
65
+ "order": "000000000001",
66
+ # The amount is a Decimal; pre-quantize to two decimals.
67
+ "amount": Decimal("10.56489").quantize(Decimal(".01"), ROUND_HALF_UP),
68
+ "merchant_url": "https://example.com/redsys/response",
69
+ "url_ok": "https://example.com/ok",
70
+ "url_ko": "https://example.com/ko",
71
+ "merchant_name": "Example Commerce",
72
+ "product_description": "Products of Example Commerce",
73
+ }) # Ds_SignatureVersion / Ds_MerchantParameters / Ds_Signature
74
+ ```
75
+
76
+ The secret key, merchant code `999008881` and terminal `1` are the RedSys public test merchant's. `Ds_MerchantParameters` and `Ds_Signature` are returned as `bytes`; decode them before rendering them in an HTML form.
77
+
78
+ Bizum: add `"payment_method": "z"` (and optionally `"mobile_number"`) to the parameters.
79
+
80
+ ### 2. Communication step
81
+
82
+ Auto-submit an HTML form (`method="POST"`) with the three `post_parameters` fields to the RedSys endpoint:
83
+
84
+ - Test: `https://sis-t.redsys.es:25443/sis/realizarPago`
85
+ - Production: `https://sis.redsys.es/sis/realizarPago`
86
+
87
+ RedSys notifies the result both as a server-to-server POST to `merchant_url` and as a browser redirect to `url_ok` / `url_ko`.
88
+
89
+ ### 3. Verify and read the response
90
+
91
+ `create_response()` takes the received `Ds_Signature` and `Ds_MerchantParameters`, verifies the signature before it reads any field, and raises `ValueError` on signature mismatch or a malformed payload: a `Ds_Signature` over 128 characters, a `Ds_MerchantParameters` over 128 KiB or that is not a Base64-encoded JSON object nested at most 32 levels, or a signed field that cannot be read.
92
+
93
+ ```python
94
+ response = client.create_response(signature, merchant_parameters) # as RedSys posted them back
95
+
96
+ if response.is_paid:
97
+ ... # actions after a successful payment
98
+ else:
99
+ raise Exception(f"declined with code {response.code}")
100
+ ```
101
+
102
+ Response predicates (per the RedSys documentation):
103
+
104
+ - `response.is_paid`: response code between 0 and 99.
105
+ - `response.is_canceled`: response code 400.
106
+ - `response.is_refunded`: response code 900.
107
+ - `response.is_authorized`: paid, refunded or canceled.
108
+
109
+ `response.code` is the RedSys code as an `int`, and `response.message` its Spanish description (`None` for a code without one). Decoded fields (`response.order`, `response.amount` as a `Decimal`, ...) read as attributes, `None` when absent; `response.parameters` holds every decoded parameter: listed ones under their attribute name (`amount`), unlisted ones under their original `Ds_*` key.
110
+
111
+ ## Signature version
112
+
113
+ The 1.x line signs with `HMAC_SHA256_V1` (3DES + HMAC-SHA256), the legacy scheme still accepted by RedSys. `HMAC_SHA512_V1` requires 2.x.
114
+
115
+ ## Support
116
+
117
+ The 1.x line receives fixes until 2026-12-31.
118
+
119
+ ## Contributing
120
+
121
+ Contributions that keep the *lightweight* philosophy are welcome.
122
+
@@ -0,0 +1,96 @@
1
+ # Welcome to python-redsys!
2
+
3
+ [![CI](https://github.com/ddiazpinto/python-redsys/actions/workflows/python-app.yml/badge.svg?branch=release/1.x)](https://github.com/ddiazpinto/python-redsys/actions/workflows/python-app.yml?query=branch%3Arelease%2F1.x) [![PyPI](https://img.shields.io/pypi/v/python-redsys.svg)](https://pypi.org/project/python-redsys/) ![Python 3.8+](https://img.shields.io/badge/python-3.8%2B-blue.svg) [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/ddiazpinto/python-redsys/blob/release/1.x/LICENSE)
4
+
5
+ A simple, lightweight client to handle payments through the RedSys platform, using its *redirect connection* (browser form POST).
6
+
7
+ The library only builds the signed request and verifies/parses the response. It makes no network or browser calls of its own: the payment form is submitted from the cardholder's browser.
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ pip install "python-redsys>=1.2,<2"
13
+
14
+ # or with Poetry
15
+ poetry add "python-redsys@^1.2"
16
+ ```
17
+
18
+ Requires Python 3.8+. Runtime dependency: `pycryptodome`.
19
+
20
+ ## Usage
21
+
22
+ The client prepares a request from a dict of parameters and verifies the response. Parameter values are validated on construction (`ValueError` on an unknown parameter or an invalid value, `TypeError` when `amount` is not a `Decimal`); `order` has 12 characters (4 digits followed by 8 alphanumerics), and `amount` is a `Decimal`, serialized to integer minor units on the wire. The allowed values for `currency`, `transaction_type` and `consumer_language` are in `redsys.constants`.
23
+
24
+ ## Using *redirect connection*
25
+
26
+ ### 1. Build a signed request
27
+
28
+ ```python
29
+ from decimal import Decimal, ROUND_HALF_UP
30
+ from redsys.client import RedirectClient
31
+ from redsys.constants import EUR, STANDARD_PAYMENT
32
+
33
+ client = RedirectClient(secret_key="sq7HjrUOBfKmC576ILgskD5srU870gJ7")
34
+
35
+ post_parameters = client.prepare_request({
36
+ "merchant_code": "999008881",
37
+ "terminal": "1",
38
+ "transaction_type": STANDARD_PAYMENT,
39
+ "currency": EUR,
40
+ "order": "000000000001",
41
+ # The amount is a Decimal; pre-quantize to two decimals.
42
+ "amount": Decimal("10.56489").quantize(Decimal(".01"), ROUND_HALF_UP),
43
+ "merchant_url": "https://example.com/redsys/response",
44
+ "url_ok": "https://example.com/ok",
45
+ "url_ko": "https://example.com/ko",
46
+ "merchant_name": "Example Commerce",
47
+ "product_description": "Products of Example Commerce",
48
+ }) # Ds_SignatureVersion / Ds_MerchantParameters / Ds_Signature
49
+ ```
50
+
51
+ The secret key, merchant code `999008881` and terminal `1` are the RedSys public test merchant's. `Ds_MerchantParameters` and `Ds_Signature` are returned as `bytes`; decode them before rendering them in an HTML form.
52
+
53
+ Bizum: add `"payment_method": "z"` (and optionally `"mobile_number"`) to the parameters.
54
+
55
+ ### 2. Communication step
56
+
57
+ Auto-submit an HTML form (`method="POST"`) with the three `post_parameters` fields to the RedSys endpoint:
58
+
59
+ - Test: `https://sis-t.redsys.es:25443/sis/realizarPago`
60
+ - Production: `https://sis.redsys.es/sis/realizarPago`
61
+
62
+ RedSys notifies the result both as a server-to-server POST to `merchant_url` and as a browser redirect to `url_ok` / `url_ko`.
63
+
64
+ ### 3. Verify and read the response
65
+
66
+ `create_response()` takes the received `Ds_Signature` and `Ds_MerchantParameters`, verifies the signature before it reads any field, and raises `ValueError` on signature mismatch or a malformed payload: a `Ds_Signature` over 128 characters, a `Ds_MerchantParameters` over 128 KiB or that is not a Base64-encoded JSON object nested at most 32 levels, or a signed field that cannot be read.
67
+
68
+ ```python
69
+ response = client.create_response(signature, merchant_parameters) # as RedSys posted them back
70
+
71
+ if response.is_paid:
72
+ ... # actions after a successful payment
73
+ else:
74
+ raise Exception(f"declined with code {response.code}")
75
+ ```
76
+
77
+ Response predicates (per the RedSys documentation):
78
+
79
+ - `response.is_paid`: response code between 0 and 99.
80
+ - `response.is_canceled`: response code 400.
81
+ - `response.is_refunded`: response code 900.
82
+ - `response.is_authorized`: paid, refunded or canceled.
83
+
84
+ `response.code` is the RedSys code as an `int`, and `response.message` its Spanish description (`None` for a code without one). Decoded fields (`response.order`, `response.amount` as a `Decimal`, ...) read as attributes, `None` when absent; `response.parameters` holds every decoded parameter: listed ones under their attribute name (`amount`), unlisted ones under their original `Ds_*` key.
85
+
86
+ ## Signature version
87
+
88
+ The 1.x line signs with `HMAC_SHA256_V1` (3DES + HMAC-SHA256), the legacy scheme still accepted by RedSys. `HMAC_SHA512_V1` requires 2.x.
89
+
90
+ ## Support
91
+
92
+ The 1.x line receives fixes until 2026-12-31.
93
+
94
+ ## Contributing
95
+
96
+ Contributions that keep the *lightweight* philosophy are welcome.
@@ -1,7 +1,7 @@
1
1
  [tool.poetry]
2
2
  name = "python-redsys"
3
- version = "1.2.1"
4
- description = "A simple, clean and less dependant client to handle payments through Redsys."
3
+ version = "1.2.3"
4
+ description = "A simple, lightweight client to handle payments through the RedSys platform."
5
5
  authors = ["David Díaz <d.diazp@gmail.com>", "Andrés Reverón Molina <andres@reveronmolina.me>"]
6
6
  license = "MIT"
7
7
  readme = "README.md"
@@ -17,14 +17,13 @@ packages = [
17
17
 
18
18
  [tool.poetry.dependencies]
19
19
  python = "^3.8"
20
- pycryptodome = "^3.19.0"
20
+ pycryptodome = "^3.19.1"
21
21
 
22
22
  [tool.poetry.dev-dependencies]
23
23
  pytest = "^7.4.2"
24
24
  pre-commit = "^3.5.0"
25
25
  pytest-cov = "^4.1.0"
26
26
  mypy = "^1.6.1"
27
- python-semantic-release = "^7.34.6"
28
27
  ruff = "^0.1.3"
29
28
 
30
29
  [tool.ruff]
@@ -40,15 +39,6 @@ indent-style = "space"
40
39
  [tool.ruff.isort]
41
40
  force-single-line = true
42
41
 
43
- [tool.semantic_release]
44
- version_variable = [
45
- "redsys/__init__.py:__version__",
46
- ]
47
- version_toml = ["pyproject.toml:tool.poetry.version"]
48
- upload_to_pypi = true
49
- upload_to_release = true
50
- build_command = "poetry build"
51
-
52
42
  [build-system]
53
43
  requires = ["poetry-core>=1.0.0"]
54
44
  build-backend = "poetry.core.masonry.api"
@@ -1,2 +1,2 @@
1
- __version__ = "1.2.1"
1
+ __version__ = "1.2.3"
2
2
  __version_info__ = tuple(int(num) if num.isdigit() else num for num in __version__.replace("-", ".", 1).split("."))
@@ -0,0 +1,152 @@
1
+ import base64
2
+ import hashlib
3
+ import hmac
4
+ import json
5
+ import re
6
+ from abc import ABC
7
+ from abc import abstractmethod
8
+ from itertools import accumulate
9
+ from operator import sub as subtract
10
+ from typing import Any
11
+ from typing import Dict
12
+
13
+ from Crypto.Cipher import DES3
14
+
15
+ from redsys.request import Request
16
+ from redsys.response import ORDER
17
+ from redsys.response import Response
18
+
19
+ # Calculated parameters
20
+ SIGNATURE_VERSION = "Ds_SignatureVersion"
21
+ MERCHANT_PARAMETERS = "Ds_MerchantParameters"
22
+ SIGNATURE = "Ds_Signature"
23
+ DEFAULT_SIGNATURE_VERSION = "HMAC_SHA256_V1"
24
+
25
+ # Real notifications take a few KiB; the caps bound the work done before the signature is checked.
26
+ _MAX_MERCHANT_PARAMETERS_LENGTH = 128 * 1024
27
+ _MAX_SIGNATURE_LENGTH = 128
28
+ # RedSys payloads nest two or three levels; deeper JSON can exhaust a small thread
29
+ # stack inside the C JSON decoder and kill the process.
30
+ _MAX_JSON_DEPTH = 32
31
+ _NOT_BRACKETS = bytes(sorted(set(range(256)) - set(b"[]{}")))
32
+ _BRACKET_WEIGHTS = bytes.maketrans(b"[{]}", b"\x02\x02\x00\x00")
33
+ _NOT_ALPHANUMERIC = re.compile(b"[^a-zA-Z0-9]")
34
+
35
+
36
+ def _json_depth_exceeds(text: bytes, limit: int) -> bool:
37
+ """Whether JSON text nests deeper than ``limit``; brackets inside strings do not count."""
38
+ if text.count(b"[") + text.count(b"{") <= limit:
39
+ return False
40
+ # Bytes operations only: the text may be attacker-sized, and a byte loop costs ten times more.
41
+ outside_strings = b"".join(text.replace(b"\\\\", b"").replace(b'\\"', b"").split(b'"')[::2])
42
+ # Opening brackets weigh 2 and closing ones 0: the running sum minus the position is the depth.
43
+ weights = outside_strings.translate(_BRACKET_WEIGHTS, _NOT_BRACKETS)
44
+ return max(map(subtract, accumulate(weights), range(1, len(weights) + 1)), default=0) > limit
45
+
46
+
47
+ def _received_field(value: str, name: str, max_length: int) -> bytes:
48
+ """A received Base64 field as bytes; Base64 is ASCII text."""
49
+ if not isinstance(value, str) or len(value) > max_length or not value.isascii():
50
+ raise ValueError(f"{name} is not Base64 text of at most {max_length} characters.")
51
+ return value.encode()
52
+
53
+
54
+ class Client(ABC):
55
+ """
56
+ Abstract class from which RedirectClient inherits.
57
+ It implements methods that may be used in future clients(i.e. rest).
58
+ """
59
+
60
+ def __init__(self, secret_key: str):
61
+ self.secret_key: bytes = secret_key.encode()
62
+
63
+ @abstractmethod
64
+ def create_response(self, signature, parameters):
65
+ raise NotImplementedError
66
+
67
+ @abstractmethod
68
+ def prepare_request(self, request):
69
+ raise NotImplementedError
70
+
71
+ @staticmethod
72
+ def encode_parameters(parameters: Dict[str, Any]) -> bytes:
73
+ """Encodes the merchant parameters in base64"""
74
+ return base64.b64encode(json.dumps(parameters).encode())
75
+
76
+ @staticmethod
77
+ def decode_parameters(parameters: bytes) -> Dict[str, Any]:
78
+ """Decodes the merchant parameters from base64; JSON nested deeper than any RedSys payload raises ValueError"""
79
+ text = base64.b64decode(parameters)
80
+ if _json_depth_exceeds(text, _MAX_JSON_DEPTH):
81
+ raise ValueError(f"JSON nests deeper than {_MAX_JSON_DEPTH} levels.")
82
+ return json.loads(text.decode())
83
+
84
+ @staticmethod
85
+ def sign_hmac256(encrypted_order: bytes, merchant_parameters: bytes) -> bytes:
86
+ """
87
+ Generates the encrypted signature using the 3DES-encrypted order
88
+ and base64-encoded merchant parameters
89
+ """
90
+ signature = hmac.new(encrypted_order, merchant_parameters, hashlib.sha256).digest()
91
+ return base64.b64encode(signature)
92
+
93
+ def encrypt_3DES(self, order: str) -> bytes:
94
+ """Encrypts(3DES algorithm) the payment order using the secret key"""
95
+ cipher = DES3.new(base64.b64decode(self.secret_key), DES3.MODE_CBC, IV=b"\0\0\0\0\0\0\0\0")
96
+ # the cipher needs to be passed 16 bytes,
97
+ # so "order" must be 16 bytes long,
98
+ # therefore we left-justify adding ceros
99
+ return cipher.encrypt(order.encode().ljust(16, b"\0"))
100
+
101
+ def generate_signature(self, order: str, merchant_parameters: bytes) -> bytes:
102
+ return self.sign_hmac256(self.encrypt_3DES(order), merchant_parameters)
103
+
104
+
105
+ class RedirectClient(Client):
106
+ def prepare_request(self, parameters: Dict[str, Any]) -> Dict[str, Any]:
107
+ """Takes the merchant parameters and returns the necessary parameters
108
+ to make the POST request to Redsys"""
109
+ request = Request(parameters)
110
+ merchant_parameters = self.encode_parameters(request.prepare_parameters())
111
+ signature = self.generate_signature(request.order, merchant_parameters)
112
+ return {
113
+ SIGNATURE_VERSION: DEFAULT_SIGNATURE_VERSION,
114
+ MERCHANT_PARAMETERS: merchant_parameters,
115
+ SIGNATURE: signature,
116
+ }
117
+
118
+ def create_response(
119
+ self,
120
+ signature: str,
121
+ merchant_parameters: str,
122
+ ) -> Response:
123
+ """
124
+ Decodes the Redsys response to check for validity.
125
+ Checks if the received signature corresponds to the sent signature.
126
+
127
+ Both the `signature` and `merchant parameters` are plain strings, not bytes.
128
+ The fields are read only after the signature matches; a malformed payload
129
+ raises `ValueError` too.
130
+ """
131
+ received_signature = _received_field(signature, SIGNATURE, _MAX_SIGNATURE_LENGTH)
132
+ encoded_parameters = _received_field(merchant_parameters, MERCHANT_PARAMETERS, _MAX_MERCHANT_PARAMETERS_LENGTH)
133
+ try:
134
+ decoded_parameters = self.decode_parameters(encoded_parameters)
135
+ except ValueError as error:
136
+ raise ValueError(f"{MERCHANT_PARAMETERS} is not a Base64-encoded JSON object: {error}") from error
137
+ if not isinstance(decoded_parameters, dict):
138
+ raise ValueError(f"{MERCHANT_PARAMETERS} is not a Base64-encoded JSON object.")
139
+ order = decoded_parameters.get(ORDER)
140
+ # encrypt_3DES takes at most 16 ASCII bytes; any other order cannot verify, so it signs as ''.
141
+ if not (isinstance(order, str) and order.isascii() and len(order) <= 16):
142
+ order = ""
143
+ calculated_signature = self.generate_signature(order, encoded_parameters)
144
+ # Signatures may arrive in URL-safe Base64; only the alphanumeric core is compared.
145
+ if not hmac.compare_digest(
146
+ _NOT_ALPHANUMERIC.sub(b"", received_signature), _NOT_ALPHANUMERIC.sub(b"", calculated_signature)
147
+ ):
148
+ raise ValueError("The provided signature is not valid.")
149
+ try:
150
+ return Response(decoded_parameters)
151
+ except (ValueError, ArithmeticError) as error:
152
+ raise ValueError(f"{MERCHANT_PARAMETERS} holds a field that is not valid.") from error
@@ -135,7 +135,10 @@ class Response:
135
135
 
136
136
  @property
137
137
  def message(self):
138
- return RESPONSE_MAP["0000"] if self.is_paid else RESPONSE_MAP[self.response]
138
+ if self.is_paid:
139
+ return RESPONSE_MAP["0000"]
140
+ # RedSys sends 4-digit codes ("0190"); the map keys drop the leading zeros ("190").
141
+ return RESPONSE_MAP.get(self.response) or RESPONSE_MAP.get(str(self.code))
139
142
 
140
143
  @property
141
144
  def parameters(self):
@@ -0,0 +1,211 @@
1
+ import base64
2
+ import hmac
3
+ import json
4
+ from decimal import ROUND_HALF_UP
5
+ from decimal import Decimal as D
6
+ from unittest import mock
7
+
8
+ import pytest
9
+
10
+ from redsys import client as client_module
11
+ from redsys.client import RedirectClient
12
+ from redsys.constants import EUR
13
+ from redsys.constants import STANDARD_PAYMENT
14
+ from redsys.request import Request
15
+
16
+
17
+ class TestRedirectClient:
18
+ @pytest.fixture(autouse=True)
19
+ def set_up(self):
20
+ secret_key = "sq7HjrUOBfKmC576ILgskD5srU870gJ7"
21
+ self.client = RedirectClient(secret_key)
22
+ self.parameters = {
23
+ "merchant_code": "100000001",
24
+ "terminal": "1",
25
+ "transaction_type": STANDARD_PAYMENT,
26
+ "currency": EUR,
27
+ "order": "000000000001",
28
+ "amount": D("10.56489").quantize(D(".01"), ROUND_HALF_UP),
29
+ "merchant_data": "test merchant data",
30
+ "merchant_name": "Example Commerce",
31
+ "titular": "Example Ltd.",
32
+ "product_description": "Products of Example Commerce",
33
+ "merchant_url": "https://example.com/redsys/response",
34
+ }
35
+ self.request = Request(self.parameters)
36
+ self.merchant_params = self.request.prepare_parameters()
37
+
38
+ def test_encode_parameters(self):
39
+ encoded_params = self.client.encode_parameters(self.merchant_params)
40
+ encoded_params_str = encoded_params.decode("UTF-8")
41
+ assert encoded_params_str.endswith("ZWRzeXMvcmVzcG9uc2UifQ==")
42
+ assert len(encoded_params_str) == 628
43
+
44
+ def test_decode_parameters(self):
45
+ encoded_params = self.client.encode_parameters(self.merchant_params)
46
+ decoded_params = self.client.decode_parameters(encoded_params)
47
+ assert decoded_params == self.merchant_params
48
+
49
+ def test_encrypt_3DES(self):
50
+ encrypted_order = self.client.encrypt_3DES(self.request.order)
51
+ assert len(encrypted_order) == 16
52
+ assert str(encrypted_order) == "b'/\\x17\\\\6\\n\\x1aY\\xf3\\xd7\\xa5\\x97\\xb9\\xb6\\xe0\\x8dH'"
53
+
54
+ def test_sign_hmac256(self):
55
+ encrypted_order = self.client.encrypt_3DES(self.request.order)
56
+ encoded_params = self.client.encode_parameters(self.merchant_params)
57
+ signature = self.client.sign_hmac256(encrypted_order, encoded_params)
58
+ assert signature == b"a2F05DwuH5aXu5vD1IdjQ+NxaR0lPsRwksW1nr2Nzuw="
59
+
60
+ def test_prepare_request(self):
61
+ prepared_request = self.client.prepare_request(self.parameters)
62
+ assert len(prepared_request.keys()) == 3
63
+ assert prepared_request.get("Ds_Signature") == b"a2F05DwuH5aXu5vD1IdjQ+NxaR0lPsRwksW1nr2Nzuw="
64
+ pass
65
+
66
+ def test_create_response_valid(self):
67
+ merchant_parameters = {
68
+ "Ds_MerchantCode": "100000001",
69
+ "Ds_Terminal": "1",
70
+ "Ds_TransactionType": "0",
71
+ "Ds_Currency": 978,
72
+ "Ds_Order": "000000000001",
73
+ "Ds_Amount": 1056,
74
+ "Ds_MerchantData": "test merchant data",
75
+ }
76
+ encoded_params = self.client.encode_parameters(merchant_parameters)
77
+ signature = self.client.generate_signature(self.request.order, encoded_params)
78
+ response = self.client.create_response(signature.decode(), encoded_params.decode())
79
+ assert response._parameters.get("order") == merchant_parameters.get("Ds_Order")
80
+
81
+ def test_create_response_invalid(self):
82
+ merchant_parameters = {
83
+ "Ds_MerchantCode": "100000001",
84
+ "Ds_Terminal": "1",
85
+ "Ds_TransactionType": "0",
86
+ "Ds_Currency": 978,
87
+ "Ds_Order": "000000000001",
88
+ "Ds_Amount": 1056,
89
+ "Ds_MerchantData": "test merchant data",
90
+ }
91
+ encoded_params = self.client.encode_parameters(merchant_parameters)
92
+ bad_signature = b"sadfe2r3q2fdssaf3"
93
+ with pytest.raises(ValueError, match="The provided signature is not valid"):
94
+ self.client.create_response(bad_signature.decode(), encoded_params.decode())
95
+
96
+
97
+ SECRET = "sq7HjrUOBfKmC576ILgskD5srU870gJ7"
98
+ ORDER = "000000000001"
99
+
100
+
101
+ def _nested(depth):
102
+ value = []
103
+ for _ in range(depth - 1):
104
+ value = [value]
105
+ return value
106
+
107
+
108
+ class TestCreateResponseHardening:
109
+ @pytest.fixture(autouse=True)
110
+ def set_up(self):
111
+ self.client = RedirectClient(SECRET)
112
+
113
+ def _signed(self, fields, order=ORDER):
114
+ encoded = self.client.encode_parameters(fields)
115
+ return self.client.generate_signature(order, encoded).decode(), encoded.decode()
116
+
117
+ def _unsigned(self, raw):
118
+ return "x", base64.b64encode(raw).decode()
119
+
120
+ @pytest.mark.parametrize(
121
+ "signature, merchant_parameters",
122
+ [
123
+ (b"x", "e30="),
124
+ ("A" * 129, "e30="),
125
+ ("x", 7),
126
+ ("x", "ée30="),
127
+ ("x", "AAAA"),
128
+ ("x", base64.b64encode(b"\xff\xfe").decode()),
129
+ ("x", base64.b64encode(b"[1, 2]").decode()),
130
+ ],
131
+ ids=[
132
+ "signature bytes",
133
+ "signature too long",
134
+ "parameters not text",
135
+ "parameters not ascii",
136
+ "not base64 json",
137
+ "not utf-8",
138
+ "json array",
139
+ ],
140
+ )
141
+ def test_malformed_payload_raises_value_error(self, signature, merchant_parameters):
142
+ with pytest.raises(ValueError) as raised:
143
+ self.client.create_response(signature, merchant_parameters)
144
+ assert "The provided signature is not valid" not in str(raised.value)
145
+
146
+ def test_oversized_parameters_are_rejected_before_decoding(self, monkeypatch):
147
+ signature, merchant_parameters = self._signed({"Ds_Order": ORDER, "Ds_Response": "0000"})
148
+ monkeypatch.setattr(client_module, "_MAX_MERCHANT_PARAMETERS_LENGTH", len(merchant_parameters) - 1)
149
+ with mock.patch.object(RedirectClient, "decode_parameters") as decode, pytest.raises(
150
+ ValueError, match="at most"
151
+ ):
152
+ self.client.create_response(signature, merchant_parameters)
153
+ decode.assert_not_called()
154
+
155
+ def test_parameters_at_the_limit_are_accepted(self, monkeypatch):
156
+ signature, merchant_parameters = self._signed({"Ds_Order": ORDER, "Ds_Response": "0000"})
157
+ monkeypatch.setattr(client_module, "_MAX_MERCHANT_PARAMETERS_LENGTH", len(merchant_parameters))
158
+ assert self.client.create_response(signature, merchant_parameters).is_paid
159
+
160
+ def test_deep_nesting_is_rejected_before_parsing(self):
161
+ raw = json.dumps({"Ds_Order": ORDER, "x": _nested(32)}).encode()
162
+ with mock.patch("redsys.client.json.loads") as parse, pytest.raises(ValueError, match="nests deeper"):
163
+ self.client.create_response(*self._unsigned(raw))
164
+ parse.assert_not_called()
165
+
166
+ def test_nesting_at_the_limit_is_accepted(self):
167
+ signature, merchant_parameters = self._signed({"Ds_Order": ORDER, "Ds_Response": "0000", "x": _nested(31)})
168
+ assert self.client.create_response(signature, merchant_parameters).is_paid
169
+
170
+ @pytest.mark.parametrize(
171
+ "text, depth",
172
+ [
173
+ ('{"a": "[[[[", "b": [1, {"c": "]]]]"}]}', 3),
174
+ ('{"a": "x\\"[[", "b": "\\\\", "c": [[]], "d": "\\\\\\"]]"}', 3),
175
+ ('{"a": "' + "]" * 40 + '", "b": ' + "[" * 30 + "]" * 30 + "}", 31),
176
+ ],
177
+ )
178
+ def test_depth_ignores_brackets_inside_strings(self, text, depth):
179
+ padded = ("[" + text + "," + ",".join(["[]"] * 40) + "]").encode()
180
+ assert client_module._json_depth_exceeds(padded, depth + 1) is False
181
+ assert client_module._json_depth_exceeds(padded, depth) is True
182
+
183
+ @pytest.mark.parametrize("fields", [{"Ds_Response": "0000"}, {"Ds_Order": "1" * 20}, {"Ds_Order": 1}])
184
+ def test_order_that_cannot_sign_fails_verification(self, fields):
185
+ signature, merchant_parameters = self._signed(fields)
186
+ with pytest.raises(ValueError, match="The provided signature is not valid"):
187
+ self.client.create_response(signature, merchant_parameters)
188
+
189
+ def test_fields_are_not_read_without_a_matching_signature(self):
190
+ raw = json.dumps({"Ds_Order": ORDER, "Ds_Amount": "not a number"}).encode()
191
+ invalid = pytest.raises(ValueError, match="The provided signature is not valid")
192
+ with mock.patch("redsys.client.Response") as response, invalid:
193
+ self.client.create_response(*self._unsigned(raw))
194
+ response.assert_not_called()
195
+
196
+ def test_signed_invalid_field_raises_value_error(self):
197
+ signature, merchant_parameters = self._signed({"Ds_Order": ORDER, "Ds_Amount": "not a number"})
198
+ with pytest.raises(ValueError, match="holds a field"):
199
+ self.client.create_response(signature, merchant_parameters)
200
+
201
+ def test_signatures_compare_in_constant_time(self):
202
+ signature, merchant_parameters = self._signed({"Ds_Order": ORDER, "Ds_Response": "0000"})
203
+ with mock.patch("redsys.client.hmac.compare_digest", wraps=hmac.compare_digest) as compare:
204
+ self.client.create_response(signature, merchant_parameters)
205
+ compare.assert_called_once()
206
+
207
+ def test_url_safe_signature_is_accepted(self):
208
+ signature, merchant_parameters = self._signed({"Ds_Order": ORDER, "Ds_Response": "0000", "Ds_Amount": "1056"})
209
+ response = self.client.create_response(signature.replace("+", "-").replace("/", "_"), merchant_parameters)
210
+ assert response.is_paid
211
+ assert response.amount == D("10.56")
@@ -30,3 +30,10 @@ class TestResponse:
30
30
  assert "amount" not in second.parameters
31
31
  assert second.amount is None
32
32
  assert first.amount == Decimal("1.00")
33
+
34
+ def test_message_for_four_digit_codes(self):
35
+ assert Response({"Ds_Response": "0190"}).message == "Denegación del emisor sin especificar motivo"
36
+ assert Response({"Ds_Response": "0900"}).message == "Transacción autorizada para devoluciones y confirmaciones"
37
+ assert Response({"Ds_Response": "0400"}).message == "Transacción autorizada para anulaciones"
38
+ assert Response({"Ds_Response": "9915"}).message == "A petición del usuario se ha cancelado el pago"
39
+ assert Response({"Ds_Response": "0105"}).message is None
@@ -1,140 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: python-redsys
3
- Version: 1.2.1
4
- Summary: A simple, clean and less dependant client to handle payments through Redsys.
5
- License: MIT
6
- License-File: LICENSE
7
- Author: David Díaz
8
- Author-email: d.diazp@gmail.com
9
- Requires-Python: >=3.8,<4.0
10
- Classifier: Intended Audience :: Developers
11
- Classifier: License :: OSI Approved :: MIT License
12
- Classifier: Operating System :: OS Independent
13
- Classifier: Programming Language :: Python :: 3
14
- Classifier: Programming Language :: Python :: 3.8
15
- Classifier: Programming Language :: Python :: 3.9
16
- Classifier: Programming Language :: Python :: 3.10
17
- Classifier: Programming Language :: Python :: 3.11
18
- Classifier: Programming Language :: Python :: 3.12
19
- Classifier: Programming Language :: Python :: 3.13
20
- Classifier: Programming Language :: Python :: 3.14
21
- Classifier: Programming Language :: Python :: 3.15
22
- Requires-Dist: pycryptodome (>=3.19.0,<4.0.0)
23
- Project-URL: Homepage, https://github.com/ddiazpinto/python-redsys
24
- Description-Content-Type: text/markdown
25
-
26
-
27
- [![PyPI version](https://badge.fury.io/py/python-redsys.svg)](https://badge.fury.io/py/python-redsys)
28
-
29
- # Welcome to python-redsys!
30
-
31
- A simple, clean and less dependant client to handle payments through the
32
- Redsys platform using one of the available methods: _redirect connection_ or (secure method).
33
-
34
- The purpose of this library is to provide a normalized interface between
35
- Redsys and other Python applications.
36
-
37
- **About RedirectClient**
38
-
39
- Although _redirect connection_ depends on a webserver to resolve the
40
- communication step, the RedirectClient provided in this library does not
41
- assume any kind of procedure to resolve that step; it merely prepares
42
- the necessary parameters to make a request and handles the corresponding
43
- response parameters. That's what less dependant means.
44
-
45
- ## Example using _redirect connection_
46
-
47
- ### 0. Install python-redsys
48
-
49
- You can add python-redsys to your project with pip:
50
- > pip install python-redsys
51
-
52
- Or with poetry:
53
- > poetry add python-redsys
54
-
55
- ### 1. Instantiate the redirect client
56
-
57
- ```python
58
- from decimal import Decimal as D, ROUND_HALF_UP
59
- from redsys.constants import EUR, STANDARD_PAYMENT
60
- from redsys.client import RedirectClient
61
-
62
- secret_key = "123456789abcdef"
63
- client = RedirectClient(secret_key)
64
- ```
65
-
66
- ### 2. Set up the request parameters
67
-
68
- ```python
69
- parameters = {
70
- "merchant_code": "100000001",
71
- "terminal": "1",
72
- "transaction_type": STANDARD_PAYMENT,
73
- "currency": EUR,
74
- "order": "000000001",
75
- "amount": D("10.56489").quantize(D(".01"), ROUND_HALF_UP),
76
- "merchant_data": "test merchant data",
77
- "merchant_name": "Example Commerce",
78
- "titular": "Example Ltd.",
79
- "product_description": "Products of Example Commerce",
80
- "merchant_url": "https://example.com/redsys/response",
81
- }
82
- ```
83
-
84
- ### 3. Prepare the request
85
-
86
- This method returns a dict with the necessary post parameters that are
87
- needed during the communication step.
88
-
89
- ```python
90
- args = client.prepare_request(parameters)
91
- ```
92
-
93
- ### 4. Communication step
94
-
95
- Redirect the _user-agent_ to the corresponding Redsys' endpoint using
96
- the post parameters given in the previous step.
97
-
98
- After the payment process is finished, Redsys will respond making a
99
- request to the `merchant_url` defined in step 2.
100
-
101
- ### 5. Create and check the response
102
-
103
- Create the response object using the received parameters from Redsys.
104
- The method `create_response()` throws a `ValueError` in case the
105
- received signature is not equal to the calculated one using the
106
- given `merchant_parameters`. This normally means that the response **is
107
- not coming from Redsys** or that it **has been compromised**.
108
-
109
- ```python
110
- signature = "YqFenHc2HpB273l8c995...."
111
- merchant_parameters = "AndvIh66VZdkC5TG3nYL5j4XfCnFFbo3VkOu9TAeTs58fxddgc..."
112
- response = client.create_response(signature, merchant_parameters)
113
- if response.is_paid:
114
- # Do the corresponding actions after a successful payment
115
- else:
116
- # Do the corresponding actions after a failed payment
117
- raise Exception(response.code, response.message)
118
- ```
119
-
120
- **Methods for checking the response:**
121
-
122
- According to the Redsys documentation:
123
-
124
- - `response.is_paid`: Returns `True` if the response code is
125
- between 0 and 99 (both included).
126
- - `response.is_canceled`: Returns `True` if the response code
127
- is 400.
128
- - `response.is_refunded`: Returns `True` if the response code
129
- is 900.
130
- - `response.is_authorized`: Returns `True` if the response is
131
- **paid**, **refunded** or **canceled**.
132
-
133
- Also, you can directly access the code or the message defined in Redsys
134
- documentation using `response.code` or `response.message`.
135
-
136
- ## Contributions
137
-
138
- Please, feel free to send any contribution that maintains the _less
139
- dependant_ philosophy.
140
-
@@ -1,114 +0,0 @@
1
-
2
- [![PyPI version](https://badge.fury.io/py/python-redsys.svg)](https://badge.fury.io/py/python-redsys)
3
-
4
- # Welcome to python-redsys!
5
-
6
- A simple, clean and less dependant client to handle payments through the
7
- Redsys platform using one of the available methods: _redirect connection_ or (secure method).
8
-
9
- The purpose of this library is to provide a normalized interface between
10
- Redsys and other Python applications.
11
-
12
- **About RedirectClient**
13
-
14
- Although _redirect connection_ depends on a webserver to resolve the
15
- communication step, the RedirectClient provided in this library does not
16
- assume any kind of procedure to resolve that step; it merely prepares
17
- the necessary parameters to make a request and handles the corresponding
18
- response parameters. That's what less dependant means.
19
-
20
- ## Example using _redirect connection_
21
-
22
- ### 0. Install python-redsys
23
-
24
- You can add python-redsys to your project with pip:
25
- > pip install python-redsys
26
-
27
- Or with poetry:
28
- > poetry add python-redsys
29
-
30
- ### 1. Instantiate the redirect client
31
-
32
- ```python
33
- from decimal import Decimal as D, ROUND_HALF_UP
34
- from redsys.constants import EUR, STANDARD_PAYMENT
35
- from redsys.client import RedirectClient
36
-
37
- secret_key = "123456789abcdef"
38
- client = RedirectClient(secret_key)
39
- ```
40
-
41
- ### 2. Set up the request parameters
42
-
43
- ```python
44
- parameters = {
45
- "merchant_code": "100000001",
46
- "terminal": "1",
47
- "transaction_type": STANDARD_PAYMENT,
48
- "currency": EUR,
49
- "order": "000000001",
50
- "amount": D("10.56489").quantize(D(".01"), ROUND_HALF_UP),
51
- "merchant_data": "test merchant data",
52
- "merchant_name": "Example Commerce",
53
- "titular": "Example Ltd.",
54
- "product_description": "Products of Example Commerce",
55
- "merchant_url": "https://example.com/redsys/response",
56
- }
57
- ```
58
-
59
- ### 3. Prepare the request
60
-
61
- This method returns a dict with the necessary post parameters that are
62
- needed during the communication step.
63
-
64
- ```python
65
- args = client.prepare_request(parameters)
66
- ```
67
-
68
- ### 4. Communication step
69
-
70
- Redirect the _user-agent_ to the corresponding Redsys' endpoint using
71
- the post parameters given in the previous step.
72
-
73
- After the payment process is finished, Redsys will respond making a
74
- request to the `merchant_url` defined in step 2.
75
-
76
- ### 5. Create and check the response
77
-
78
- Create the response object using the received parameters from Redsys.
79
- The method `create_response()` throws a `ValueError` in case the
80
- received signature is not equal to the calculated one using the
81
- given `merchant_parameters`. This normally means that the response **is
82
- not coming from Redsys** or that it **has been compromised**.
83
-
84
- ```python
85
- signature = "YqFenHc2HpB273l8c995...."
86
- merchant_parameters = "AndvIh66VZdkC5TG3nYL5j4XfCnFFbo3VkOu9TAeTs58fxddgc..."
87
- response = client.create_response(signature, merchant_parameters)
88
- if response.is_paid:
89
- # Do the corresponding actions after a successful payment
90
- else:
91
- # Do the corresponding actions after a failed payment
92
- raise Exception(response.code, response.message)
93
- ```
94
-
95
- **Methods for checking the response:**
96
-
97
- According to the Redsys documentation:
98
-
99
- - `response.is_paid`: Returns `True` if the response code is
100
- between 0 and 99 (both included).
101
- - `response.is_canceled`: Returns `True` if the response code
102
- is 400.
103
- - `response.is_refunded`: Returns `True` if the response code
104
- is 900.
105
- - `response.is_authorized`: Returns `True` if the response is
106
- **paid**, **refunded** or **canceled**.
107
-
108
- Also, you can directly access the code or the message defined in Redsys
109
- documentation using `response.code` or `response.message`.
110
-
111
- ## Contributions
112
-
113
- Please, feel free to send any contribution that maintains the _less
114
- dependant_ philosophy.
@@ -1,105 +0,0 @@
1
- import base64
2
- import hashlib
3
- import hmac
4
- import json
5
- import re
6
- from abc import ABC
7
- from abc import abstractmethod
8
- from typing import Any
9
- from typing import Dict
10
-
11
- from Crypto.Cipher import DES3
12
-
13
- from redsys.request import Request
14
- from redsys.response import Response
15
-
16
- # Calculated parameters
17
- SIGNATURE_VERSION = "Ds_SignatureVersion"
18
- MERCHANT_PARAMETERS = "Ds_MerchantParameters"
19
- SIGNATURE = "Ds_Signature"
20
- DEFAULT_SIGNATURE_VERSION = "HMAC_SHA256_V1"
21
-
22
-
23
- class Client(ABC):
24
- """
25
- Abstract class from which RedirectClient inherits.
26
- It implements methods that may be used in future clients(i.e. rest).
27
- """
28
-
29
- def __init__(self, secret_key: str):
30
- self.secret_key: bytes = secret_key.encode()
31
-
32
- @abstractmethod
33
- def create_response(self, signature, parameters):
34
- raise NotImplementedError
35
-
36
- @abstractmethod
37
- def prepare_request(self, request):
38
- raise NotImplementedError
39
-
40
- @staticmethod
41
- def encode_parameters(parameters: Dict[str, Any]) -> bytes:
42
- """Encodes the merchant parameters in base64"""
43
- return base64.b64encode(json.dumps(parameters).encode())
44
-
45
- @staticmethod
46
- def decode_parameters(parameters: bytes) -> Dict[str, Any]:
47
- """Decodes the merchant parameters from base64"""
48
- return json.loads(base64.b64decode(parameters).decode())
49
-
50
- @staticmethod
51
- def sign_hmac256(encrypted_order: bytes, merchant_parameters: bytes) -> bytes:
52
- """
53
- Generates the encrypted signature using the 3DES-encrypted order
54
- and base64-encoded merchant parameters
55
- """
56
- signature = hmac.new(encrypted_order, merchant_parameters, hashlib.sha256).digest()
57
- return base64.b64encode(signature)
58
-
59
- def encrypt_3DES(self, order: str) -> bytes:
60
- """Encrypts(3DES algorithm) the payment order using the secret key"""
61
- cipher = DES3.new(base64.b64decode(self.secret_key), DES3.MODE_CBC, IV=b"\0\0\0\0\0\0\0\0")
62
- # the cipher needs to be passed 16 bytes,
63
- # so "order" must be 16 bytes long,
64
- # therefore we left-justify adding ceros
65
- return cipher.encrypt(order.encode().ljust(16, b"\0"))
66
-
67
- def generate_signature(self, order: str, merchant_parameters: bytes) -> bytes:
68
- return self.sign_hmac256(self.encrypt_3DES(order), merchant_parameters)
69
-
70
-
71
- class RedirectClient(Client):
72
- def prepare_request(self, parameters: Dict[str, Any]) -> Dict[str, Any]:
73
- """Takes the merchant parameters and returns the necessary parameters
74
- to make the POST request to Redsys"""
75
- request = Request(parameters)
76
- merchant_parameters = self.encode_parameters(request.prepare_parameters())
77
- signature = self.generate_signature(request.order, merchant_parameters)
78
- return {
79
- SIGNATURE_VERSION: DEFAULT_SIGNATURE_VERSION,
80
- MERCHANT_PARAMETERS: merchant_parameters,
81
- SIGNATURE: signature,
82
- }
83
-
84
- def create_response(
85
- self,
86
- signature: str,
87
- merchant_parameters: str,
88
- ) -> Response:
89
- """
90
- Decodes the Redsys response to check for validity.
91
- Checks if the received signature corresponds to the sent signature.
92
-
93
- Both the `signature` and `merchant parameters` are plain strings, not bytes.
94
- """
95
- decoded_parameters = self.decode_parameters(merchant_parameters.encode())
96
- response = Response(decoded_parameters)
97
- calculated_signature = self.generate_signature(response.order, merchant_parameters.encode())
98
- # Remove any non-alphanumeric characters from the signature
99
- not_alphanumeric = re.compile("[^a-zA-Z0-9]")
100
- safe_signature = re.sub(not_alphanumeric, "", signature)
101
-
102
- safe_calculated_signature = re.sub(not_alphanumeric, "", calculated_signature.decode())
103
- if safe_signature != safe_calculated_signature:
104
- raise ValueError("The provided signature is not valid.")
105
- return response
@@ -1,89 +0,0 @@
1
- from decimal import ROUND_HALF_UP
2
- from decimal import Decimal as D
3
-
4
- import pytest
5
-
6
- from redsys.client import RedirectClient
7
- from redsys.constants import EUR
8
- from redsys.constants import STANDARD_PAYMENT
9
- from redsys.request import Request
10
-
11
-
12
- class TestRedirectClient:
13
- @pytest.fixture(autouse=True)
14
- def set_up(self):
15
- secret_key = "sq7HjrUOBfKmC576ILgskD5srU870gJ7"
16
- self.client = RedirectClient(secret_key)
17
- self.parameters = {
18
- "merchant_code": "100000001",
19
- "terminal": "1",
20
- "transaction_type": STANDARD_PAYMENT,
21
- "currency": EUR,
22
- "order": "000000000001",
23
- "amount": D("10.56489").quantize(D(".01"), ROUND_HALF_UP),
24
- "merchant_data": "test merchant data",
25
- "merchant_name": "Example Commerce",
26
- "titular": "Example Ltd.",
27
- "product_description": "Products of Example Commerce",
28
- "merchant_url": "https://example.com/redsys/response",
29
- }
30
- self.request = Request(self.parameters)
31
- self.merchant_params = self.request.prepare_parameters()
32
-
33
- def test_encode_parameters(self):
34
- encoded_params = self.client.encode_parameters(self.merchant_params)
35
- encoded_params_str = encoded_params.decode("UTF-8")
36
- assert encoded_params_str.endswith("ZWRzeXMvcmVzcG9uc2UifQ==")
37
- assert len(encoded_params_str) == 628
38
-
39
- def test_decode_parameters(self):
40
- encoded_params = self.client.encode_parameters(self.merchant_params)
41
- decoded_params = self.client.decode_parameters(encoded_params)
42
- assert decoded_params == self.merchant_params
43
-
44
- def test_encrypt_3DES(self):
45
- encrypted_order = self.client.encrypt_3DES(self.request.order)
46
- assert len(encrypted_order) == 16
47
- assert str(encrypted_order) == "b'/\\x17\\\\6\\n\\x1aY\\xf3\\xd7\\xa5\\x97\\xb9\\xb6\\xe0\\x8dH'"
48
-
49
- def test_sign_hmac256(self):
50
- encrypted_order = self.client.encrypt_3DES(self.request.order)
51
- encoded_params = self.client.encode_parameters(self.merchant_params)
52
- signature = self.client.sign_hmac256(encrypted_order, encoded_params)
53
- assert signature == b"a2F05DwuH5aXu5vD1IdjQ+NxaR0lPsRwksW1nr2Nzuw="
54
-
55
- def test_prepare_request(self):
56
- prepared_request = self.client.prepare_request(self.parameters)
57
- assert len(prepared_request.keys()) == 3
58
- assert prepared_request.get("Ds_Signature") == b"a2F05DwuH5aXu5vD1IdjQ+NxaR0lPsRwksW1nr2Nzuw="
59
- pass
60
-
61
- def test_create_response_valid(self):
62
- merchant_parameters = {
63
- "Ds_MerchantCode": "100000001",
64
- "Ds_Terminal": "1",
65
- "Ds_TransactionType": "0",
66
- "Ds_Currency": 978,
67
- "Ds_Order": "000000000001",
68
- "Ds_Amount": 1056,
69
- "Ds_MerchantData": "test merchant data",
70
- }
71
- encoded_params = self.client.encode_parameters(merchant_parameters)
72
- signature = self.client.generate_signature(self.request.order, encoded_params)
73
- response = self.client.create_response(signature.decode(), encoded_params.decode())
74
- assert response._parameters.get("order") == merchant_parameters.get("Ds_Order")
75
-
76
- def test_create_response_invalid(self):
77
- merchant_parameters = {
78
- "Ds_MerchantCode": "100000001",
79
- "Ds_Terminal": "1",
80
- "Ds_TransactionType": "0",
81
- "Ds_Currency": 978,
82
- "Ds_Order": "000000000001",
83
- "Ds_Amount": 1056,
84
- "Ds_MerchantData": "test merchant data",
85
- }
86
- encoded_params = self.client.encode_parameters(merchant_parameters)
87
- bad_signature = b"sadfe2r3q2fdssaf3"
88
- with pytest.raises(ValueError, match="The provided signature is not valid"):
89
- self.client.create_response(bad_signature.decode(), encoded_params.decode())
File without changes