python-redsys 2.2.1__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-redsys
3
- Version: 2.2.1
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.inicia_payment(**operation, **card).send()
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.RTP_TRATA_PATH)`; read `response.rtp_status` and `response.rtp_response` (`redsys.bizum`).
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
 
@@ -167,6 +168,18 @@ Fields are validated when the operation method is called, before anything is sig
167
168
 
168
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`.
169
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
+
170
183
  ## Response codes
171
184
 
172
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).
@@ -175,7 +188,7 @@ A parameter the library does not model yet can be passed by its wire name (`Ds_M
175
188
 
176
189
  | | |
177
190
  |---|---|
178
- | Version | 2.2.1; 1.x receives fixes until 2026-12-31 ([migration guide](docs/migration-1x-to-2x.md)) |
191
+ | Version | 2.3.0; 1.x receives fixes until 2026-12-31 ([migration guide](docs/migration-1x-to-2x.md)) |
179
192
  | Python | 3.10 to 3.15 |
180
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 |
181
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 |
@@ -184,5 +197,5 @@ A parameter the library does not model yet can be passed by its wire name (`Ds_M
184
197
 
185
198
  - [`docs/redirect-connection.md`](docs/redirect-connection.md) and [`docs/direct-connection.md`](docs/direct-connection.md): protocol reference for each connection.
186
199
  - [`docs/response-codes.md`](docs/response-codes.md): response, SIS and Bizum codes.
187
- - [`docs/official-libraries.md`](docs/official-libraries.md): equivalences for integrators of RedSys's PHP and Java libraries.
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.
188
201
  - [`CONTRIBUTING.md`](CONTRIBUTING.md): development setup, checks and live tests.
@@ -1,15 +1,17 @@
1
- python_redsys-2.2.1.dist-info/licenses/LICENSE,sha256=qsc7MUj20dcRHbyjIJn2jSbGRMaBOuHk8F9leaomY_4,11360
2
- python_redsys-2.2.1.dist-info/licenses/NOTICE,sha256=6tlv5QuzsbfmGxsQNEcN7Uopzyp7vgD54xb-_L4DGyE,201
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/clients.py,sha256=Ic7bpPKGccgXRPa03BvrXGIcKQcesC8YJ_Qf9gjLrjY,22730
6
- redsys/codes.py,sha256=wxoV9h85zwNbsRDcZI3gpc9Q3JBSsVuybHeqtg7xrn4,2508
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
9
  redsys/exceptions.py,sha256=vq_RjtAcRURnLTIfzOPPU2O_97p1MWNWk8zW1WjgKHU,785
9
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=-aY5hP-WOr3mRl0p-J4da64XcPss8ewEaN7o1cwYjPs,1142
21
- redsys/api/languages.py,sha256=fl4mG6cBFNSOMcAMY1mj4w19NeZ1HyAwEGYt_oIe2KU,1043
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=PMDMlsrxgjoWUOZLpi2BsJK1Mrdvc0Ihjdz1icodvKE,2146
31
+ redsys/api/transactions.py,sha256=AE7X-0Oj6C0c0fKO0C4JXcH7DPOOhWKPLnKE7QSSfG4,2396
30
32
  redsys/api/xpay.py,sha256=KRojPBEkS3yhvrVJCUBP_8L8gxfVImS13tbmESe46ew,693
31
- python_redsys-2.2.1.dist-info/METADATA,sha256=DKHnz3ArgjN_-tU3HIKUKrC7tMgT4D3ERwbTj52USi8,10112
32
- python_redsys-2.2.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
33
- python_redsys-2.2.1.dist-info/top_level.txt,sha256=79TrHj--FP5SDyZO42-NUsiYJmHiQX42txZigHOqghY,7
34
- python_redsys-2.2.1.dist-info/RECORD,,
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__
@@ -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
- INICIA_PATH = '/sis/rest/iniciaPeticionREST'
29
+ START_PATH = '/sis/rest/iniciaPeticionREST'
26
30
  """Direct connection: 3-D Secure initialization."""
27
31
 
28
- TRATA_PATH = '/sis/rest/trataPeticionREST'
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
- RTP_TRATA_PATH = '/sis/rest/RTP/trataPeticionREST'
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
- EUSKERA = 13
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
- EUSKERA,
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'})
@@ -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
@@ -22,6 +22,7 @@ from warnings import warn
22
22
  from pydantic import ValidationError as PydanticValidationError
23
23
 
24
24
  from redsys import threeds
25
+ from redsys._deprecation import deprecated
25
26
  from redsys.api import environments, transactions
26
27
  from redsys.crypto import (
27
28
  DEFAULT_SIGNATURE_VERSION,
@@ -211,7 +212,7 @@ class Client:
211
212
  )
212
213
 
213
214
  def url(self, path: str) -> str:
214
- """The client's environment host followed by ``path``, e.g. ``environments.RTP_TRATA_PATH``."""
215
+ """The client's environment host followed by ``path``, e.g. ``environments.RTP_OPERATION_PATH``."""
215
216
  if not isinstance(path, str) or not path.startswith('/'):
216
217
  raise ValidationError('path must start with "/".')
217
218
  return f'{environments.HOSTS[self.environment]}{path}'
@@ -352,16 +353,27 @@ def _require_httpx():
352
353
 
353
354
  _EMV3DS_WIRE_NAME = 'Ds_Merchant_EMV3DS'
354
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
+
355
364
 
356
365
  class _DirectBase(Client):
357
366
  """Operations of the REST direct connection, independent of the HTTP transport."""
358
367
 
359
368
  # Endpoints per the REST guide 4.0.1 (RS.TE.CEL.MAN.0037).
360
- _PATH = environments.TRATA_PATH
369
+ _PATH = environments.OPERATION_PATH
361
370
  REAL_ENDPOINT = environments.HOSTS[environments.PROD] + _PATH
362
371
  TEST_ENDPOINT = environments.HOSTS[environments.TEST] + _PATH
363
- INICIA_REAL_ENDPOINT = environments.HOSTS[environments.PROD] + environments.INICIA_PATH
364
- INICIA_TEST_ENDPOINT = environments.HOSTS[environments.TEST] + environments.INICIA_PATH
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
365
377
 
366
378
  _DEFAULT_MODEL = DirectPaymentMessage
367
379
  _MODELS = {
@@ -376,9 +388,19 @@ class _DirectBase(Client):
376
388
  transactions.AUTHENTICATION_CONFIRMATION_CANCELLATION: CancellationMessage,
377
389
  }
378
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
+
379
401
  @property
380
- def inicia_endpoint(self) -> str:
381
- return self.url(environments.INICIA_PATH)
402
+ def start_endpoint(self) -> str:
403
+ return self.url(environments.START_PATH)
382
404
 
383
405
  def payment(self, **fields) -> Request:
384
406
  return self._operation(transactions.AUTHORIZATION, fields)
@@ -433,29 +455,51 @@ class _DirectBase(Client):
433
455
  )
