python-redsys 2.1.0__py3-none-any.whl → 2.2.1__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.1.dist-info/METADATA +188 -0
- python_redsys-2.2.1.dist-info/RECORD +34 -0
- redsys/__init__.py +38 -2
- redsys/_code_texts.py +4673 -0
- redsys/api/__init__.py +1 -1
- redsys/api/bizum.py +71 -0
- redsys/api/cards.py +50 -0
- redsys/api/currencies.py +18 -18
- redsys/api/emv3ds.py +99 -0
- redsys/api/environments.py +41 -0
- redsys/api/languages.py +9 -1
- redsys/api/options.py +31 -0
- redsys/api/pay_methods.py +25 -0
- redsys/api/paygold.py +33 -0
- redsys/api/processed_pay_methods.py +207 -0
- redsys/api/responses.py +290 -0
- redsys/api/sca.py +11 -3
- redsys/api/secure_payment.py +12 -0
- redsys/api/transactions.py +26 -9
- redsys/api/xpay.py +25 -0
- redsys/clients.py +326 -96
- redsys/codes.py +76 -0
- redsys/crypto.py +8 -8
- redsys/exceptions.py +5 -2
- redsys/models.py +314 -52
- redsys/orders.py +20 -0
- redsys/request.py +19 -13
- redsys/threeds.py +21 -16
- python_redsys-2.1.0.dist-info/METADATA +0 -225
- python_redsys-2.1.0.dist-info/RECORD +0 -20
- {python_redsys-2.1.0.dist-info → python_redsys-2.2.1.dist-info}/WHEEL +0 -0
- {python_redsys-2.1.0.dist-info → python_redsys-2.2.1.dist-info}/licenses/LICENSE +0 -0
- {python_redsys-2.1.0.dist-info → python_redsys-2.2.1.dist-info}/licenses/NOTICE +0 -0
- {python_redsys-2.1.0.dist-info → python_redsys-2.2.1.dist-info}/top_level.txt +0 -0
redsys/clients.py
CHANGED
|
@@ -1,24 +1,28 @@
|
|
|
1
|
-
"""
|
|
1
|
+
"""Clients for the RedSys redirect and direct connections.
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
the factory for every operation. You never build or import a request model --
|
|
6
|
-
call an operation method (``payment``, ``refund``, ...) or the low-level
|
|
7
|
-
``request()`` they all delegate to, and you get back a ``Request``:
|
|
3
|
+
A client holds the credentials and the account (secret key, merchant code, terminal,
|
|
4
|
+
environment, signature version) and builds every operation as a signed ``Request``:
|
|
8
5
|
|
|
9
|
-
client = DirectClient(secret_key='...', merchant_code='
|
|
10
|
-
response = client.payment(order=
|
|
6
|
+
client = DirectClient(secret_key='...', merchant_code='999008881', terminal=1, sandbox=True)
|
|
7
|
+
response = client.payment(order=generate_order(), amount=Decimal('10.56')).send()
|
|
11
8
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
and parse incoming results through ``client.parse_response(payload)``.
|
|
9
|
+
A redirect request ends in ``to_dict()``, the form the browser posts; a direct request
|
|
10
|
+
ends in ``send()``. ``parse_response()`` verifies and parses a received result.
|
|
15
11
|
"""
|
|
16
12
|
|
|
13
|
+
from base64 import b64decode
|
|
14
|
+
from collections.abc import Mapping
|
|
17
15
|
from hmac import compare_digest
|
|
16
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
18
17
|
from logging import getLogger
|
|
19
|
-
from re import sub
|
|
18
|
+
from re import fullmatch, sub
|
|
19
|
+
from urllib.parse import urlsplit
|
|
20
|
+
from warnings import warn
|
|
20
21
|
|
|
21
|
-
from
|
|
22
|
+
from pydantic import ValidationError as PydanticValidationError
|
|
23
|
+
|
|
24
|
+
from redsys import threeds
|
|
25
|
+
from redsys.api import environments, transactions
|
|
22
26
|
from redsys.crypto import (
|
|
23
27
|
DEFAULT_SIGNATURE_VERSION,
|
|
24
28
|
HMAC_SHA256_V1,
|
|
@@ -27,8 +31,9 @@ from redsys.crypto import (
|
|
|
27
31
|
SIGNATURE_VERSIONS,
|
|
28
32
|
get_signer,
|
|
29
33
|
)
|
|
30
|
-
from redsys.exceptions import ResponseError
|
|
34
|
+
from redsys.exceptions import ResponseError, ValidationError
|
|
31
35
|
from redsys.models import (
|
|
36
|
+
BaseRequest,
|
|
32
37
|
CancellationMessage,
|
|
33
38
|
ConfirmationMessage,
|
|
34
39
|
DirectPaymentMessage,
|
|
@@ -37,6 +42,7 @@ from redsys.models import (
|
|
|
37
42
|
RedirectPreauthorizationMessage,
|
|
38
43
|
RefundMessage,
|
|
39
44
|
Response,
|
|
45
|
+
decode_merchant_parameters,
|
|
40
46
|
)
|
|
41
47
|
from redsys.request import (
|
|
42
48
|
MERCHANT_PARAMETERS,
|
|
@@ -47,9 +53,26 @@ from redsys.request import (
|
|
|
47
53
|
|
|
48
54
|
logger = getLogger(__name__)
|
|
49
55
|
|
|
50
|
-
|
|
56
|
+
|
|
57
|
+
def _default_module() -> str:
|
|
58
|
+
try:
|
|
59
|
+
return f'python-redsys/{version("python-redsys")}'
|
|
60
|
+
except PackageNotFoundError:
|
|
61
|
+
return 'python-redsys'
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
#: Ds_Merchant_Module sent by default: this library and its installed version.
|
|
65
|
+
DEFAULT_MODULE = _default_module()
|
|
66
|
+
|
|
67
|
+
# Seconds; ``send(timeout=...)`` overrides it.
|
|
51
68
|
DEFAULT_TIMEOUT = 30
|
|
52
69
|
|
|
70
|
+
# Real payloads take a few KiB; the caps bound the work done before the signature is checked.
|
|
71
|
+
_MAX_MERCHANT_PARAMETERS_LENGTH = 128 * 1024
|
|
72
|
+
_MAX_SIGNATURE_LENGTH = 128
|
|
73
|
+
|
|
74
|
+
_ORDER_WIRE_NAME = Response.model_fields['order'].alias
|
|
75
|
+
|
|
53
76
|
__all__ = [
|
|
54
77
|
'Client',
|
|
55
78
|
'RedirectClient',
|
|
@@ -64,6 +87,7 @@ __all__ = [
|
|
|
64
87
|
'HMAC_SHA512_V2',
|
|
65
88
|
'SIGNATURE_VERSIONS',
|
|
66
89
|
'DEFAULT_SIGNATURE_VERSION',
|
|
90
|
+
'DEFAULT_MODULE',
|
|
67
91
|
]
|
|
68
92
|
|
|
69
93
|
|
|
@@ -79,15 +103,74 @@ def _normalize_signature(signature) -> str:
|
|
|
79
103
|
return sub(r'[^a-zA-Z0-9]', '', signature)
|
|
80
104
|
|
|
81
105
|
|
|
106
|
+
def _base64_text(value, name: str, max_length: int) -> bytes:
|
|
107
|
+
"""A received Base64 field as bytes; Base64 is ASCII, so anything else is malformed."""
|
|
108
|
+
if isinstance(value, (str, bytes, bytearray)) and len(value) > max_length:
|
|
109
|
+
raise ValidationError(f'{name} exceeds {max_length} characters.')
|
|
110
|
+
if isinstance(value, str) and value.isascii():
|
|
111
|
+
value = value.encode('ascii')
|
|
112
|
+
elif isinstance(value, bytearray):
|
|
113
|
+
value = bytes(value)
|
|
114
|
+
if not isinstance(value, bytes) or not value.isascii():
|
|
115
|
+
raise ValidationError(f'{name} is missing or is not Base64 text.')
|
|
116
|
+
return value
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _resolve_environment(environment: str | None, sandbox: bool | None) -> str:
|
|
120
|
+
"""The environment a client targets; ``sandbox`` means TEST when true and PROD when false."""
|
|
121
|
+
implied = None if sandbox is None else environments.TEST if sandbox else environments.PROD
|
|
122
|
+
if environment is None:
|
|
123
|
+
return implied or environments.PROD
|
|
124
|
+
if environment not in environments.HOSTS:
|
|
125
|
+
raise ValidationError('environment is not valid.')
|
|
126
|
+
if implied not in (None, environment):
|
|
127
|
+
raise ValidationError('environment contradicts sandbox.')
|
|
128
|
+
return environment
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _endpoint_option(fields: dict) -> str | None:
|
|
132
|
+
"""Pop a call's ``endpoint``, which is never signed; it must be an HTTPS URL."""
|
|
133
|
+
endpoint = fields.pop('endpoint', None)
|
|
134
|
+
if endpoint is None:
|
|
135
|
+
return None
|
|
136
|
+
parts = urlsplit(endpoint) if isinstance(endpoint, str) else None
|
|
137
|
+
if parts is None or parts.scheme != 'https' or not parts.netloc:
|
|
138
|
+
raise ValidationError('endpoint must be an https:// URL.')
|
|
139
|
+
return endpoint
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _parse_api_key(api_key: str) -> tuple[str, str, int, str]:
|
|
143
|
+
"""Split an API key into (environment, merchant code, terminal, secret key).
|
|
144
|
+
|
|
145
|
+
The format is ``<environment>_<Base64URL of merchant_terminal_secret>``, with
|
|
146
|
+
or without padding. Failures raise outside any ``except`` block and name no
|
|
147
|
+
detail, so neither the key nor its decoded secret reaches the traceback.
|
|
148
|
+
"""
|
|
149
|
+
environment, _, payload = api_key.partition('_') if isinstance(api_key, str) else ('', '', '')
|
|
150
|
+
payload = payload.rstrip('=')
|
|
151
|
+
try:
|
|
152
|
+
decoded = b64decode(payload + '=' * (-len(payload) % 4), b'-_', validate=True).decode('utf-8')
|
|
153
|
+
except ValueError:
|
|
154
|
+
decoded = ''
|
|
155
|
+
fields = fullmatch(r'([0-9]{1,9})_([0-9]{1,3})_(.+)', decoded)
|
|
156
|
+
if environment not in environments.HOSTS or fields is None:
|
|
157
|
+
raise ValidationError('API key is not valid.')
|
|
158
|
+
merchant_code, terminal, secret_key = fields.groups()
|
|
159
|
+
return environment, merchant_code, int(terminal), secret_key
|
|
160
|
+
|
|
161
|
+
|
|
82
162
|
class Client:
|
|
83
163
|
"""Base client: credentials, account identity, request factory, response parsing."""
|
|
84
164
|
|
|
85
165
|
REAL_ENDPOINT: str | None = None
|
|
86
166
|
TEST_ENDPOINT: str | None = None
|
|
167
|
+
_PATH: str | None = None
|
|
87
168
|
|
|
88
|
-
#:
|
|
169
|
+
#: Request model per transaction type; other types use ``_DEFAULT_MODEL``.
|
|
89
170
|
_DEFAULT_MODEL: type | None = None
|
|
90
171
|
_MODELS: dict[int, type] = {}
|
|
172
|
+
#: The transaction types the connection accepts; ``None`` leaves the check to the model.
|
|
173
|
+
_TRANSACTION_TYPES: tuple[int, ...] | None = None
|
|
91
174
|
|
|
92
175
|
def __init__(
|
|
93
176
|
self,
|
|
@@ -95,25 +178,52 @@ class Client:
|
|
|
95
178
|
*,
|
|
96
179
|
merchant_code: str | None = None,
|
|
97
180
|
terminal: int | None = None,
|
|
98
|
-
|
|
181
|
+
currency: int | None = None,
|
|
182
|
+
sandbox: bool | None = None,
|
|
183
|
+
environment: str | None = None,
|
|
99
184
|
signature_version: str = DEFAULT_SIGNATURE_VERSION,
|
|
185
|
+
module: str | None = DEFAULT_MODULE,
|
|
100
186
|
):
|
|
101
187
|
self._secret_key = secret_key
|
|
188
|
+
self.module = module
|
|
102
189
|
self.merchant_code = merchant_code
|
|
103
190
|
self.terminal = terminal
|
|
104
|
-
self.
|
|
191
|
+
self.currency = currency
|
|
192
|
+
self.environment = _resolve_environment(environment, sandbox)
|
|
193
|
+
self.sandbox = self.environment != environments.PROD
|
|
105
194
|
self.signature_version = signature_version
|
|
106
|
-
self.endpoint = self.
|
|
195
|
+
self.endpoint = self.url(self._PATH) if self._PATH else None
|
|
107
196
|
|
|
108
|
-
|
|
197
|
+
@classmethod
|
|
198
|
+
def from_api_key(cls, api_key: str, **options):
|
|
199
|
+
"""Build a client from a RedSys API key, which carries the environment and the credentials.
|
|
200
|
+
|
|
201
|
+
``options`` are the remaining constructor options (``signature_version``, ``currency``, ``module``).
|
|
202
|
+
Raises ``ValidationError`` if the key is not valid.
|
|
203
|
+
"""
|
|
204
|
+
environment, merchant_code, terminal, secret_key = _parse_api_key(api_key)
|
|
205
|
+
return cls(secret_key, merchant_code=merchant_code, terminal=terminal, environment=environment, **options)
|
|
206
|
+
|
|
207
|
+
def __repr__(self) -> str:
|
|
208
|
+
return (
|
|
209
|
+
f'{type(self).__name__}(merchant_code={self.merchant_code!r}, terminal={self.terminal!r}, '
|
|
210
|
+
f'environment={self.environment!r}, signature_version={self.signature_version!r})'
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
def url(self, path: str) -> str:
|
|
214
|
+
"""The client's environment host followed by ``path``, e.g. ``environments.RTP_TRATA_PATH``."""
|
|
215
|
+
if not isinstance(path, str) or not path.startswith('/'):
|
|
216
|
+
raise ValidationError('path must start with "/".')
|
|
217
|
+
return f'{environments.HOSTS[self.environment]}{path}'
|
|
218
|
+
|
|
219
|
+
# == Request building ==
|
|
109
220
|
def _inject(self, fields: dict) -> dict:
|
|
110
|
-
"""Merge the client's account
|
|
111
|
-
data
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
data.update(fields)
|
|
221
|
+
"""Merge the client's account defaults into a call's fields (call wins, by either name)."""
|
|
222
|
+
data = dict(fields)
|
|
223
|
+
for name in ('merchant_code', 'terminal', 'currency', 'module'):
|
|
224
|
+
value = getattr(self, name)
|
|
225
|
+
if value is not None and name not in data and BaseRequest.model_fields[name].alias not in data:
|
|
226
|
+
data[name] = value
|
|
117
227
|
return data
|
|
118
228
|
|
|
119
229
|
def _model_for(self, transaction_type: int) -> type:
|
|
@@ -125,65 +235,111 @@ class Client:
|
|
|
125
235
|
def request(self, transaction_type: int, **fields) -> Request:
|
|
126
236
|
"""Build, validate and sign any operation by its transaction type.
|
|
127
237
|
|
|
128
|
-
|
|
129
|
-
|
|
238
|
+
For the types without a method, such as ``transactions.REFUND_CANCELLATION``.
|
|
239
|
+
Raises ``ValidationError`` if ``fields`` name a different transaction type, or if
|
|
240
|
+
the connection does not accept it (the redirect connection takes
|
|
241
|
+
``transactions.REDIRECT_TRANSACTION_TYPES``). Every operation takes ``endpoint=``,
|
|
242
|
+
an HTTPS URL that replaces the client's for that request only; it is not signed.
|
|
130
243
|
"""
|
|
244
|
+
return self._operation(transaction_type, fields)
|
|
245
|
+
|
|
246
|
+
def _operation(self, transaction_type: int, fields: dict, endpoint: str | None = None) -> Request:
|
|
247
|
+
fields = dict(fields)
|
|
248
|
+
override = _endpoint_option(fields)
|
|
249
|
+
return self._prepare(self._message(transaction_type, fields), endpoint=override or endpoint)
|
|
250
|
+
|
|
251
|
+
def _message(self, transaction_type: int, fields: dict):
|
|
252
|
+
if self._TRANSACTION_TYPES is not None and transaction_type not in self._TRANSACTION_TYPES:
|
|
253
|
+
raise ValidationError(f'transaction type {transaction_type} is not accepted by {type(self).__name__}.')
|
|
131
254
|
data = self._inject(fields)
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
255
|
+
for name in ('transaction_type', BaseRequest.model_fields['transaction_type'].alias):
|
|
256
|
+
if str(data.pop(name, transaction_type)) != str(transaction_type):
|
|
257
|
+
raise ValidationError(f'{name} contradicts the operation, transaction type {transaction_type}.')
|
|
258
|
+
return self._model_for(transaction_type)(**data, transaction_type=transaction_type)
|
|
135
259
|
|
|
136
|
-
def _prepare(self, model) -> Request:
|
|
137
|
-
return self._build_request(model)
|
|
260
|
+
def _prepare(self, model, endpoint: str | None = None) -> Request:
|
|
261
|
+
return self._build_request(model, endpoint=endpoint or self.endpoint)
|
|
138
262
|
|
|
139
|
-
def _build_request(
|
|
263
|
+
def _build_request(
|
|
264
|
+
self, model, signature_version: str | None = None, sender=None, endpoint: str | None = None
|
|
265
|
+
) -> Request:
|
|
140
266
|
version = signature_version or self.signature_version
|
|
141
267
|
signer = get_signer(self._secret_key, version)
|
|
142
268
|
merchant_parameters = signer.encode_parameters(model.prepare_parameters())
|
|
143
269
|
signature = signer.sign(model.get_order(), merchant_parameters)
|
|
144
|
-
return Request(merchant_parameters, signature, version, sender=sender)
|
|
270
|
+
return Request(merchant_parameters, signature, version, sender=sender, endpoint=endpoint)
|
|
145
271
|
|
|
146
|
-
#
|
|
147
|
-
def parse_response(self, payload:
|
|
272
|
+
# == Response parsing ==
|
|
273
|
+
def parse_response(self, payload: Mapping) -> Response:
|
|
148
274
|
"""Verify the signature and parse a received payload into a ``Response``.
|
|
149
275
|
|
|
150
276
|
Accepts both the redirect callback form fields and the direct REST JSON
|
|
151
|
-
body.
|
|
152
|
-
|
|
153
|
-
|
|
277
|
+
body. Fields are validated only after the signature matches. Raises
|
|
278
|
+
``ResponseError`` if RedSys answered with an error code instead of a
|
|
279
|
+
signed result, ``ValidationError`` if the payload is not a well-formed
|
|
280
|
+
RedSys result, and ``ValueError`` if the signature does not match (the
|
|
281
|
+
payload is not from RedSys or was tampered with).
|
|
154
282
|
"""
|
|
283
|
+
if not isinstance(payload, Mapping):
|
|
284
|
+
raise ValidationError('The payload must be a mapping of the received fields.')
|
|
155
285
|
if MERCHANT_PARAMETERS not in payload:
|
|
156
286
|
error_code = payload.get('errorCode') or payload.get('Ds_ErrorCode')
|
|
287
|
+
if not error_code:
|
|
288
|
+
raise ValidationError(f'The payload carries neither {MERCHANT_PARAMETERS} nor an error code.')
|
|
157
289
|
raise ResponseError(error_code, payload)
|
|
158
|
-
merchant_parameters =
|
|
159
|
-
|
|
160
|
-
|
|
290
|
+
merchant_parameters = _base64_text(
|
|
291
|
+
payload[MERCHANT_PARAMETERS], MERCHANT_PARAMETERS, _MAX_MERCHANT_PARAMETERS_LENGTH
|
|
292
|
+
)
|
|
293
|
+
signature = _base64_text(payload.get(SIGNATURE), SIGNATURE, _MAX_SIGNATURE_LENGTH)
|
|
161
294
|
version = payload.get(SIGNATURE_VERSION, DEFAULT_SIGNATURE_VERSION)
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
295
|
+
if version not in SIGNATURE_VERSIONS:
|
|
296
|
+
raise ValidationError(f'{SIGNATURE_VERSION} is not supported.')
|
|
297
|
+
try:
|
|
298
|
+
fields = decode_merchant_parameters(merchant_parameters)
|
|
299
|
+
except ValueError as error:
|
|
300
|
+
raise ValidationError(f'{MERCHANT_PARAMETERS} is not a Base64-encoded JSON object: {error}') from error
|
|
301
|
+
if not isinstance(fields, dict):
|
|
302
|
+
raise ValidationError(f'{MERCHANT_PARAMETERS} is not a Base64-encoded JSON object.')
|
|
303
|
+
# A signed result always carries Ds_Order; without it, '' makes verification fail.
|
|
304
|
+
order = fields.get(_ORDER_WIRE_NAME)
|
|
305
|
+
try:
|
|
306
|
+
expected = get_signer(self._secret_key, version).sign(
|
|
307
|
+
order if isinstance(order, str) else '', merchant_parameters
|
|
308
|
+
)
|
|
309
|
+
except UnicodeEncodeError as error:
|
|
310
|
+
raise ValidationError(f'{_ORDER_WIRE_NAME} is not valid text.') from error
|
|
311
|
+
if not compare_digest(_normalize_signature(signature), _normalize_signature(expected)):
|
|
168
312
|
raise ValueError('Signature is not valid.')
|
|
169
|
-
|
|
313
|
+
try:
|
|
314
|
+
return Response._from_fields(fields)
|
|
315
|
+
except (PydanticValidationError, ArithmeticError) as error:
|
|
316
|
+
raise ValidationError(f'{MERCHANT_PARAMETERS} holds a field that is not valid.') from error
|
|
170
317
|
|
|
171
318
|
|
|
172
319
|
class RedirectClient(Client):
|
|
173
|
-
"""Redirect connection
|
|
174
|
-
browser submits to RedSys. The library performs no HTTP and no redirect."""
|
|
320
|
+
"""Redirect connection: builds the signed form fields the browser posts to RedSys; performs no HTTP."""
|
|
175
321
|
|
|
176
322
|
# Endpoints per the redirection guide 4.2 (RS.TE.CEL.MAN.0039).
|
|
177
|
-
|
|
178
|
-
|
|
323
|
+
_PATH = environments.REDIRECT_PATH
|
|
324
|
+
REAL_ENDPOINT = environments.HOSTS[environments.PROD] + _PATH
|
|
325
|
+
TEST_ENDPOINT = environments.HOSTS[environments.TEST] + _PATH
|
|
179
326
|
_DEFAULT_MODEL = RedirectPaymentMessage
|
|
180
327
|
_MODELS = {transactions.PREAUTHORIZATION: RedirectPreauthorizationMessage}
|
|
328
|
+
_TRANSACTION_TYPES = transactions.REDIRECT_TRANSACTION_TYPES
|
|
181
329
|
|
|
182
330
|
def payment(self, **fields) -> Request:
|
|
183
|
-
return self.
|
|
331
|
+
return self._operation(transactions.AUTHORIZATION, fields)
|
|
184
332
|
|
|
185
333
|
def preauthorization(self, **fields) -> Request:
|
|
186
|
-
return self.
|
|
334
|
+
return self._operation(transactions.PREAUTHORIZATION, fields)
|
|
335
|
+
|
|
336
|
+
def authentication(self, **fields) -> Request:
|
|
337
|
+
"""Authenticate the cardholder and validate the card, with no hold (transaction type 7)."""
|
|
338
|
+
return self._operation(transactions.AUTHENTICATION, fields)
|
|
339
|
+
|
|
340
|
+
def refund_without_original(self, **fields) -> Request:
|
|
341
|
+
"""Credit the cardholder with no previous sale (transaction type 34)."""
|
|
342
|
+
return self._operation(transactions.REFUND_WITHOUT_ORIGINAL, fields)
|
|
187
343
|
|
|
188
344
|
|
|
189
345
|
def _require_httpx():
|
|
@@ -194,21 +350,25 @@ def _require_httpx():
|
|
|
194
350
|
return httpx
|
|
195
351
|
|
|
196
352
|
|
|
353
|
+
_EMV3DS_WIRE_NAME = 'Ds_Merchant_EMV3DS'
|
|
354
|
+
|
|
355
|
+
|
|
197
356
|
class _DirectBase(Client):
|
|
198
|
-
"""
|
|
357
|
+
"""Operations of the REST direct connection, independent of the HTTP transport."""
|
|
199
358
|
|
|
200
359
|
# Endpoints per the REST guide 4.0.1 (RS.TE.CEL.MAN.0037).
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
360
|
+
_PATH = environments.TRATA_PATH
|
|
361
|
+
REAL_ENDPOINT = environments.HOSTS[environments.PROD] + _PATH
|
|
362
|
+
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
|
|
205
365
|
|
|
206
366
|
_DEFAULT_MODEL = DirectPaymentMessage
|
|
207
367
|
_MODELS = {
|
|
208
368
|
transactions.PREAUTHORIZATION: DirectPreauthorizationMessage,
|
|
209
369
|
transactions.CONFIRMATION: ConfirmationMessage,
|
|
210
370
|
transactions.REFUND: RefundMessage,
|
|
211
|
-
transactions.
|
|
371
|
+
transactions.VOID: CancellationMessage,
|
|
212
372
|
transactions.REPLACEMENT_PREAUTHORIZATION: DirectPreauthorizationMessage,
|
|
213
373
|
transactions.PARTIAL_CONFIRMATION: ConfirmationMessage,
|
|
214
374
|
transactions.PAYMENT_CANCELLATION: CancellationMessage,
|
|
@@ -218,60 +378,130 @@ class _DirectBase(Client):
|
|
|
218
378
|
|
|
219
379
|
@property
|
|
220
380
|
def inicia_endpoint(self) -> str:
|
|
221
|
-
return self.
|
|
381
|
+
return self.url(environments.INICIA_PATH)
|
|
222
382
|
|
|
223
383
|
def payment(self, **fields) -> Request:
|
|
224
|
-
return self.
|
|
384
|
+
return self._operation(transactions.AUTHORIZATION, fields)
|
|
225
385
|
|
|
226
386
|
def preauthorization(self, **fields) -> Request:
|
|
227
|
-
return self.
|
|
387
|
+
return self._operation(transactions.PREAUTHORIZATION, fields)
|
|
228
388
|
|
|
229
389
|
def confirmation(self, **fields) -> Request:
|
|
230
|
-
return self.
|
|
390
|
+
return self._operation(transactions.CONFIRMATION, fields)
|
|
391
|
+
|
|
392
|
+
def partial_confirmation(self, **fields) -> Request:
|
|
393
|
+
return self._operation(transactions.PARTIAL_CONFIRMATION, fields)
|
|
394
|
+
|
|
395
|
+
def authentication(self, **fields) -> Request:
|
|
396
|
+
return self._operation(transactions.AUTHENTICATION, fields)
|
|
397
|
+
|
|
398
|
+
def authentication_confirmation(self, **fields) -> Request:
|
|
399
|
+
return self._operation(transactions.AUTHENTICATION_CONFIRMATION, fields)
|
|
400
|
+
|
|
401
|
+
def authentication_confirmation_cancellation(self, **fields) -> Request:
|
|
402
|
+
return self._operation(transactions.AUTHENTICATION_CONFIRMATION_CANCELLATION, fields)
|
|
403
|
+
|
|
404
|
+
def pay_gold(self, **fields) -> Request:
|
|
405
|
+
return self._operation(transactions.PAY_GOLD, fields)
|
|
406
|
+
|
|
407
|
+
def pay_gold_expiry_change(self, **fields) -> Request:
|
|
408
|
+
"""Change the expiry of a PayGold link (transaction type 51); RedSys requires ``amount``."""
|
|
409
|
+
return self._operation(transactions.PAY_GOLD_EXPIRY_CHANGE, fields)
|
|
410
|
+
|
|
411
|
+
def refund_without_original(self, **fields) -> Request:
|
|
412
|
+
"""Credit the cardholder with no previous sale (transaction type 34)."""
|
|
413
|
+
return self._operation(transactions.REFUND_WITHOUT_ORIGINAL, fields)
|
|
231
414
|
|
|
232
415
|
def refund(self, **fields) -> Request:
|
|
233
|
-
return self.
|
|
416
|
+
return self._operation(transactions.REFUND, fields)
|
|
417
|
+
|
|
418
|
+
def void(self, **fields) -> Request:
|
|
419
|
+
"""Void a preauthorization (transaction type 9)."""
|
|
420
|
+
return self._operation(transactions.VOID, fields)
|
|
421
|
+
|
|
422
|
+
def payment_cancellation(self, **fields) -> Request:
|
|
423
|
+
"""Cancel a payment after a merchant time-out or technical error (transaction type 45)."""
|
|
424
|
+
return self._operation(transactions.PAYMENT_CANCELLATION, fields)
|
|
234
425
|
|
|
235
426
|
def cancellation(self, **fields) -> Request:
|
|
236
|
-
|
|
427
|
+
"""Deprecated: sends type 9; use ``void()``, or ``payment_cancellation()`` for type 45."""
|
|
428
|
+
warn(
|
|
429
|
+
'cancellation() is deprecated and goes away in 3.0: use void() for type 9, the type it sends, '
|
|
430
|
+
'or payment_cancellation() for type 45.',
|
|
431
|
+
DeprecationWarning,
|
|
432
|
+
stacklevel=2,
|
|
433
|
+
)
|
|
434
|
+
return self.void(**fields)
|
|
237
435
|
|
|
238
436
|
def inicia(self, **fields) -> Request:
|
|
239
|
-
"""3-D Secure
|
|
437
|
+
"""3-D Secure initialization (iniciaPeticionREST) from the given fields, ``emv3ds`` included."""
|
|
438
|
+
fields = dict(fields)
|
|
439
|
+
endpoint = _endpoint_option(fields)
|
|
240
440
|
model = self._DEFAULT_MODEL(**self._inject(fields))
|
|
241
|
-
return self._prepare(model, endpoint=self.inicia_endpoint)
|
|
441
|
+
return self._prepare(model, endpoint=endpoint or self.inicia_endpoint)
|
|
442
|
+
|
|
443
|
+
def inicia_payment(self, **fields) -> Request:
|
|
444
|
+
"""3-D Secure step 1 for a payment; ``emv3ds`` defaults to ``threeds.card_data()``."""
|
|
445
|
+
return self._inicia(transactions.AUTHORIZATION, fields)
|
|
446
|
+
|
|
447
|
+
def inicia_preauthorization(self, **fields) -> Request:
|
|
448
|
+
"""3-D Secure step 1 for a preauthorization; ``emv3ds`` defaults to ``threeds.card_data()``."""
|
|
449
|
+
return self._inicia(transactions.PREAUTHORIZATION, fields)
|
|
450
|
+
|
|
451
|
+
def inicia_authentication(self, **fields) -> Request:
|
|
452
|
+
"""3-D Secure step 1 for an authentication; ``emv3ds`` defaults to ``threeds.card_data()``."""
|
|
453
|
+
return self._inicia(transactions.AUTHENTICATION, fields)
|
|
454
|
+
|
|
455
|
+
def _inicia(self, transaction_type: int, fields: dict) -> Request:
|
|
456
|
+
if 'emv3ds' not in fields and _EMV3DS_WIRE_NAME not in fields:
|
|
457
|
+
fields['emv3ds'] = threeds.card_data()
|
|
458
|
+
return self._operation(transaction_type, fields, endpoint=self.inicia_endpoint)
|
|
459
|
+
|
|
460
|
+
def challenge_response(
|
|
461
|
+
self, *, cres: str, protocol_version: str, transaction_type: int = transactions.AUTHORIZATION, **fields
|
|
462
|
+
) -> Request:
|
|
463
|
+
"""3-D Secure final step after the challenge; ``transaction_type`` is the one authenticated."""
|
|
464
|
+
if 'emv3ds' in fields or _EMV3DS_WIRE_NAME in fields:
|
|
465
|
+
raise ValidationError('challenge_response() builds emv3ds from cres and protocol_version.')
|
|
466
|
+
emv3ds = threeds.challenge_response(cres=cres, protocol_version=protocol_version)
|
|
467
|
+
return self._operation(transaction_type, {**fields, 'emv3ds': emv3ds})
|
|
242
468
|
|
|
243
469
|
def _prepare(self, model, endpoint: str | None = None) -> Request:
|
|
244
|
-
|
|
245
|
-
return self._build_request(model, sender=self._make_sender(endpoint))
|
|
470
|
+
return self._build_request(model, sender=self._send, endpoint=endpoint or self.endpoint)
|
|
246
471
|
|
|
247
|
-
def
|
|
472
|
+
def _send(self, request, **httpx_kwargs):
|
|
248
473
|
raise NotImplementedError
|
|
249
474
|
|
|
475
|
+
def _parse_http_response(self, http_response) -> Response:
|
|
476
|
+
http_response.raise_for_status()
|
|
477
|
+
transport = (http_response.status_code, dict(http_response.headers), http_response.text)
|
|
478
|
+
try:
|
|
479
|
+
body = http_response.json()
|
|
480
|
+
except ValueError as error:
|
|
481
|
+
raise ValidationError('The answer is not JSON.') from error
|
|
482
|
+
try:
|
|
483
|
+
response = self.parse_response(body)
|
|
484
|
+
except ResponseError as error:
|
|
485
|
+
error.http_status, error.http_headers, error.raw_body = transport
|
|
486
|
+
raise
|
|
487
|
+
return response._with_transport(*transport)
|
|
250
488
|
|
|
251
|
-
class DirectClient(_DirectBase):
|
|
252
|
-
"""Synchronous REST direct-connection client. Requires the httpx extra."""
|
|
253
489
|
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
httpx = _require_httpx()
|
|
257
|
-
httpx_kwargs.setdefault('timeout', DEFAULT_TIMEOUT)
|
|
258
|
-
http_response = httpx.post(endpoint, json=request.to_dict(), **httpx_kwargs)
|
|
259
|
-
http_response.raise_for_status()
|
|
260
|
-
return self.parse_response(http_response.json())
|
|
490
|
+
class DirectClient(_DirectBase):
|
|
491
|
+
"""Synchronous REST direct-connection client; ``send()`` requires the ``http`` extra (httpx)."""
|
|
261
492
|
|
|
262
|
-
|
|
493
|
+
def _send(self, request, **httpx_kwargs):
|
|
494
|
+
httpx = _require_httpx()
|
|
495
|
+
httpx_kwargs.setdefault('timeout', DEFAULT_TIMEOUT)
|
|
496
|
+
return self._parse_http_response(httpx.post(request.endpoint, json=request.to_dict(), **httpx_kwargs))
|
|
263
497
|
|
|
264
498
|
|
|
265
499
|
class AsyncDirectClient(_DirectBase):
|
|
266
|
-
"""Asynchronous REST direct-connection client (
|
|
267
|
-
|
|
268
|
-
def
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
http_response.raise_for_status()
|
|
275
|
-
return self.parse_response(http_response.json())
|
|
276
|
-
|
|
277
|
-
return sender
|
|
500
|
+
"""Asynchronous REST direct-connection client; ``await send()`` requires the ``http`` extra (httpx)."""
|
|
501
|
+
|
|
502
|
+
async def _send(self, request, **httpx_kwargs):
|
|
503
|
+
httpx = _require_httpx()
|
|
504
|
+
httpx_kwargs.setdefault('timeout', DEFAULT_TIMEOUT)
|
|
505
|
+
async with httpx.AsyncClient() as client:
|
|
506
|
+
http_response = await client.post(request.endpoint, json=request.to_dict(), **httpx_kwargs)
|
|
507
|
+
return self._parse_http_response(http_response)
|
redsys/codes.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Meanings of RedSys result and error codes, in Spanish, Catalan, Galician, Basque or English.
|
|
2
|
+
|
|
3
|
+
from redsys.codes import describe
|
|
4
|
+
|
|
5
|
+
describe('0195', 'en') # Ds_Response
|
|
6
|
+
describe('SIS0051') # SIS error code
|
|
7
|
+
describe('BIZ00009') # Bizum Request-to-Pay code
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from re import fullmatch
|
|
11
|
+
|
|
12
|
+
from redsys import _code_texts
|
|
13
|
+
from redsys.api import languages, responses
|
|
14
|
+
|
|
15
|
+
# Position of each language in the (Spanish, Catalan, Galician, Basque, English) texts; Valencian reads the Catalan.
|
|
16
|
+
_TEXT_INDEX = {
|
|
17
|
+
'es': 0,
|
|
18
|
+
'ca': 1,
|
|
19
|
+
'va': 1,
|
|
20
|
+
'gl': 2,
|
|
21
|
+
'eu': 3,
|
|
22
|
+
'en': 4,
|
|
23
|
+
languages.SPANISH: 0,
|
|
24
|
+
languages.CATALAN: 1,
|
|
25
|
+
languages.VALENCIAN: 1,
|
|
26
|
+
languages.GALICIAN: 2,
|
|
27
|
+
languages.EUSKERA: 3,
|
|
28
|
+
languages.ENGLISH: 4,
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _language_index(language) -> int | None:
|
|
33
|
+
if isinstance(language, str):
|
|
34
|
+
language = int(language) if language.isdigit() else language.lower()
|
|
35
|
+
return _TEXT_INDEX.get(language)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _texts(code) -> tuple[str, ...] | None:
|
|
39
|
+
if isinstance(code, bool):
|
|
40
|
+
return None
|
|
41
|
+
if isinstance(code, int):
|
|
42
|
+
code = str(code)
|
|
43
|
+
if not isinstance(code, str):
|
|
44
|
+
return None
|
|
45
|
+
code = code.strip().upper()
|
|
46
|
+
if match := fullmatch(r'SIS([0-9]{4})', code):
|
|
47
|
+
return _code_texts.SIS.get(int(match.group(1)))
|
|
48
|
+
if match := fullmatch(r'BIZ([0-9]{5})', code):
|
|
49
|
+
return _code_texts.BIZ.get(int(match.group(1)))
|
|
50
|
+
if not fullmatch(r'[0-9]{1,4}', code):
|
|
51
|
+
return None
|
|
52
|
+
number = int(code)
|
|
53
|
+
if number <= responses.AUTHORIZED_LAST:
|
|
54
|
+
return _code_texts.AUTHORIZED
|
|
55
|
+
if number in _code_texts.DS_RESPONSE:
|
|
56
|
+
return _code_texts.DS_RESPONSE[number]
|
|
57
|
+
# Every SIS0nnn error has a numeric twin 9nnn that can arrive in Ds_Response.
|
|
58
|
+
return _code_texts.SIS.get(number - 9000) if number >= 9000 else None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def describe(code, language='es') -> str:
|
|
62
|
+
"""The meaning of a ``Ds_Response`` code, an ``SISnnnn`` error code or a Bizum ``BIZnnnnn`` code.
|
|
63
|
+
|
|
64
|
+
``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.
|
|
68
|
+
"""
|
|
69
|
+
texts = _texts(code)
|
|
70
|
+
index = _language_index(language)
|
|
71
|
+
if texts is None or index is None:
|
|
72
|
+
return ''
|
|
73
|
+
return texts[index]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
__all__ = ['describe']
|