python-redsys 2.2.0__py3-none-any.whl → 2.3.0__py3-none-any.whl
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.
- {python_redsys-2.2.0.dist-info → python_redsys-2.3.0.dist-info}/METADATA +19 -5
- {python_redsys-2.2.0.dist-info → python_redsys-2.3.0.dist-info}/RECORD +15 -13
- redsys/_deprecation.py +27 -0
- redsys/api/environments.py +17 -3
- redsys/api/languages.py +65 -2
- redsys/api/transactions.py +10 -3
- redsys/clients.py +122 -28
- redsys/codes.py +9 -11
- redsys/exceptions.py +1 -1
- redsys/models.py +31 -3
- redsys/testing.py +77 -0
- {python_redsys-2.2.0.dist-info → python_redsys-2.3.0.dist-info}/WHEEL +0 -0
- {python_redsys-2.2.0.dist-info → python_redsys-2.3.0.dist-info}/licenses/LICENSE +0 -0
- {python_redsys-2.2.0.dist-info → python_redsys-2.3.0.dist-info}/licenses/NOTICE +0 -0
- {python_redsys-2.2.0.dist-info → python_redsys-2.3.0.dist-info}/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: python-redsys
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.3.0
|
|
4
4
|
Summary: A simple, lightweight client to handle payments through the RedSys platform.
|
|
5
5
|
Author-email: David Díaz <d.diazp@gmail.com>
|
|
6
6
|
License-Expression: Apache-2.0
|
|
@@ -97,7 +97,7 @@ from redsys import emv3ds, threeds
|
|
|
97
97
|
card = dict(pan="4548810000000003", expiry_date="4912", cvv2="123")
|
|
98
98
|
operation = dict(order=generate_order(), amount=Decimal("10.56"))
|
|
99
99
|
|
|
100
|
-
config = client.
|
|
100
|
+
config = client.start_payment(**operation, **card).send()
|
|
101
101
|
# Optional 3DSMethod: the browser posts threeds.method_data(...) to config.three_ds_method_url.
|
|
102
102
|
|
|
103
103
|
authentication = threeds.authentication_data(
|
|
@@ -134,7 +134,7 @@ client.payment(
|
|
|
134
134
|
## Payment methods
|
|
135
135
|
|
|
136
136
|
- **Bizum, redirect:** `pay_methods=pay_methods.BIZUM` on `payment()`.
|
|
137
|
-
- **Bizum Request-to-Pay, direct:** the same, plus `bizum_mobile_number` and `endpoint=client.url(environments.
|
|
137
|
+
- **Bizum Request-to-Pay, direct:** the same, plus `bizum_mobile_number` and `endpoint=client.url(environments.RTP_OPERATION_PATH)`; read `response.rtp_status` and `response.rtp_response` (`redsys.bizum`).
|
|
138
138
|
- **PayGold link:** `pay_gold(customer_mobile=..., customer_sms_text=f"{paygold.SMS_AMOUNT} {paygold.SMS_URL}")`; the link is `response.url_pago_2_fases`.
|
|
139
139
|
- **Google Pay and Apple Pay:** `xpay_data` (or `xpay_decoded_data`) with `xpay_type=xpay.GOOGLE` and `xpay_origen=xpay.WEB`.
|
|
140
140
|
- **inSite:** `idoper=` with the token from RedSys's JavaScript, on a direct `payment()`.
|
|
@@ -149,6 +149,7 @@ client.payment(
|
|
|
149
149
|
| `signature_version=` | `HMAC_SHA512_V2` (default), `HMAC_SHA512_V1` or legacy `HMAC_SHA256_V1`, from `redsys.clients` |
|
|
150
150
|
| `module=` | `Ds_Merchant_Module` of every request: `python-redsys/<version>` by default, another text, or `None` to leave it out |
|
|
151
151
|
| `endpoint=` on an operation | Sends that request to another HTTPS URL; `client.url(path)` builds one |
|
|
152
|
+
| `consumer_language=` on an operation | Payment page language: `languages.from_iso("es-ES")` turns an ISO 639-1 code or a locale tag into its `redsys.languages` value, `languages.DEFAULT` for a language RedSys does not list |
|
|
152
153
|
|
|
153
154
|
Every documented value has a named constant in `redsys` (`transactions`, `currencies`, `languages`, `pay_methods`, `cof`, `sca`, `options`, `emv3ds`, `cards`, `responses`, ...). Use them instead of literals.
|
|
154
155
|
|
|
@@ -161,11 +162,24 @@ Fields are validated when the operation method is called, before anything is sig
|
|
|
161
162
|
| A field with the wrong type or format, a missing required field, a misspelled or 1.x field name, an unknown currency or transaction type | `pydantic.ValidationError`; `.errors()` lists each field |
|
|
162
163
|
| A transaction type that contradicts the operation or the redirect connection, a non-HTTPS `endpoint`, an invalid API key or environment | `redsys.exceptions.ValidationError` |
|
|
163
164
|
| A signature that does not match in `parse_response()` | `ValueError` |
|
|
165
|
+
| A payload in `parse_response()` or an answer in `send()` that is not a well-formed RedSys result, for example without a signature or not a Base64-encoded JSON object | `redsys.exceptions.ValidationError` |
|
|
164
166
|
| RedSys answers with an error code instead of a signed result | `redsys.exceptions.ResponseError`; `.error_code` holds the `SISnnnn` code |
|
|
165
167
|
| An HTTP error status from RedSys in `send()` | `httpx.HTTPStatusError` |
|
|
166
168
|
|
|
167
169
|
A parameter the library does not model yet can be passed by its wire name (`Ds_Merchant_...`): it is sent as given, with an `UnknownParameterWarning`.
|
|
168
170
|
|
|
171
|
+
## Testing
|
|
172
|
+
|
|
173
|
+
`redsys.testing.signed_response()` builds what RedSys posts to `merchant_url` or answers to a direct call, signed with the client's key, to test the code that receives it. `response` defaults to `"0000"`; other fields go by attribute or wire name, and `amount` in major units.
|
|
174
|
+
|
|
175
|
+
```python
|
|
176
|
+
from redsys import responses
|
|
177
|
+
from redsys.testing import signed_response
|
|
178
|
+
|
|
179
|
+
payload = signed_response(client, order="1234ABCD", amount=Decimal("10.56"), response=responses.DECLINED)
|
|
180
|
+
assert not client.parse_response(payload).is_paid()
|
|
181
|
+
```
|
|
182
|
+
|
|
169
183
|
## Response codes
|
|
170
184
|
|
|
171
185
|
`response.response_code` is the integer `Ds_Response`; `response.is_paid()` (0 to 99), `is_refunded()` (900), `is_canceled()` (400) and `is_authorized()` (any of them) cover the common outcomes. `response.describe(language)` and `redsys.codes.describe(code, language)` give the meaning of any `Ds_Response`, `SISnnnn` or Bizum `BIZnnnnn` code. Table: [`docs/response-codes.md`](docs/response-codes.md).
|
|
@@ -174,7 +188,7 @@ A parameter the library does not model yet can be passed by its wire name (`Ds_M
|
|
|
174
188
|
|
|
175
189
|
| | |
|
|
176
190
|
|---|---|
|
|
177
|
-
| Version | 2.
|
|
191
|
+
| Version | 2.3.0; 1.x receives fixes until 2026-12-31 ([migration guide](docs/migration-1x-to-2x.md)) |
|
|
178
192
|
| Python | 3.10 to 3.15 |
|
|
179
193
|
| RedSys documents followed | Redirection guide 4.2, REST guide 4.0.1, Bizum guide 2.6, inSite guide 4.1, PayGold guide 1.8.2, Google Pay guide 1.9, Apple Pay guide 3.2, "Parámetros de entrada y salida" page |
|
|
180
194
|
| Verified against the RedSys test environment | Redirect in a browser with the 3DS challenge; direct end to end (frictionless and challenged 3DS, 3DSMethod, refund, void, payment cancellation, stored-card merchant-initiated charge), in all three signature versions |
|
|
@@ -183,5 +197,5 @@ A parameter the library does not model yet can be passed by its wire name (`Ds_M
|
|
|
183
197
|
|
|
184
198
|
- [`docs/redirect-connection.md`](docs/redirect-connection.md) and [`docs/direct-connection.md`](docs/direct-connection.md): protocol reference for each connection.
|
|
185
199
|
- [`docs/response-codes.md`](docs/response-codes.md): response, SIS and Bizum codes.
|
|
186
|
-
- [`docs/official-libraries.md`](docs/official-libraries.md):
|
|
200
|
+
- [`docs/official-libraries.md`](docs/official-libraries.md): RedSys's names (operations, endpoints, the libraries' concepts) and their python-redsys equivalents, including the names deprecated until 3.0.
|
|
187
201
|
- [`CONTRIBUTING.md`](CONTRIBUTING.md): development setup, checks and live tests.
|
|
@@ -1,15 +1,17 @@
|
|
|
1
|
-
python_redsys-2.
|
|
2
|
-
python_redsys-2.
|
|
1
|
+
python_redsys-2.3.0.dist-info/licenses/LICENSE,sha256=qsc7MUj20dcRHbyjIJn2jSbGRMaBOuHk8F9leaomY_4,11360
|
|
2
|
+
python_redsys-2.3.0.dist-info/licenses/NOTICE,sha256=6tlv5QuzsbfmGxsQNEcN7Uopzyp7vgD54xb-_L4DGyE,201
|
|
3
3
|
redsys/__init__.py,sha256=pLpynJ40Qpr4yM9TX8MZ0pTrbl7TkbVp9cQog1NA-hI,605
|
|
4
4
|
redsys/_code_texts.py,sha256=NLkVpNRNphxWIbvBYBJ96xFwrb_fbioEYXkBfKdKxEI,197037
|
|
5
|
-
redsys/
|
|
6
|
-
redsys/
|
|
5
|
+
redsys/_deprecation.py,sha256=Gpoycufexm2je_m5d6OU9lYsYt91dAc2Kh5-upjN-Ek,1077
|
|
6
|
+
redsys/clients.py,sha256=tEX560-y5Z5My8PDFoSUKg_EXT6nRkCIi9mICjn0vFU,24436
|
|
7
|
+
redsys/codes.py,sha256=mQPAsqidfMC5allCfoLfnmZ3Qun47wKUFeYmt_qc-jE,2604
|
|
7
8
|
redsys/crypto.py,sha256=FJxYzhqarhaIDwFxTlk7JFNOEXM2_AZ1TAh325sHC7k,5438
|
|
8
|
-
redsys/exceptions.py,sha256=
|
|
9
|
-
redsys/models.py,sha256=
|
|
9
|
+
redsys/exceptions.py,sha256=vq_RjtAcRURnLTIfzOPPU2O_97p1MWNWk8zW1WjgKHU,785
|
|
10
|
+
redsys/models.py,sha256=9ph9-pNjF_Ro_zrstK3yD11tqyr5RI249AB2lZow1o4,28898
|
|
10
11
|
redsys/orders.py,sha256=ryYlu8wnbudQNeaUB1bKXg2WxHTzWjv-h_iu3ZguV60,786
|
|
11
12
|
redsys/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
|
|
12
13
|
redsys/request.py,sha256=5SxS3s2URXS_dVk5HaYO-o9tyw4PkWwsKKaQC9J-5GY,2356
|
|
14
|
+
redsys/testing.py,sha256=h7NCgpf4ngNEeZL7A8ScR5C26n7W61B68DPJ5xWEh6Y,3436
|
|
13
15
|
redsys/threeds.py,sha256=wtGcduv9a84S7CKL8k1kA_q_5o98L5AGYM32OeGNQ9I,2589
|
|
14
16
|
redsys/api/__init__.py,sha256=ORl2UtMhq3z51luED3tFr7n98KEl9IpuDHUfxJ_F8So,81
|
|
15
17
|
redsys/api/bizum.py,sha256=WkfhGx5pmvIxFG9-NkjaBnC3ccKH37Kf1zbaFbdpB4k,1934
|
|
@@ -17,8 +19,8 @@ redsys/api/cards.py,sha256=iGRQDf6sjSEhmsgbpM3DlRcnLk-OhGbWHQSlAT4OmjM,1069
|
|
|
17
19
|
redsys/api/cof.py,sha256=fEf9ugVvOMs-jAzXkXDQl4NshyZuSYvbYfqnRH8otrk,660
|
|
18
20
|
redsys/api/currencies.py,sha256=pjJf64k5nVuvG3N99AUjPN2BBTzlwUBEO9Co76CGRus,999
|
|
19
21
|
redsys/api/emv3ds.py,sha256=U3nfkOIobMBk8UPCjt_6yZcAEpvOM6J0Tq4B_h02T_c,3160
|
|
20
|
-
redsys/api/environments.py,sha256
|
|
21
|
-
redsys/api/languages.py,sha256=
|
|
22
|
+
redsys/api/environments.py,sha256=O5I2gEW8alD921KV3EtuKKmHMM1ERtigk_1sOiRzCrQ,1619
|
|
23
|
+
redsys/api/languages.py,sha256=a-WIzS0vsyuD9cqD9agYJDRKyFxrnOi7M4u_6TImemc,2656
|
|
22
24
|
redsys/api/options.py,sha256=2Bw_IIlso8Lep7mpOMMHK7OzMLdlmhYRT-WSkTFa1GM,1156
|
|
23
25
|
redsys/api/pay_methods.py,sha256=LTjmAf0fKDZg6HEDhRHyGdtB8fOjeK99exQbF8oMbug,730
|
|
24
26
|
redsys/api/paygold.py,sha256=YGEnbOpjpt6PKG8zkUTwLQ6w5198BJSJ4yzt6T7SJXs,1125
|
|
@@ -26,9 +28,9 @@ redsys/api/processed_pay_methods.py,sha256=ZxN4GRi7iLbXldcoBbD1bIpXkzeYpyOX4QTzH
|
|
|
26
28
|
redsys/api/responses.py,sha256=qrS3YaM-NxBmXjRKPZlUgtcFl5aMWGADFKGIwEfCeXM,7333
|
|
27
29
|
redsys/api/sca.py,sha256=521jL7B_GZF-gymx3xDpEJCYhZVu5NSPM51TGEt0J34,1039
|
|
28
30
|
redsys/api/secure_payment.py,sha256=QxzhFMLHbCQdb1-J9kbfuWq4rp6URPUrY1yVMZ3Kv3c,403
|
|
29
|
-
redsys/api/transactions.py,sha256=
|
|
31
|
+
redsys/api/transactions.py,sha256=AE7X-0Oj6C0c0fKO0C4JXcH7DPOOhWKPLnKE7QSSfG4,2396
|
|
30
32
|
redsys/api/xpay.py,sha256=KRojPBEkS3yhvrVJCUBP_8L8gxfVImS13tbmESe46ew,693
|
|
31
|
-
python_redsys-2.
|
|
32
|
-
python_redsys-2.
|
|
33
|
-
python_redsys-2.
|
|
34
|
-
python_redsys-2.
|
|
33
|
+
python_redsys-2.3.0.dist-info/METADATA,sha256=NjgKqnkyoej3rJaKkE-Pa2ZZbiC4EtmjtIH_dN-if4Y,10956
|
|
34
|
+
python_redsys-2.3.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
35
|
+
python_redsys-2.3.0.dist-info/top_level.txt,sha256=79TrHj--FP5SDyZO42-NUsiYJmHiQX42txZigHOqghY,7
|
|
36
|
+
python_redsys-2.3.0.dist-info/RECORD,,
|
redsys/_deprecation.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Deprecated aliases of renamed public names; each warns and resolves to its replacement."""
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from typing import Any
|
|
6
|
+
from warnings import warn
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def deprecated(old: str, new: str, stacklevel: int = 3) -> None:
|
|
10
|
+
"""Warn that ``old`` goes away in 3.0; the default level points past the deprecated accessor to its caller."""
|
|
11
|
+
warn(f'{old} is deprecated and goes away in 3.0: use {new}.', DeprecationWarning, stacklevel=stacklevel)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def module_aliases(module: str, aliases: dict[str, str]) -> Callable[[str], Any]:
|
|
15
|
+
"""A module ``__getattr__`` that serves each old name in ``aliases`` as its new one.
|
|
16
|
+
|
|
17
|
+
Served names stay out of ``dir()``, so introspection does not warn.
|
|
18
|
+
"""
|
|
19
|
+
label = module.rpartition('.')[2]
|
|
20
|
+
|
|
21
|
+
def __getattr__(name: str) -> Any:
|
|
22
|
+
if name not in aliases:
|
|
23
|
+
raise AttributeError(f'module {module!r} has no attribute {name!r}')
|
|
24
|
+
deprecated(f'{label}.{name}', f'{label}.{aliases[name]}')
|
|
25
|
+
return getattr(sys.modules[module], aliases[name])
|
|
26
|
+
|
|
27
|
+
return __getattr__
|
redsys/api/environments.py
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
"""RedSys environments and their hosts."""
|
|
2
2
|
|
|
3
|
+
import typing as _typing
|
|
4
|
+
|
|
5
|
+
from redsys._deprecation import module_aliases as _module_aliases
|
|
6
|
+
|
|
3
7
|
DESA = 'DESA'
|
|
4
8
|
"""Development."""
|
|
5
9
|
|
|
@@ -22,16 +26,16 @@ HOSTS = {
|
|
|
22
26
|
REDIRECT_PATH = '/sis/realizarPago'
|
|
23
27
|
"""Redirect connection."""
|
|
24
28
|
|
|
25
|
-
|
|
29
|
+
START_PATH = '/sis/rest/iniciaPeticionREST'
|
|
26
30
|
"""Direct connection: 3-D Secure initialization."""
|
|
27
31
|
|
|
28
|
-
|
|
32
|
+
OPERATION_PATH = '/sis/rest/trataPeticionREST'
|
|
29
33
|
"""Direct connection: operations."""
|
|
30
34
|
|
|
31
35
|
RTP_CHECK_PATH = '/sis/rest/RTP/checkRtpUsuario'
|
|
32
36
|
"""Bizum Request-to-Pay: whether the customer can receive a payment request."""
|
|
33
37
|
|
|
34
|
-
|
|
38
|
+
RTP_OPERATION_PATH = '/sis/rest/RTP/trataPeticionREST'
|
|
35
39
|
"""Bizum Request-to-Pay: payment (types 0 and 7) and refund without original (type 34)."""
|
|
36
40
|
|
|
37
41
|
RTP_BACKUP_PATH = '/sis/rest/RTP/respaldarUsuarioRTP'
|
|
@@ -39,3 +43,13 @@ RTP_BACKUP_PATH = '/sis/rest/RTP/respaldarUsuarioRTP'
|
|
|
39
43
|
|
|
40
44
|
RTP_BACKUP_VALIDATION_PATH = '/sis/rest/RTP/validarRespaldoUsuarioRTP'
|
|
41
45
|
"""Bizum Request-to-Pay backup: validates the one-time password."""
|
|
46
|
+
|
|
47
|
+
# Type checkers see the deprecated names as plain aliases; at run time they warn.
|
|
48
|
+
if _typing.TYPE_CHECKING:
|
|
49
|
+
INICIA_PATH = START_PATH
|
|
50
|
+
TRATA_PATH = OPERATION_PATH
|
|
51
|
+
RTP_TRATA_PATH = RTP_OPERATION_PATH
|
|
52
|
+
else:
|
|
53
|
+
__getattr__ = _module_aliases(
|
|
54
|
+
__name__, {'INICIA_PATH': 'START_PATH', 'TRATA_PATH': 'OPERATION_PATH', 'RTP_TRATA_PATH': 'RTP_OPERATION_PATH'}
|
|
55
|
+
)
|
redsys/api/languages.py
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
"""Values of ``Ds_Merchant_ConsumerLanguage``; ``DEFAULT`` leaves the language undetermined."""
|
|
2
2
|
|
|
3
|
+
import typing as _typing
|
|
4
|
+
from re import split as _split
|
|
5
|
+
|
|
6
|
+
from redsys._deprecation import module_aliases as _module_aliases
|
|
7
|
+
|
|
3
8
|
DEFAULT = 0
|
|
4
9
|
SPANISH = 1
|
|
5
10
|
ENGLISH = 2
|
|
@@ -13,7 +18,7 @@ PORTUGUESE = 9
|
|
|
13
18
|
VALENCIAN = 10
|
|
14
19
|
POLISH = 11
|
|
15
20
|
GALICIAN = 12
|
|
16
|
-
|
|
21
|
+
BASQUE = 13
|
|
17
22
|
BULGARIAN = 100
|
|
18
23
|
CHINESE = 156
|
|
19
24
|
CROATIAN = 191
|
|
@@ -50,7 +55,7 @@ LANGUAGES = (
|
|
|
50
55
|
VALENCIAN,
|
|
51
56
|
POLISH,
|
|
52
57
|
GALICIAN,
|
|
53
|
-
|
|
58
|
+
BASQUE,
|
|
54
59
|
BULGARIAN,
|
|
55
60
|
CHINESE,
|
|
56
61
|
CROATIAN,
|
|
@@ -73,3 +78,61 @@ LANGUAGES = (
|
|
|
73
78
|
SLOVENIAN,
|
|
74
79
|
TURKISH,
|
|
75
80
|
)
|
|
81
|
+
|
|
82
|
+
_ISO_639_1 = {
|
|
83
|
+
'es': SPANISH,
|
|
84
|
+
'en': ENGLISH,
|
|
85
|
+
'ca': CATALAN,
|
|
86
|
+
'fr': FRENCH,
|
|
87
|
+
'de': GERMAN,
|
|
88
|
+
'nl': DUTCH,
|
|
89
|
+
'it': ITALIAN,
|
|
90
|
+
'sv': SWEDISH,
|
|
91
|
+
'pt': PORTUGUESE,
|
|
92
|
+
'pl': POLISH,
|
|
93
|
+
'gl': GALICIAN,
|
|
94
|
+
'eu': BASQUE,
|
|
95
|
+
'bg': BULGARIAN,
|
|
96
|
+
'zh': CHINESE,
|
|
97
|
+
'hr': CROATIAN,
|
|
98
|
+
'cs': CZECH,
|
|
99
|
+
'da': DANISH,
|
|
100
|
+
'et': ESTONIAN,
|
|
101
|
+
'fi': FINNISH,
|
|
102
|
+
'el': GREEK,
|
|
103
|
+
'hu': HUNGARIAN,
|
|
104
|
+
'hi': HINDI,
|
|
105
|
+
'ja': JAPANESE,
|
|
106
|
+
'ko': KOREAN,
|
|
107
|
+
'lv': LATVIAN,
|
|
108
|
+
'lt': LITHUANIAN,
|
|
109
|
+
'mt': MALTESE,
|
|
110
|
+
'ro': ROMANIAN,
|
|
111
|
+
'ru': RUSSIAN,
|
|
112
|
+
'ar': ARABIC,
|
|
113
|
+
'sk': SLOVAK,
|
|
114
|
+
'sl': SLOVENIAN,
|
|
115
|
+
'tr': TURKISH,
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def from_iso(code: str | None) -> int:
|
|
120
|
+
"""The value for an ISO 639-1 code or a locale tag: ``'es'``, ``'es-ES'``, ``'pt_BR'``, ``'es_ES.UTF-8'``.
|
|
121
|
+
|
|
122
|
+
The first subtag names the language, in any case. Catalan with the ``valencia`` variant
|
|
123
|
+
(``'ca-ES-valencia'``, ``'ca_ES@valencia'``) gives ``VALENCIAN``. A language RedSys does not
|
|
124
|
+
list, or anything that is not text, gives ``DEFAULT``.
|
|
125
|
+
"""
|
|
126
|
+
if not isinstance(code, str):
|
|
127
|
+
return DEFAULT
|
|
128
|
+
subtags = _split(r'[-_.@]', code.lower())
|
|
129
|
+
if subtags[0] == 'ca' and 'valencia' in subtags[1:]:
|
|
130
|
+
return VALENCIAN
|
|
131
|
+
return _ISO_639_1.get(subtags[0], DEFAULT)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
# Type checkers see the deprecated names as plain aliases; at run time they warn.
|
|
135
|
+
if _typing.TYPE_CHECKING:
|
|
136
|
+
EUSKERA = BASQUE
|
|
137
|
+
else:
|
|
138
|
+
__getattr__ = _module_aliases(__name__, {'EUSKERA': 'BASQUE'})
|
redsys/api/transactions.py
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
"""Values of ``Ds_Merchant_TransactionType``."""
|
|
2
2
|
|
|
3
|
+
import typing as _typing
|
|
4
|
+
|
|
5
|
+
from redsys._deprecation import module_aliases as _module_aliases
|
|
6
|
+
|
|
3
7
|
AUTHORIZATION = 0
|
|
4
8
|
"""Authorization."""
|
|
5
9
|
|
|
@@ -21,9 +25,6 @@ AUTHENTICATION_CONFIRMATION = 8
|
|
|
21
25
|
VOID = 9
|
|
22
26
|
"""Void of a preauthorization ("Anulación de preautorización")."""
|
|
23
27
|
|
|
24
|
-
CANCELLATION = VOID
|
|
25
|
-
"""Former name of ``VOID``."""
|
|
26
|
-
|
|
27
28
|
REPLACEMENT_PREAUTHORIZATION = 11
|
|
28
29
|
"""Replacement preauthorization: extends an existing preauthorization."""
|
|
29
30
|
|
|
@@ -89,3 +90,9 @@ REDIRECT_TRANSACTION_TYPES = (
|
|
|
89
90
|
REFUND_WITHOUT_ORIGINAL,
|
|
90
91
|
)
|
|
91
92
|
"""The types the redirect connection accepts."""
|
|
93
|
+
|
|
94
|
+
# Type checkers see the deprecated names as plain aliases; at run time they warn.
|
|
95
|
+
if _typing.TYPE_CHECKING:
|
|
96
|
+
CANCELLATION = VOID
|
|
97
|
+
else:
|
|
98
|
+
__getattr__ = _module_aliases(__name__, {'CANCELLATION': 'VOID'})
|
redsys/clients.py
CHANGED
|
@@ -11,6 +11,7 @@ ends in ``send()``. ``parse_response()`` verifies and parses a received result.
|
|
|
11
11
|
"""
|
|
12
12
|
|
|
13
13
|
from base64 import b64decode
|
|
14
|
+
from collections.abc import Mapping
|
|
14
15
|
from hmac import compare_digest
|
|
15
16
|
from importlib.metadata import PackageNotFoundError, version
|
|
16
17
|
from logging import getLogger
|
|
@@ -18,7 +19,10 @@ from re import fullmatch, sub
|
|
|
18
19
|
from urllib.parse import urlsplit
|
|
19
20
|
from warnings import warn
|
|
20
21
|
|
|
22
|
+
from pydantic import ValidationError as PydanticValidationError
|
|
23
|
+
|
|
21
24
|
from redsys import threeds
|
|
25
|
+
from redsys._deprecation import deprecated
|
|
22
26
|
from redsys.api import environments, transactions
|
|
23
27
|
from redsys.crypto import (
|
|
24
28
|
DEFAULT_SIGNATURE_VERSION,
|
|
@@ -39,6 +43,7 @@ from redsys.models import (
|
|
|
39
43
|
RedirectPreauthorizationMessage,
|
|
40
44
|
RefundMessage,
|
|
41
45
|
Response,
|
|
46
|
+
decode_merchant_parameters,
|
|
42
47
|
)
|
|
43
48
|
from redsys.request import (
|
|
44
49
|
MERCHANT_PARAMETERS,
|
|
@@ -63,6 +68,12 @@ DEFAULT_MODULE = _default_module()
|
|
|
63
68
|
# Seconds; ``send(timeout=...)`` overrides it.
|
|
64
69
|
DEFAULT_TIMEOUT = 30
|
|
65
70
|
|
|
71
|
+
# Real payloads take a few KiB; the caps bound the work done before the signature is checked.
|
|
72
|
+
_MAX_MERCHANT_PARAMETERS_LENGTH = 128 * 1024
|
|
73
|
+
_MAX_SIGNATURE_LENGTH = 128
|
|
74
|
+
|
|
75
|
+
_ORDER_WIRE_NAME = Response.model_fields['order'].alias
|
|
76
|
+
|
|
66
77
|
__all__ = [
|
|
67
78
|
'Client',
|
|
68
79
|
'RedirectClient',
|
|
@@ -93,6 +104,19 @@ def _normalize_signature(signature) -> str:
|
|
|
93
104
|
return sub(r'[^a-zA-Z0-9]', '', signature)
|
|
94
105
|
|
|
95
106
|
|
|
107
|
+
def _base64_text(value, name: str, max_length: int) -> bytes:
|
|
108
|
+
"""A received Base64 field as bytes; Base64 is ASCII, so anything else is malformed."""
|
|
109
|
+
if isinstance(value, (str, bytes, bytearray)) and len(value) > max_length:
|
|
110
|
+
raise ValidationError(f'{name} exceeds {max_length} characters.')
|
|
111
|
+
if isinstance(value, str) and value.isascii():
|
|
112
|
+
value = value.encode('ascii')
|
|
113
|
+
elif isinstance(value, bytearray):
|
|
114
|
+
value = bytes(value)
|
|
115
|
+
if not isinstance(value, bytes) or not value.isascii():
|
|
116
|
+
raise ValidationError(f'{name} is missing or is not Base64 text.')
|
|
117
|
+
return value
|
|
118
|
+
|
|
119
|
+
|
|
96
120
|
def _resolve_environment(environment: str | None, sandbox: bool | None) -> str:
|
|
97
121
|
"""The environment a client targets; ``sandbox`` means TEST when true and PROD when false."""
|
|
98
122
|
implied = None if sandbox is None else environments.TEST if sandbox else environments.PROD
|
|
@@ -188,7 +212,7 @@ class Client:
|
|
|
188
212
|
)
|
|
189
213
|
|
|
190
214
|
def url(self, path: str) -> str:
|
|
191
|
-
"""The client's environment host followed by ``path``, e.g. ``environments.
|
|
215
|
+
"""The client's environment host followed by ``path``, e.g. ``environments.RTP_OPERATION_PATH``."""
|
|
192
216
|
if not isinstance(path, str) or not path.startswith('/'):
|
|
193
217
|
raise ValidationError('path must start with "/".')
|
|
194
218
|
return f'{environments.HOSTS[self.environment]}{path}'
|
|
@@ -247,27 +271,50 @@ class Client:
|
|
|
247
271
|
return Request(merchant_parameters, signature, version, sender=sender, endpoint=endpoint)
|
|
248
272
|
|
|
249
273
|
# == Response parsing ==
|
|
250
|
-
def parse_response(self, payload:
|
|
274
|
+
def parse_response(self, payload: Mapping) -> Response:
|
|
251
275
|
"""Verify the signature and parse a received payload into a ``Response``.
|
|
252
276
|
|
|
253
277
|
Accepts both the redirect callback form fields and the direct REST JSON
|
|
254
|
-
body.
|
|
255
|
-
|
|
256
|
-
|
|
278
|
+
body. Fields are validated only after the signature matches. Raises
|
|
279
|
+
``ResponseError`` if RedSys answered with an error code instead of a
|
|
280
|
+
signed result, ``ValidationError`` if the payload is not a well-formed
|
|
281
|
+
RedSys result, and ``ValueError`` if the signature does not match (the
|
|
282
|
+
payload is not from RedSys or was tampered with).
|
|
257
283
|
"""
|
|
284
|
+
if not isinstance(payload, Mapping):
|
|
285
|
+
raise ValidationError('The payload must be a mapping of the received fields.')
|
|
258
286
|
if MERCHANT_PARAMETERS not in payload:
|
|
259
287
|
error_code = payload.get('errorCode') or payload.get('Ds_ErrorCode')
|
|
288
|
+
if not error_code:
|
|
289
|
+
raise ValidationError(f'The payload carries neither {MERCHANT_PARAMETERS} nor an error code.')
|
|
260
290
|
raise ResponseError(error_code, payload)
|
|
261
|
-
merchant_parameters =
|
|
262
|
-
|
|
263
|
-
|
|
291
|
+
merchant_parameters = _base64_text(
|
|
292
|
+
payload[MERCHANT_PARAMETERS], MERCHANT_PARAMETERS, _MAX_MERCHANT_PARAMETERS_LENGTH
|
|
293
|
+
)
|
|
294
|
+
signature = _base64_text(payload.get(SIGNATURE), SIGNATURE, _MAX_SIGNATURE_LENGTH)
|
|
264
295
|
version = payload.get(SIGNATURE_VERSION, DEFAULT_SIGNATURE_VERSION)
|
|
265
|
-
|
|
296
|
+
if version not in SIGNATURE_VERSIONS:
|
|
297
|
+
raise ValidationError(f'{SIGNATURE_VERSION} is not supported.')
|
|
298
|
+
try:
|
|
299
|
+
fields = decode_merchant_parameters(merchant_parameters)
|
|
300
|
+
except ValueError as error:
|
|
301
|
+
raise ValidationError(f'{MERCHANT_PARAMETERS} is not a Base64-encoded JSON object: {error}') from error
|
|
302
|
+
if not isinstance(fields, dict):
|
|
303
|
+
raise ValidationError(f'{MERCHANT_PARAMETERS} is not a Base64-encoded JSON object.')
|
|
266
304
|
# A signed result always carries Ds_Order; without it, '' makes verification fail.
|
|
267
|
-
|
|
268
|
-
|
|
305
|
+
order = fields.get(_ORDER_WIRE_NAME)
|
|
306
|
+
try:
|
|
307
|
+
expected = get_signer(self._secret_key, version).sign(
|
|
308
|
+
order if isinstance(order, str) else '', merchant_parameters
|
|
309
|
+
)
|
|
310
|
+
except UnicodeEncodeError as error:
|
|
311
|
+
raise ValidationError(f'{_ORDER_WIRE_NAME} is not valid text.') from error
|
|
312
|
+
if not compare_digest(_normalize_signature(signature), _normalize_signature(expected)):
|
|
269
313
|
raise ValueError('Signature is not valid.')
|
|
270
|
-
|
|
314
|
+
try:
|
|
315
|
+
return Response._from_fields(fields)
|
|
316
|
+
except (PydanticValidationError, ArithmeticError) as error:
|
|
317
|
+
raise ValidationError(f'{MERCHANT_PARAMETERS} holds a field that is not valid.') from error
|
|
271
318
|
|
|
272
319
|
|
|
273
320
|
class RedirectClient(Client):
|
|
@@ -306,16 +353,27 @@ def _require_httpx():
|
|
|
306
353
|
|
|
307
354
|
_EMV3DS_WIRE_NAME = 'Ds_Merchant_EMV3DS'
|
|
308
355
|
|
|
356
|
+
_RENAMED_MEMBERS = {
|
|
357
|
+
'inicia_endpoint': 'start_endpoint',
|
|
358
|
+
'inicia': 'start',
|
|
359
|
+
'inicia_payment': 'start_payment',
|
|
360
|
+
'inicia_preauthorization': 'start_preauthorization',
|
|
361
|
+
'inicia_authentication': 'start_authentication',
|
|
362
|
+
}
|
|
363
|
+
|
|
309
364
|
|
|
310
365
|
class _DirectBase(Client):
|
|
311
366
|
"""Operations of the REST direct connection, independent of the HTTP transport."""
|
|
312
367
|
|
|
313
368
|
# Endpoints per the REST guide 4.0.1 (RS.TE.CEL.MAN.0037).
|
|
314
|
-
_PATH = environments.
|
|
369
|
+
_PATH = environments.OPERATION_PATH
|
|
315
370
|
REAL_ENDPOINT = environments.HOSTS[environments.PROD] + _PATH
|
|
316
371
|
TEST_ENDPOINT = environments.HOSTS[environments.TEST] + _PATH
|
|
317
|
-
|
|
318
|
-
|
|
372
|
+
START_REAL_ENDPOINT = environments.HOSTS[environments.PROD] + environments.START_PATH
|
|
373
|
+
START_TEST_ENDPOINT = environments.HOSTS[environments.TEST] + environments.START_PATH
|
|
374
|
+
# Deprecated, without a warning: a class attribute that warns fires on introspection (help(), create_autospec).
|
|
375
|
+
INICIA_REAL_ENDPOINT = START_REAL_ENDPOINT
|
|
376
|
+
INICIA_TEST_ENDPOINT = START_TEST_ENDPOINT
|
|
319
377
|
|
|
320
378
|
_DEFAULT_MODEL = DirectPaymentMessage
|
|
321
379
|
_MODELS = {
|
|
@@ -330,9 +388,19 @@ class _DirectBase(Client):
|
|
|
330
388
|
transactions.AUTHENTICATION_CONFIRMATION_CANCELLATION: CancellationMessage,
|
|
331
389
|
}
|
|
332
390
|
|
|
391
|
+
def __init_subclass__(cls, **kwargs):
|
|
392
|
+
super().__init_subclass__(**kwargs)
|
|
393
|
+
for old, new in _RENAMED_MEMBERS.items():
|
|
394
|
+
if old in vars(cls):
|
|
395
|
+
warn(
|
|
396
|
+
f'{cls.__name__}.{old} overrides a deprecated name the client no longer calls: override {new}.',
|
|
397
|
+
DeprecationWarning,
|
|
398
|
+
stacklevel=2,
|
|
399
|
+
)
|
|
400
|
+
|
|
333
401
|
@property
|
|
334
|
-
def
|
|
335
|
-
return self.url(environments.
|
|
402
|
+
def start_endpoint(self) -> str:
|
|
403
|
+
return self.url(environments.START_PATH)
|
|
336
404
|
|
|
337
405
|
def payment(self, **fields) -> Request:
|
|
338
406
|
return self._operation(transactions.AUTHORIZATION, fields)
|
|
@@ -387,29 +455,51 @@ class _DirectBase(Client):
|
|
|
387
455
|
)
|
|
388
456
|
return self.void(**fields)
|
|
389
457
|
|
|
390
|
-
def
|
|
458
|
+
def start(self, **fields) -> Request:
|
|
391
459
|
"""3-D Secure initialization (iniciaPeticionREST) from the given fields, ``emv3ds`` included."""
|
|
392
460
|
fields = dict(fields)
|
|
393
461
|
endpoint = _endpoint_option(fields)
|
|
394
462
|
model = self._DEFAULT_MODEL(**self._inject(fields))
|
|
395
|
-
return self._prepare(model, endpoint=endpoint or self.
|
|
463
|
+
return self._prepare(model, endpoint=endpoint or self.start_endpoint)
|
|
396
464
|
|
|
397
|
-
def
|
|
465
|
+
def start_payment(self, **fields) -> Request:
|
|
398
466
|
"""3-D Secure step 1 for a payment; ``emv3ds`` defaults to ``threeds.card_data()``."""
|
|
399
|
-
return self.
|
|
467
|
+
return self._start(transactions.AUTHORIZATION, fields)
|
|
400
468
|
|
|
401
|
-
def
|
|
469
|
+
def start_preauthorization(self, **fields) -> Request:
|
|
402
470
|
"""3-D Secure step 1 for a preauthorization; ``emv3ds`` defaults to ``threeds.card_data()``."""
|
|
403
|
-
return self.
|
|
471
|
+
return self._start(transactions.PREAUTHORIZATION, fields)
|
|
404
472
|
|
|
405
|
-
def
|
|
473
|
+
def start_authentication(self, **fields) -> Request:
|
|
406
474
|
"""3-D Secure step 1 for an authentication; ``emv3ds`` defaults to ``threeds.card_data()``."""
|
|
407
|
-
return self.
|
|
475
|
+
return self._start(transactions.AUTHENTICATION, fields)
|
|
408
476
|
|
|
409
|
-
def
|
|
477
|
+
def _start(self, transaction_type: int, fields: dict) -> Request:
|
|
410
478
|
if 'emv3ds' not in fields and _EMV3DS_WIRE_NAME not in fields:
|
|
411
479
|
fields['emv3ds'] = threeds.card_data()
|
|
412
|
-
return self._operation(transaction_type, fields, endpoint=self.
|
|
480
|
+
return self._operation(transaction_type, fields, endpoint=self.start_endpoint)
|
|
481
|
+
|
|
482
|
+
# == Deprecated aliases ==
|
|
483
|
+
@property
|
|
484
|
+
def inicia_endpoint(self) -> str:
|
|
485
|
+
deprecated('inicia_endpoint', 'start_endpoint')
|
|
486
|
+
return self.start_endpoint
|
|
487
|
+
|
|
488
|
+
def inicia(self, **fields) -> Request:
|
|
489
|
+
deprecated('inicia()', 'start()')
|
|
490
|
+
return self.start(**fields)
|
|
491
|
+
|
|
492
|
+
def inicia_payment(self, **fields) -> Request:
|
|
493
|
+
deprecated('inicia_payment()', 'start_payment()')
|
|
494
|
+
return self.start_payment(**fields)
|
|
495
|
+
|
|
496
|
+
def inicia_preauthorization(self, **fields) -> Request:
|
|
497
|
+
deprecated('inicia_preauthorization()', 'start_preauthorization()')
|
|
498
|
+
return self.start_preauthorization(**fields)
|
|
499
|
+
|
|
500
|
+
def inicia_authentication(self, **fields) -> Request:
|
|
501
|
+
deprecated('inicia_authentication()', 'start_authentication()')
|
|
502
|
+
return self.start_authentication(**fields)
|
|
413
503
|
|
|
414
504
|
def challenge_response(
|
|
415
505
|
self, *, cres: str, protocol_version: str, transaction_type: int = transactions.AUTHORIZATION, **fields
|
|
@@ -430,7 +520,11 @@ class _DirectBase(Client):
|
|
|
430
520
|
http_response.raise_for_status()
|
|
431
521
|
transport = (http_response.status_code, dict(http_response.headers), http_response.text)
|
|
432
522
|
try:
|
|
433
|
-
|
|
523
|
+
body = http_response.json()
|
|
524
|
+
except ValueError as error:
|
|
525
|
+
raise ValidationError('The answer is not JSON.') from error
|
|
526
|
+
try:
|
|
527
|
+
response = self.parse_response(body)
|
|
434
528
|
except ResponseError as error:
|
|
435
529
|
error.http_status, error.http_headers, error.raw_body = transport
|
|
436
530
|
raise
|
redsys/codes.py
CHANGED
|
@@ -14,24 +14,21 @@ from redsys.api import languages, responses
|
|
|
14
14
|
|
|
15
15
|
# Position of each language in the (Spanish, Catalan, Galician, Basque, English) texts; Valencian reads the Catalan.
|
|
16
16
|
_TEXT_INDEX = {
|
|
17
|
-
'es': 0,
|
|
18
|
-
'ca': 1,
|
|
19
|
-
'va': 1,
|
|
20
|
-
'gl': 2,
|
|
21
|
-
'eu': 3,
|
|
22
|
-
'en': 4,
|
|
23
17
|
languages.SPANISH: 0,
|
|
24
18
|
languages.CATALAN: 1,
|
|
25
19
|
languages.VALENCIAN: 1,
|
|
26
20
|
languages.GALICIAN: 2,
|
|
27
|
-
languages.
|
|
21
|
+
languages.BASQUE: 3,
|
|
28
22
|
languages.ENGLISH: 4,
|
|
29
23
|
}
|
|
30
24
|
|
|
31
25
|
|
|
32
26
|
def _language_index(language) -> int | None:
|
|
33
27
|
if isinstance(language, str):
|
|
34
|
-
|
|
28
|
+
if language.isdigit():
|
|
29
|
+
language = int(language)
|
|
30
|
+
else:
|
|
31
|
+
language = languages.VALENCIAN if language.lower() == 'va' else languages.from_iso(language)
|
|
35
32
|
return _TEXT_INDEX.get(language)
|
|
36
33
|
|
|
37
34
|
|
|
@@ -62,9 +59,10 @@ def describe(code, language='es') -> str:
|
|
|
62
59
|
"""The meaning of a ``Ds_Response`` code, an ``SISnnnn`` error code or a Bizum ``BIZnnnnn`` code.
|
|
63
60
|
|
|
64
61
|
``code`` is an ``int`` or a ``str`` (``0``, ``'0000'``, ``'SIS0051'``, ``'BIZ00009'``). ``language``
|
|
65
|
-
is an ISO code (``'es'``, ``'
|
|
66
|
-
|
|
67
|
-
Returns ``''`` for an unknown
|
|
62
|
+
is an ISO code or a locale tag, read by ``languages.from_iso`` (``'es'``, ``'es-ES'``, ``'en'``, ``'ca'``,
|
|
63
|
+
``'gl'``, ``'eu'``; ``'va'`` reads the Catalan), or RedSys's numeric one (``languages.SPANISH``,
|
|
64
|
+
``ENGLISH``, ``CATALAN``, ``VALENCIAN``, ``GALICIAN``, ``BASQUE``). Returns ``''`` for an unknown
|
|
65
|
+
code or language.
|
|
68
66
|
"""
|
|
69
67
|
texts = _texts(code)
|
|
70
68
|
index = _language_index(language)
|
redsys/exceptions.py
CHANGED
|
@@ -15,7 +15,7 @@ class ResponseError(RedsysError):
|
|
|
15
15
|
|
|
16
16
|
|
|
17
17
|
class ValidationError(RedsysError, ValueError):
|
|
18
|
-
"""
|
|
18
|
+
"""Rejected input: a client option or operation fields RedSys does not accept, or a malformed received payload."""
|
|
19
19
|
|
|
20
20
|
|
|
21
21
|
class UnknownParameterWarning(UserWarning):
|
redsys/models.py
CHANGED
|
@@ -20,7 +20,9 @@ dict with ``model_validate``. Field constraints follow these RedSys documents:
|
|
|
20
20
|
|
|
21
21
|
from base64 import b64decode, b64encode
|
|
22
22
|
from decimal import Decimal
|
|
23
|
+
from itertools import accumulate
|
|
23
24
|
from json import dumps, loads
|
|
25
|
+
from operator import sub as subtract
|
|
24
26
|
from typing import Any
|
|
25
27
|
from warnings import warn
|
|
26
28
|
|
|
@@ -48,13 +50,35 @@ _LEGACY_FIELDS: dict[str, str] = {
|
|
|
48
50
|
}
|
|
49
51
|
|
|
50
52
|
|
|
53
|
+
# RedSys payloads nest two or three levels; deeper JSON can exhaust a small thread
|
|
54
|
+
# stack inside the C JSON decoder and kill the process.
|
|
55
|
+
_MAX_JSON_DEPTH = 32
|
|
56
|
+
_NOT_BRACKETS = bytes(sorted(set(range(256)) - set(b'[]{}')))
|
|
57
|
+
_BRACKET_WEIGHTS = bytes.maketrans(b'[{]}', b'\x02\x02\x00\x00')
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _json_depth_exceeds(text: bytes, limit: int) -> bool:
|
|
61
|
+
"""Whether JSON text nests deeper than ``limit``; brackets inside strings do not count."""
|
|
62
|
+
if text.count(b'[') + text.count(b'{') <= limit:
|
|
63
|
+
return False
|
|
64
|
+
# Bytes operations only: the text may be attacker-sized, and a byte loop costs ten times more.
|
|
65
|
+
outside_strings = b''.join(text.replace(b'\\\\', b'').replace(b'\\"', b'').split(b'"')[::2])
|
|
66
|
+
# Opening brackets weigh 2 and closing ones 0: the running sum minus the position is the depth.
|
|
67
|
+
weights = outside_strings.translate(_BRACKET_WEIGHTS, _NOT_BRACKETS)
|
|
68
|
+
return max(map(subtract, accumulate(weights), range(1, len(weights) + 1)), default=0) > limit
|
|
69
|
+
|
|
70
|
+
|
|
51
71
|
def decode_merchant_parameters(data: bytes) -> dict:
|
|
52
72
|
"""Decode a Ds_MerchantParameters string in standard or URL-safe Base64, padded or not.
|
|
53
73
|
|
|
54
74
|
RedSys mixes the forms by signature version (HMAC_SHA512_V2 responses come unpadded).
|
|
75
|
+
JSON nested deeper than any RedSys payload raises ``ValueError`` before it is parsed.
|
|
55
76
|
"""
|
|
56
77
|
data = data.replace(b'-', b'+').replace(b'_', b'/')
|
|
57
|
-
|
|
78
|
+
text = b64decode(data + b'=' * (-len(data) % 4))
|
|
79
|
+
if _json_depth_exceeds(text, _MAX_JSON_DEPTH):
|
|
80
|
+
raise ValueError(f'JSON nests deeper than {_MAX_JSON_DEPTH} levels.')
|
|
81
|
+
return loads(text.decode('utf-8'))
|
|
58
82
|
|
|
59
83
|
|
|
60
84
|
def currency_decimals(currency: int | None) -> int:
|
|
@@ -487,12 +511,16 @@ class Response(BaseModel):
|
|
|
487
511
|
@classmethod
|
|
488
512
|
def _blank_amount_to_none(cls, value):
|
|
489
513
|
# Keep the raw integer minor units here; scaling needs the currency and
|
|
490
|
-
# is applied in
|
|
514
|
+
# is applied in _from_fields.
|
|
491
515
|
return None if value in (None, '') else value
|
|
492
516
|
|
|
493
517
|
@classmethod
|
|
494
518
|
def from_merchant_parameters(cls, merchant_parameters: bytes) -> 'Response':
|
|
495
|
-
|
|
519
|
+
return cls._from_fields(decode_merchant_parameters(merchant_parameters))
|
|
520
|
+
|
|
521
|
+
@classmethod
|
|
522
|
+
def _from_fields(cls, fields: dict) -> 'Response':
|
|
523
|
+
response = cls.model_validate(fields)
|
|
496
524
|
if response.amount is not None:
|
|
497
525
|
# scaleb keeps the currency's decimals: 100 EUR minor units read as 1.00, not 1.
|
|
498
526
|
response.amount = response.amount.scaleb(-currency_decimals(response.currency))
|
redsys/testing.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Signed RedSys results for testing the code that receives them.
|
|
2
|
+
|
|
3
|
+
from redsys.testing import signed_response
|
|
4
|
+
|
|
5
|
+
payload = signed_response(client, order='1234ABCD', amount=Decimal('10.56'))
|
|
6
|
+
response = client.parse_response(payload) # what a notification handler does
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from decimal import Decimal
|
|
10
|
+
|
|
11
|
+
from redsys.clients import Client
|
|
12
|
+
from redsys.crypto import get_signer
|
|
13
|
+
from redsys.models import Response, minor_units_factor
|
|
14
|
+
from redsys.request import MERCHANT_PARAMETERS, SIGNATURE, SIGNATURE_VERSION
|
|
15
|
+
|
|
16
|
+
_WIRE_NAMES = {name: field.alias or name for name, field in Response.model_fields.items()}
|
|
17
|
+
_CLIENT_FIELDS = ('merchant_code', 'terminal', 'currency')
|
|
18
|
+
|
|
19
|
+
__all__ = ['signed_response']
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def signed_response(
|
|
23
|
+
client: Client,
|
|
24
|
+
*,
|
|
25
|
+
order: str,
|
|
26
|
+
response: str | int | None = '0000',
|
|
27
|
+
signature_version: str | None = None,
|
|
28
|
+
**fields,
|
|
29
|
+
) -> dict[str, str]:
|
|
30
|
+
"""The three fields RedSys posts to the notification URL or answers to a direct call, signed for ``client``.
|
|
31
|
+
|
|
32
|
+
``fields`` are ``Response`` attribute names (``authorization_code``) or wire names
|
|
33
|
+
(``Ds_Card_Country``), sent as given. ``response`` takes the code as text or as an ``int`` such as
|
|
34
|
+
``responses.DECLINED``. ``amount`` is a ``Decimal`` in major units, sent in the
|
|
35
|
+
currency's minor units. The client's ``merchant_code``, ``terminal`` and ``currency`` fill the
|
|
36
|
+
fields not given. ``response=None`` leaves out ``Ds_Response``, as a 3-D Secure challenge
|
|
37
|
+
request does. The signature uses ``signature_version``, the client's by default, and comes in
|
|
38
|
+
Base64URL, as RedSys sends it. Raises ``ValueError`` for a name that is neither an attribute nor
|
|
39
|
+
a ``Ds_`` wire name, a field given twice, or an amount finer than the currency's minor unit.
|
|
40
|
+
"""
|
|
41
|
+
wire: dict[str, object] = {}
|
|
42
|
+
|
|
43
|
+
def put(name: str, value: object) -> None:
|
|
44
|
+
if name in _WIRE_NAMES:
|
|
45
|
+
name = _WIRE_NAMES[name]
|
|
46
|
+
elif not name.startswith('Ds_') and name not in _WIRE_NAMES.values():
|
|
47
|
+
raise ValueError(f'{name} is neither a Response attribute nor a Ds_ wire name.')
|
|
48
|
+
if name in wire:
|
|
49
|
+
raise ValueError(f'{name} is given twice.')
|
|
50
|
+
wire[name] = value
|
|
51
|
+
|
|
52
|
+
amount = fields.pop('amount', None)
|
|
53
|
+
put('order', order)
|
|
54
|
+
if response is not None:
|
|
55
|
+
put('response', f'{response:04d}' if isinstance(response, int) else response)
|
|
56
|
+
for name, value in fields.items():
|
|
57
|
+
put(name, value)
|
|
58
|
+
for name in _CLIENT_FIELDS:
|
|
59
|
+
value = getattr(client, name)
|
|
60
|
+
if value is not None and _WIRE_NAMES[name] not in wire:
|
|
61
|
+
wire[_WIRE_NAMES[name]] = str(value)
|
|
62
|
+
if amount is not None:
|
|
63
|
+
currency = wire.get(_WIRE_NAMES['currency'])
|
|
64
|
+
minor_units = Decimal(amount) * minor_units_factor(int(str(currency)) if currency is not None else None)
|
|
65
|
+
if minor_units != minor_units.to_integral_value():
|
|
66
|
+
raise ValueError(f'amount {amount} is finer than the minor unit of the currency.')
|
|
67
|
+
put('amount', str(int(minor_units)))
|
|
68
|
+
|
|
69
|
+
version = signature_version or client.signature_version
|
|
70
|
+
signer = get_signer(client._secret_key, version)
|
|
71
|
+
merchant_parameters = signer.encode_parameters(wire)
|
|
72
|
+
signature = signer.sign(order, merchant_parameters).replace(b'+', b'-').replace(b'/', b'_')
|
|
73
|
+
return {
|
|
74
|
+
SIGNATURE_VERSION: version,
|
|
75
|
+
MERCHANT_PARAMETERS: merchant_parameters.decode('ascii'),
|
|
76
|
+
SIGNATURE: signature.decode('ascii'),
|
|
77
|
+
}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|