434
456
  return self.void(**fields)
435
457
 
436
- def inicia(self, **fields) -> Request:
458
+ def start(self, **fields) -> Request:
437
459
  """3-D Secure initialization (iniciaPeticionREST) from the given fields, ``emv3ds`` included."""
438
460
  fields = dict(fields)
439
461
  endpoint = _endpoint_option(fields)
440
462
  model = self._DEFAULT_MODEL(**self._inject(fields))
441
- return self._prepare(model, endpoint=endpoint or self.inicia_endpoint)
463
+ return self._prepare(model, endpoint=endpoint or self.start_endpoint)
442
464
 
443
- def inicia_payment(self, **fields) -> Request:
465
+ def start_payment(self, **fields) -> Request:
444
466
  """3-D Secure step 1 for a payment; ``emv3ds`` defaults to ``threeds.card_data()``."""
445
- return self._inicia(transactions.AUTHORIZATION, fields)
467
+ return self._start(transactions.AUTHORIZATION, fields)
446
468
 
447
- def inicia_preauthorization(self, **fields) -> Request:
469
+ def start_preauthorization(self, **fields) -> Request:
448
470
  """3-D Secure step 1 for a preauthorization; ``emv3ds`` defaults to ``threeds.card_data()``."""
449
- return self._inicia(transactions.PREAUTHORIZATION, fields)
471
+ return self._start(transactions.PREAUTHORIZATION, fields)
450
472
 
451
- def inicia_authentication(self, **fields) -> Request:
473
+ def start_authentication(self, **fields) -> Request:
452
474
  """3-D Secure step 1 for an authentication; ``emv3ds`` defaults to ``threeds.card_data()``."""
453
- return self._inicia(transactions.AUTHENTICATION, fields)
475
+ return self._start(transactions.AUTHENTICATION, fields)
454
476
 
455
- def _inicia(self, transaction_type: int, fields: dict) -> Request:
477
+ def _start(self, transaction_type: int, fields: dict) -> Request:
456
478
  if 'emv3ds' not in fields and _EMV3DS_WIRE_NAME not in fields:
457
479
  fields['emv3ds'] = threeds.card_data()
458
- return self._operation(transaction_type, fields, endpoint=self.inicia_endpoint)
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)
459
503
 
460
504
  def challenge_response(
461
505
  self, *, cres: str, protocol_version: str, transaction_type: int = transactions.AUTHORIZATION, **fields
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.EUSKERA: 3,
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
- language = int(language) if language.isdigit() else language.lower()
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'``, ``'en'``, ``'ca'``, ``'gl'``, ``'eu'``; ``'va'`` reads the Catalan) or RedSys's numeric
66
- one (``languages.SPANISH``, ``ENGLISH``, ``CATALAN``, ``VALENCIAN``, ``GALICIAN``, ``EUSKERA``).
67
- Returns ``''`` for an unknown code or language.
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/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
+ }