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/crypto.py
CHANGED
|
@@ -14,13 +14,13 @@ HMAC_SHA512_V2 also sends Ds_MerchantParameters as unpadded Base64URL; the other
|
|
|
14
14
|
versions send standard Base64. Responses are decoded tolerantly in either form.
|
|
15
15
|
|
|
16
16
|
The SHA-512 versions key their HMAC with the Base64 text of the derived key and differ
|
|
17
|
-
only in the padding of the signature (
|
|
18
|
-
HMAC_SHA256_V1 uses the raw derived bytes.
|
|
17
|
+
only in the padding of the signature (verified against signed responses of the RedSys
|
|
18
|
+
test environment); HMAC_SHA256_V1 uses the raw derived bytes.
|
|
19
19
|
|
|
20
20
|
HMAC_SHA512_V1 is the REST guide 4.0.1 scheme; HMAC_SHA512_V2 (the default) is the one the
|
|
21
|
-
redirection guide 4.1 and later
|
|
22
|
-
|
|
23
|
-
|
|
21
|
+
redirection guide 4.1 and later uses; HMAC_SHA256_V1 is still accepted (REST guide 4.0.1,
|
|
22
|
+
Anexo 2). The cipher parameters are pinned by a known-answer test against RedSys's official
|
|
23
|
+
worked example (see tests/test_crypto.py).
|
|
24
24
|
"""
|
|
25
25
|
|
|
26
26
|
from base64 import b64decode, b64encode, urlsafe_b64encode
|
|
@@ -84,7 +84,7 @@ class Sha512V1Signer(Signer):
|
|
|
84
84
|
|
|
85
85
|
def sign(self, order: str, merchant_parameters: bytes) -> bytes:
|
|
86
86
|
# The HMAC key is the Base64 text of the derived key, not its raw bytes
|
|
87
|
-
# (confirmed
|
|
87
|
+
# (confirmed against the RedSys test environment, where raw bytes give SIS0042).
|
|
88
88
|
derived = b64encode(self._derive_key(order))
|
|
89
89
|
# REST manual: Base64URL with the '=' padding kept.
|
|
90
90
|
return urlsafe_b64encode(HMAC(derived, merchant_parameters, sha512).digest())
|
|
@@ -96,12 +96,12 @@ class Sha512V2Signer(Sha512V1Signer):
|
|
|
96
96
|
def encode_parameters(self, parameters: dict) -> bytes:
|
|
97
97
|
# V2 endpoints decode Ds_MerchantParameters as unpadded Base64URL: the 3DS
|
|
98
98
|
# initialization rejects standard or padded Base64 with SIS0430 (verified
|
|
99
|
-
#
|
|
99
|
+
# against the test environment).
|
|
100
100
|
return urlsafe_b64encode(dumps(parameters, sort_keys=True).encode('utf-8')).rstrip(b'=')
|
|
101
101
|
|
|
102
102
|
def sign(self, order: str, merchant_parameters: bytes) -> bytes:
|
|
103
103
|
# Same derived key and HMAC as HMAC_SHA512_V1; only the '=' padding goes
|
|
104
|
-
# (
|
|
104
|
+
# (verified against the test environment).
|
|
105
105
|
return super().sign(order, merchant_parameters).rstrip(b'=')
|
|
106
106
|
|
|
107
107
|
|
redsys/exceptions.py
CHANGED
|
@@ -8,11 +8,14 @@ class ResponseError(RedsysError):
|
|
|
8
8
|
def __init__(self, error_code, payload=None):
|
|
9
9
|
self.error_code = error_code
|
|
10
10
|
self.payload = payload
|
|
11
|
+
self.http_status = None
|
|
12
|
+
self.http_headers = None
|
|
13
|
+
self.raw_body = None
|
|
11
14
|
super().__init__(f'RedSys returned error: {error_code}')
|
|
12
15
|
|
|
13
16
|
|
|
14
|
-
class ValidationError(RedsysError):
|
|
15
|
-
"""
|
|
17
|
+
class ValidationError(RedsysError, ValueError):
|
|
18
|
+
"""Rejected input: a client option or operation fields RedSys does not accept, or a malformed received payload."""
|
|
16
19
|
|
|
17
20
|
|
|
18
21
|
class UnknownParameterWarning(UserWarning):
|
redsys/models.py
CHANGED
|
@@ -9,38 +9,76 @@ dict with ``model_validate``. Field constraints follow these RedSys documents:
|
|
|
9
9
|
- TPV Virtual, Manual de Integración REST, RS.TE.CEL.MAN.0037, version 4.0.1 (2025-10-17),
|
|
10
10
|
https://pagosonline.redsys.es/download/1738/
|
|
11
11
|
- Guía de integración de Bizum, version 2.6 (2026-08-25), https://pagosonline.redsys.es/download/2053/
|
|
12
|
+
- inSite guide, version 4.1 (2026-01-05), https://pagosonline.redsys.es/download/1751/
|
|
13
|
+
- Pago por e-mail/SMS (PayGold), RS.TE.CEL.MAN.0026, version 1.8.2 (2026-04-20),
|
|
14
|
+
https://pagosonline.redsys.es/download/2056/
|
|
15
|
+
- Integración de Google Pay, version 1.9 (2025-05-21), https://pagosonline.redsys.es/download/2045/
|
|
16
|
+
- Apple Pay, guía de instalación, version 3.2 (2023-03-28), https://pagosonline.redsys.es/download/2050/
|
|
12
17
|
- Developer portal pages "Firmar una operación", "Parámetros de entrada y salida" and "Operativa DCC".
|
|
13
|
-
-
|
|
14
|
-
for the response fields the guides omit.
|
|
18
|
+
- Responses of the RedSys test environment, for the response fields the guides omit.
|
|
15
19
|
"""
|
|
16
20
|
|
|
17
21
|
from base64 import b64decode, b64encode
|
|
18
22
|
from decimal import Decimal
|
|
23
|
+
from itertools import accumulate
|
|
19
24
|
from json import dumps, loads
|
|
25
|
+
from operator import sub as subtract
|
|
20
26
|
from typing import Any
|
|
21
27
|
from warnings import warn
|
|
22
28
|
|
|
23
|
-
from pydantic import
|
|
24
|
-
|
|
25
|
-
|
|
29
|
+
from pydantic import (
|
|
30
|
+
AliasChoices,
|
|
31
|
+
BaseModel,
|
|
32
|
+
ConfigDict,
|
|
33
|
+
Field,
|
|
34
|
+
PrivateAttr,
|
|
35
|
+
field_serializer,
|
|
36
|
+
field_validator,
|
|
37
|
+
model_validator,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
from redsys.api import emv3ds, options, paygold, responses, transactions, xpay
|
|
41
|
+
from redsys.api.currencies import CURRENCIES, CURRENCY_DECIMALS, EUR
|
|
26
42
|
from redsys.api.transactions import TRANSACTION_TYPES
|
|
43
|
+
from redsys.codes import describe
|
|
27
44
|
from redsys.exceptions import UnknownParameterWarning
|
|
28
45
|
|
|
29
|
-
# 1.x request names that changed
|
|
30
|
-
_LEGACY_FIELDS: dict[str, str
|
|
46
|
+
# 1.x request names that changed in 2.0; the error names the replacement.
|
|
47
|
+
_LEGACY_FIELDS: dict[str, str] = {
|
|
31
48
|
'payment_method': 'pay_methods',
|
|
32
49
|
'mobile_number': 'bizum_mobile_number',
|
|
33
|
-
'transaction_date': None,
|
|
34
50
|
}
|
|
35
51
|
|
|
36
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
|
+
|
|
37
71
|
def decode_merchant_parameters(data: bytes) -> dict:
|
|
38
72
|
"""Decode a Ds_MerchantParameters string in standard or URL-safe Base64, padded or not.
|
|
39
73
|
|
|
40
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.
|
|
41
76
|
"""
|
|
42
77
|
data = data.replace(b'-', b'+').replace(b'_', b'/')
|
|
43
|
-
|
|
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'))
|
|
44
82
|
|
|
45
83
|
|
|
46
84
|
def currency_decimals(currency: int | None) -> int:
|
|
@@ -56,26 +94,22 @@ def minor_units_factor(currency: int | None) -> int:
|
|
|
56
94
|
class BaseRequest(BaseModel):
|
|
57
95
|
"""Fields common to every operation message, with validation and wire serialization."""
|
|
58
96
|
|
|
59
|
-
#
|
|
97
|
+
# extra='allow' keeps the unmodeled wire names that _screen_unknown_fields lets through.
|
|
60
98
|
model_config = ConfigDict(populate_by_name=True, extra='allow')
|
|
61
99
|
|
|
62
100
|
merchant_code: str = Field(alias='Ds_Merchant_MerchantCode', max_length=9)
|
|
63
101
|
terminal: int = Field(alias='Ds_Merchant_Terminal', ge=1, le=999)
|
|
64
102
|
transaction_type: int = Field(0, alias='Ds_Merchant_TransactionType')
|
|
65
103
|
amount: Decimal = Field(alias='Ds_Merchant_Amount', description='Major units; scaled to minor units on the wire.')
|
|
66
|
-
currency: int = Field(alias='Ds_Merchant_Currency')
|
|
104
|
+
currency: int = Field(EUR, alias='Ds_Merchant_Currency')
|
|
67
105
|
order: str = Field(alias='Ds_Merchant_Order', min_length=4, max_length=12, pattern=r'^[0-9]{4}[a-zA-Z0-9]{0,8}$')
|
|
68
106
|
merchant_data: str | None = Field(None, alias='Ds_Merchant_MerchantData', max_length=1024)
|
|
107
|
+
module: str | None = Field(None, alias='Ds_Merchant_Module', description='Integration that sends the request.')
|
|
69
108
|
|
|
70
109
|
@model_validator(mode='before')
|
|
71
110
|
@classmethod
|
|
72
111
|
def _screen_unknown_fields(cls, data: Any) -> Any:
|
|
73
|
-
"""Reject
|
|
74
|
-
|
|
75
|
-
A parameter the library does not model yet is accepted under its wire
|
|
76
|
-
name (``Ds_Merchant_*``) and sent as given, so a RedSys addition does not
|
|
77
|
-
wait for a library release. Any other unknown name is a mistake and fails.
|
|
78
|
-
"""
|
|
112
|
+
"""Reject unknown and 1.x names; let unmodeled wire names (``Ds_Merchant_*``) through with a warning."""
|
|
79
113
|
if not isinstance(data, dict):
|
|
80
114
|
return data
|
|
81
115
|
known = {name for name in cls.model_fields} | {f.alias for f in cls.model_fields.values() if f.alias}
|
|
@@ -83,9 +117,7 @@ class BaseRequest(BaseModel):
|
|
|
83
117
|
if key in known:
|
|
84
118
|
continue
|
|
85
119
|
if key in _LEGACY_FIELDS:
|
|
86
|
-
|
|
87
|
-
hint = f'use {replacement!r}' if replacement else 'it has no 2.x equivalent'
|
|
88
|
-
raise ValueError(f'{key!r} is a 1.x field name; {hint}.')
|
|
120
|
+
raise ValueError(f'{key!r} is a 1.x field name; use {_LEGACY_FIELDS[key]!r}.')
|
|
89
121
|
if key.lower().startswith('ds_merchant_'):
|
|
90
122
|
warn(f'{key!r} is not modeled by this library; sent as given.', UnknownParameterWarning, stacklevel=2)
|
|
91
123
|
continue
|
|
@@ -127,13 +159,40 @@ class _StoredCredentialFields(BaseModel):
|
|
|
127
159
|
identifier: str | None = Field(
|
|
128
160
|
None, alias='Ds_Merchant_Identifier', max_length=40, description='Stored-card token; see redsys.api.cof.'
|
|
129
161
|
)
|
|
130
|
-
direct_payment: str | None = Field(
|
|
162
|
+
direct_payment: str | None = Field(
|
|
163
|
+
None, alias='Ds_Merchant_DirectPayment', description='options.DIRECT_PAYMENT or options.MOTO.'
|
|
164
|
+
)
|
|
131
165
|
cof_ini: str | None = Field(None, alias='Ds_Merchant_Cof_Ini', max_length=1, description='See redsys.api.cof.')
|
|
132
166
|
cof_type: str | None = Field(None, alias='Ds_Merchant_Cof_Type', max_length=1, description='See redsys.api.cof.')
|
|
133
167
|
cof_txnid: str | None = Field(None, alias='Ds_Merchant_Cof_Txnid', max_length=15)
|
|
168
|
+
group: str | None = Field(
|
|
169
|
+
None, alias='Ds_Merchant_Group', pattern=r'^[0-9]{1,9}$', description='Group that shares card references.'
|
|
170
|
+
)
|
|
171
|
+
email_titular: str | None = Field(
|
|
172
|
+
None, alias='Ds_Merchant_Email_Titular', max_length=100, description='Cardholder e-mail; gets a summary.'
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
class _CardFields(BaseModel):
|
|
177
|
+
"""Card data, inSite token and 3-D Secure data, accepted by both connections."""
|
|
178
|
+
|
|
179
|
+
pan: str | None = Field(None, alias='Ds_Merchant_Pan', max_length=19, pattern=r'^[0-9]{12,19}$')
|
|
180
|
+
expiry_date: str | None = Field(None, alias='Ds_Merchant_ExpiryDate', pattern=r'^[0-9]{4}$', description='YYMM.')
|
|
181
|
+
cvv2: str | None = Field(None, alias='Ds_Merchant_Cvv2', pattern=r'^[0-9]{3,4}$')
|
|
182
|
+
idoper: str | None = Field(None, alias='Ds_Merchant_Idoper', max_length=40, description='inSite operation token.')
|
|
183
|
+
emv3ds: dict[str, Any] | None = Field(None, alias='Ds_Merchant_EMV3DS', description='Build with redsys.threeds.')
|
|
134
184
|
|
|
135
185
|
|
|
136
|
-
class
|
|
186
|
+
class _DirectOperationFields(BaseModel):
|
|
187
|
+
"""Fields of every direct-connection operation."""
|
|
188
|
+
|
|
189
|
+
merchant_descriptor: str | None = Field(
|
|
190
|
+
None, alias='Ds_Merchant_MerchantDescriptor', max_length=25, description='Soft descriptor; bank activation.'
|
|
191
|
+
)
|
|
192
|
+
client_ip: str | None = Field(None, alias='Ds_Merchant_ClientIP', max_length=15, description='Customer IP.')
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
class _RedirectFields(_StoredCredentialFields, _CardFields):
|
|
137
196
|
"""Fields of the redirect connection (browser form)."""
|
|
138
197
|
|
|
139
198
|
merchant_url: str | None = Field(None, alias='Ds_Merchant_MerchantURL', max_length=250)
|
|
@@ -143,7 +202,7 @@ class _RedirectFields(_StoredCredentialFields):
|
|
|
143
202
|
product_description: str | None = Field(None, alias='Ds_Merchant_ProductDescription', max_length=125)
|
|
144
203
|
titular: str | None = Field(None, alias='Ds_Merchant_Titular', max_length=60)
|
|
145
204
|
consumer_language: int | None = Field(None, alias='Ds_Merchant_ConsumerLanguage')
|
|
146
|
-
pay_methods: str | None = Field(None, alias='Ds_Merchant_PayMethods', description='
|
|
205
|
+
pay_methods: str | None = Field(None, alias='Ds_Merchant_PayMethods', description='See redsys.api.pay_methods.')
|
|
147
206
|
bizum_mobile_number: str | None = Field(None, alias='Ds_Merchant_Bizum_MobileNumber', max_length=19)
|
|
148
207
|
excep_sca: str | None = Field(
|
|
149
208
|
None,
|
|
@@ -151,32 +210,105 @@ class _RedirectFields(_StoredCredentialFields):
|
|
|
151
210
|
max_length=3,
|
|
152
211
|
description='PSD2 SCA exemption requested; codes in redsys.api.sca.',
|
|
153
212
|
)
|
|
213
|
+
merchant_descriptor: str | None = Field(
|
|
214
|
+
None, alias='Ds_Merchant_MerchantDescriptor', max_length=25, description='Soft descriptor; bank activation.'
|
|
215
|
+
)
|
|
216
|
+
shipping_address_pyp: str | None = Field(
|
|
217
|
+
None, alias='Ds_Merchant_ShippingAddressPyP', pattern=r'^[SN]$', description='See redsys.api.options.'
|
|
218
|
+
)
|
|
219
|
+
perso_code: int | None = Field(
|
|
220
|
+
None, alias='Ds_Merchant_PersoCode', ge=0, le=9, description='Payment page personalization.'
|
|
221
|
+
)
|
|
222
|
+
|
|
154
223
|
|
|
224
|
+
class _XPayFields(BaseModel):
|
|
225
|
+
"""Google Pay and Apple Pay data; the wire names have no MERCHANT infix."""
|
|
155
226
|
|
|
156
|
-
|
|
227
|
+
xpay_data: str | None = Field(
|
|
228
|
+
None, alias='DS_XPAYDATA', max_length=10000, description='Encrypted wallet payload, as the wallet guide says.'
|
|
229
|
+
)
|
|
230
|
+
xpay_decoded_data: dict[str, Any] | None = Field(
|
|
231
|
+
None, alias='DS_XPAYDECODEDDATA', description='Wallet payload decrypted by the merchant.'
|
|
232
|
+
)
|
|
233
|
+
xpay_type: str | None = Field(None, alias='DS_XPAYTYPE', description='See redsys.api.xpay.')
|
|
234
|
+
xpay_origen: str | None = Field(None, alias='DS_XPAYORIGEN', description='See redsys.api.xpay.')
|
|
235
|
+
|
|
236
|
+
@field_validator('xpay_type')
|
|
237
|
+
@classmethod
|
|
238
|
+
def _validate_xpay_type(cls, value: str | None) -> str | None:
|
|
239
|
+
if value is not None and value not in xpay.TYPES:
|
|
240
|
+
raise ValueError('xpay_type is not valid.')
|
|
241
|
+
return value
|
|
242
|
+
|
|
243
|
+
@field_validator('xpay_origen')
|
|
244
|
+
@classmethod
|
|
245
|
+
def _validate_xpay_origen(cls, value: str | None) -> str | None:
|
|
246
|
+
if value is not None and value not in xpay.ORIGINS:
|
|
247
|
+
raise ValueError('xpay_origen is not valid.')
|
|
248
|
+
return value
|
|
249
|
+
|
|
250
|
+
@model_validator(mode='after')
|
|
251
|
+
def _one_wallet_payload_with_its_type_and_origin(self):
|
|
252
|
+
payloads = (self.xpay_data is not None) + (self.xpay_decoded_data is not None)
|
|
253
|
+
described = (self.xpay_type is not None) + (self.xpay_origen is not None)
|
|
254
|
+
if payloads > 1:
|
|
255
|
+
raise ValueError('xpay_data and xpay_decoded_data are mutually exclusive.')
|
|
256
|
+
if (payloads, described) not in ((0, 0), (1, 2)):
|
|
257
|
+
raise ValueError('a wallet payload goes with xpay_type and xpay_origen.')
|
|
258
|
+
return self
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
class _DirectFields(_StoredCredentialFields, _CardFields, _DirectOperationFields, _XPayFields):
|
|
157
262
|
"""Fields of the direct connection (server-to-server card data, 3DS, stored credentials)."""
|
|
158
263
|
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
264
|
+
mpi_external: dict[str, Any] | None = Field(
|
|
265
|
+
None, alias='Ds_Merchant_MpiExternal', description='Results of an external 3DS server.'
|
|
266
|
+
)
|
|
267
|
+
token_data: dict[str, Any] | None = Field(
|
|
268
|
+
None, alias='Ds_Merchant_TokenData', description='Network token cryptogram data.'
|
|
269
|
+
)
|
|
164
270
|
# RedSys spells the wire name "Frecuency".
|
|
165
271
|
date_frequency: str | None = Field(None, alias='Ds_Merchant_DateFrecuency', description='Days between charges.')
|
|
166
272
|
charge_expiry_date: str | None = Field(None, alias='Ds_Merchant_ChargeExpiryDate', description='yyyy-MM-dd.')
|
|
167
273
|
dcc: str | dict[str, Any] | None = Field(
|
|
168
|
-
None,
|
|
274
|
+
None,
|
|
275
|
+
alias='Ds_Merchant_DCC',
|
|
276
|
+
description='options.DCC_QUERY on the 3DS initialization; then the accepted offer.',
|
|
169
277
|
)
|
|
170
278
|
excep_sca: str | None = Field(
|
|
171
279
|
None,
|
|
172
280
|
alias='Ds_Merchant_Excep_SCA',
|
|
173
281
|
max_length=3,
|
|
174
|
-
description='PSD2 SCA exemption requested; codes in redsys.api.sca.
|
|
282
|
+
description='PSD2 SCA exemption requested; codes in redsys.api.sca. sca.QUERY on the 3DS initialization asks.',
|
|
283
|
+
)
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
class _PaymentFields(BaseModel):
|
|
287
|
+
"""Fields of payments (type 0) and authentications (type 7) on both connections."""
|
|
288
|
+
|
|
289
|
+
tax_reference: str | None = Field(
|
|
290
|
+
None, alias='Ds_Merchant_Tax_Reference', max_length=100, description='Tax payment barcode; bank activation.'
|
|
175
291
|
)
|
|
292
|
+
ota: str | None = Field(None, alias='Ds_Merchant_OTA', pattern=r'^S$', description='See redsys.api.options.')
|
|
176
293
|
|
|
177
294
|
|
|
178
|
-
class
|
|
179
|
-
"""
|
|
295
|
+
class _BizumFields(BaseModel):
|
|
296
|
+
"""Bizum fields of payments on both connections."""
|
|
297
|
+
|
|
298
|
+
bizum_mrt_amount_variation: str | None = Field(
|
|
299
|
+
None,
|
|
300
|
+
alias='Ds_Merchant_Bizum_MrtAmountVariation',
|
|
301
|
+
pattern=r'^[0-9]+$',
|
|
302
|
+
description='Ceiling for later MIT amounts, in minor units; on the operation that creates the TID.',
|
|
303
|
+
)
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
class RedirectPaymentMessage(BaseRequest, _RedirectFields, _PaymentFields, _BizumFields):
|
|
307
|
+
"""Redirect-connection payment (transaction type 0), authentication (7) or refund without original (34)."""
|
|
308
|
+
|
|
309
|
+
bizum_id_oper: str | None = Field(
|
|
310
|
+
None, alias='Ds_Merchant_Bizum_IdOper', description='Response.bizum_id_oper; asks RedSys for the backup.'
|
|
311
|
+
)
|
|
180
312
|
|
|
181
313
|
|
|
182
314
|
class RedirectPreauthorizationMessage(BaseRequest, _RedirectFields):
|
|
@@ -185,12 +317,90 @@ class RedirectPreauthorizationMessage(BaseRequest, _RedirectFields):
|
|
|
185
317
|
transaction_type: int = Field(1, alias='Ds_Merchant_TransactionType')
|
|
186
318
|
|
|
187
319
|
|
|
188
|
-
class
|
|
189
|
-
"""
|
|
320
|
+
class _PayGoldFields(BaseModel):
|
|
321
|
+
"""Fields of a PayGold link (types 15 and 51)."""
|
|
322
|
+
|
|
323
|
+
customer_mobile: str | None = Field(None, alias='Ds_Merchant_Customer_Mobile', max_length=19)
|
|
324
|
+
customer_mail: str | None = Field(None, alias='Ds_Merchant_Customer_Mail', max_length=100)
|
|
325
|
+
customer_sms_text: str | None = Field(
|
|
326
|
+
None, alias='Ds_Merchant_Customer_Sms_Text', max_length=160, description='Must contain paygold.SMS_URL.'
|
|
327
|
+
)
|
|
328
|
+
p2f_expiry_date: str | None = Field(
|
|
329
|
+
None,
|
|
330
|
+
alias='Ds_Merchant_P2f_ExpiryDate',
|
|
331
|
+
pattern=r'^([0-9]{1,23}|[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2}\.[0-9]{2}\.[0-9]{2}\.[0-9]{3})$',
|
|
332
|
+
description='Minutes from now, or yyyy-mm-dd-HH.MM.ss.sss.',
|
|
333
|
+
)
|
|
334
|
+
p2f_xml_data: str | None = Field(
|
|
335
|
+
None, alias='Ds_Merchant_P2f_XmlData', max_length=1000, description='E-mail tags; see redsys.api.paygold.'
|
|
336
|
+
)
|
|
337
|
+
alt_transaction_type: int | None = Field(
|
|
338
|
+
None,
|
|
339
|
+
alias='Ds_Merchant_AltTransType',
|
|
340
|
+
description='transactions.REFUND_WITHOUT_ORIGINAL turns the link into a refund without original.',
|
|
341
|
+
)
|
|
342
|
+
pay_methods: str | None = Field(None, alias='Ds_Merchant_PayMethods', description='See redsys.api.pay_methods.')
|
|
343
|
+
merchant_url: str | None = Field(None, alias='Ds_Merchant_MerchantURL', max_length=250)
|
|
344
|
+
|
|
345
|
+
@field_validator('customer_sms_text')
|
|
346
|
+
@classmethod
|
|
347
|
+
def _sms_text_holds_the_link(cls, value: str | None) -> str | None:
|
|
348
|
+
if value is not None and paygold.SMS_URL not in value:
|
|
349
|
+
raise ValueError(f'customer_sms_text must contain {paygold.SMS_URL}.')
|
|
350
|
+
return value
|
|
351
|
+
|
|
352
|
+
@field_validator('p2f_expiry_date', mode='before')
|
|
353
|
+
@classmethod
|
|
354
|
+
def _minutes_as_text(cls, value):
|
|
355
|
+
return str(value) if isinstance(value, int) and not isinstance(value, bool) else value
|
|
356
|
+
|
|
357
|
+
@field_validator('alt_transaction_type')
|
|
358
|
+
@classmethod
|
|
359
|
+
def _validate_alt_transaction_type(cls, value: int | None) -> int | None:
|
|
360
|
+
if value is not None and value != transactions.REFUND_WITHOUT_ORIGINAL:
|
|
361
|
+
raise ValueError('alt_transaction_type is 34, refund without original.')
|
|
362
|
+
return value
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
class DirectPaymentMessage(BaseRequest, _DirectFields, _PaymentFields, _PayGoldFields, _BizumFields):
|
|
366
|
+
"""Direct-connection card payment (transaction type 0), and the types without their own message."""
|
|
190
367
|
|
|
191
368
|
sum_total: Decimal | None = Field(
|
|
192
369
|
None, alias='Ds_Merchant_SumTotal', description='Recurring series total; scaled like amount.'
|
|
193
370
|
)
|
|
371
|
+
financing: str | dict[str, Any] | None = Field(
|
|
372
|
+
None,
|
|
373
|
+
alias='Ds_Merchant_Financing',
|
|
374
|
+
description='options.FINANCING_QUERY on the 3DS initialization; then the chosen option.',
|
|
375
|
+
)
|
|
376
|
+
matching_data: str | None = Field(
|
|
377
|
+
None, alias='Ds_Merchant_MatchingData', max_length=21, description='Unique; type 17, with acquirer_identifier.'
|
|
378
|
+
)
|
|
379
|
+
acquirer_identifier: str | None = Field(
|
|
380
|
+
None, alias='Ds_Acquirer_Identifier', pattern=r'^[0-9]{1,6}$', description='Type 17, with matching_data.'
|
|
381
|
+
)
|
|
382
|
+
bizum_mobile_number: str | None = Field(None, alias='Ds_Merchant_Bizum_MobileNumber', max_length=19)
|
|
383
|
+
otp: str | None = Field(
|
|
384
|
+
None, alias='Ds_Merchant_Otp', pattern=r'^[0-9]+$', description='Bizum backup one-time password.'
|
|
385
|
+
)
|
|
386
|
+
|
|
387
|
+
@field_validator('otp', mode='before')
|
|
388
|
+
@classmethod
|
|
389
|
+
def _otp_as_text(cls, value):
|
|
390
|
+
return str(value) if isinstance(value, int) and not isinstance(value, bool) else value
|
|
391
|
+
|
|
392
|
+
@field_validator('financing')
|
|
393
|
+
@classmethod
|
|
394
|
+
def _validate_financing(cls, value):
|
|
395
|
+
if isinstance(value, str) and value != options.FINANCING_QUERY:
|
|
396
|
+
raise ValueError('financing is "Y" or the chosen option.')
|
|
397
|
+
return value
|
|
398
|
+
|
|
399
|
+
@model_validator(mode='after')
|
|
400
|
+
def _matching_data_with_acquirer(self):
|
|
401
|
+
if (self.matching_data is None) != (self.acquirer_identifier is None):
|
|
402
|
+
raise ValueError('matching_data and acquirer_identifier go together.')
|
|
403
|
+
return self
|
|
194
404
|
|
|
195
405
|
@field_serializer('sum_total')
|
|
196
406
|
def _serialize_sum_total(self, value: Decimal | None) -> int | None:
|
|
@@ -203,21 +413,30 @@ class DirectPreauthorizationMessage(BaseRequest, _DirectFields):
|
|
|
203
413
|
transaction_type: int = Field(1, alias='Ds_Merchant_TransactionType')
|
|
204
414
|
|
|
205
415
|
|
|
206
|
-
class ConfirmationMessage(BaseRequest):
|
|
416
|
+
class ConfirmationMessage(BaseRequest, _DirectOperationFields):
|
|
207
417
|
"""Capture of a previous preauthorization (transaction type 2)."""
|
|
208
418
|
|
|
209
419
|
transaction_type: int = Field(2, alias='Ds_Merchant_TransactionType')
|
|
210
420
|
|
|
211
421
|
|
|
212
|
-
class RefundMessage(BaseRequest):
|
|
422
|
+
class RefundMessage(BaseRequest, _DirectOperationFields):
|
|
213
423
|
"""Refund of a previous payment (transaction type 3)."""
|
|
214
424
|
|
|
215
425
|
transaction_type: int = Field(3, alias='Ds_Merchant_TransactionType')
|
|
216
426
|
authorization_code: str | None = Field(None, alias='Ds_Merchant_AuthorisationCode', max_length=6)
|
|
427
|
+
transaction_date: str | None = Field(
|
|
428
|
+
None,
|
|
429
|
+
alias='Ds_Merchant_TransactionDate',
|
|
430
|
+
pattern=r'^[0-9]{4}-[0-9]{2}-[0-9]{2}$',
|
|
431
|
+
description='yyyy-mm-dd of the original operation.',
|
|
432
|
+
)
|
|
433
|
+
rts: str | None = Field(
|
|
434
|
+
None, alias='Ds_Merchant_RTS', pattern=r'^[0-9]{1,24}$', description='Response.rts of a partial confirmation.'
|
|
435
|
+
)
|
|
217
436
|
|
|
218
437
|
|
|
219
|
-
class CancellationMessage(BaseRequest):
|
|
220
|
-
"""
|
|
438
|
+
class CancellationMessage(BaseRequest, _DirectOperationFields):
|
|
439
|
+
"""Void of a preauthorization (transaction type 9) or another cancellation (types 45 to 47)."""
|
|
221
440
|
|
|
222
441
|
transaction_type: int = Field(9, alias='Ds_Merchant_TransactionType')
|
|
223
442
|
|
|
@@ -247,8 +466,7 @@ class Response(BaseModel):
|
|
|
247
466
|
card_country: str | None = Field(None, alias='Ds_Card_Country')
|
|
248
467
|
card_type: str | None = Field(None, alias='Ds_Card_Type')
|
|
249
468
|
card_brand: str | None = Field(None, alias='Ds_Card_Brand')
|
|
250
|
-
# Not in the integration guides
|
|
251
|
-
# and modeled by the official PHP library 2.0.1.
|
|
469
|
+
# Not in the integration guides; returned by the test environment.
|
|
252
470
|
card_typology: str | None = Field(None, alias='Ds_Card_Typology', description='For example CONSUMO.')
|
|
253
471
|
eci: str | None = Field(None, alias='Ds_ECI', description='E-commerce indicator of the authentication.')
|
|
254
472
|
response_description: str | None = Field(None, alias='Ds_Response_Description')
|
|
@@ -268,22 +486,41 @@ class Response(BaseModel):
|
|
|
268
486
|
dcc: dict[str, Any] | None = Field(None, alias='Ds_DCC', description='Offer from the 3DS initialization.')
|
|
269
487
|
identifier: str | None = Field(None, alias='Ds_Merchant_Identifier', description='Token returned on request.')
|
|
270
488
|
cof_txnid: str | None = Field(None, alias='Ds_Merchant_Cof_Txnid')
|
|
271
|
-
processed_pay_method: str | None = Field(
|
|
489
|
+
processed_pay_method: str | None = Field(
|
|
490
|
+
None, alias='Ds_ProcessedPayMethod', description='See redsys.api.processed_pay_methods.'
|
|
491
|
+
)
|
|
272
492
|
bizum_id_oper: str | None = Field(None, alias='Ds_Bizum_IdOper')
|
|
273
493
|
bizum_cuenta_truncada: str | None = Field(None, alias='Ds_Bizum_CuentaTruncada')
|
|
274
494
|
currency_dcc: str | None = Field(None, alias='Ds_Currency_DCC', description='Dynamic currency conversion.')
|
|
275
495
|
amount_dcc: str | None = Field(None, alias='Ds_Amount_DCC', description='Minor units in Ds_Currency_DCC.')
|
|
496
|
+
rts: str | None = Field(None, alias='rts', description='Partial confirmation reference; refund it with rts=.')
|
|
497
|
+
rtp_status: str | None = Field(None, alias='Ds_RtpStatus', description='Bizum Request-to-Pay: OK or KO.')
|
|
498
|
+
rtp_response: str | None = Field(None, alias='Ds_RtpResponse', description='BIZnnnnn; see redsys.api.bizum.')
|
|
499
|
+
rtp_description: str | None = Field(None, alias='Ds_RtpDescription')
|
|
500
|
+
rtp_backup_html: str | None = Field(None, alias='Ds_RtpBackupHtml', description='Base64 HTML backup form.')
|
|
501
|
+
rtp_backup_template: str | None = Field(
|
|
502
|
+
None, alias='Ds_RtpBackupTemplate', description='Base64 JSON pieces of a backup form.'
|
|
503
|
+
)
|
|
504
|
+
url_pago_2_fases: str | None = Field(None, alias='Ds_UrlPago2Fases', description='PayGold payment link.')
|
|
505
|
+
|
|
506
|
+
_http_status: int | None = PrivateAttr(None)
|
|
507
|
+
_http_headers: dict[str, str] | None = PrivateAttr(None)
|
|
508
|
+
_raw_body: str | None = PrivateAttr(None)
|
|
276
509
|
|
|
277
510
|
@field_validator('amount', mode='before')
|
|
278
511
|
@classmethod
|
|
279
512
|
def _blank_amount_to_none(cls, value):
|
|
280
513
|
# Keep the raw integer minor units here; scaling needs the currency and
|
|
281
|
-
# is applied in
|
|
514
|
+
# is applied in _from_fields.
|
|
282
515
|
return None if value in (None, '') else value
|
|
283
516
|
|
|
284
517
|
@classmethod
|
|
285
518
|
def from_merchant_parameters(cls, merchant_parameters: bytes) -> 'Response':
|
|
286
|
-
|
|
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)
|
|
287
524
|
if response.amount is not None:
|
|
288
525
|
# scaleb keeps the currency's decimals: 100 EUR minor units read as 1.00, not 1.
|
|
289
526
|
response.amount = response.amount.scaleb(-currency_decimals(response.currency))
|
|
@@ -292,25 +529,50 @@ class Response(BaseModel):
|
|
|
292
529
|
def get_order(self) -> str | None:
|
|
293
530
|
return self.order
|
|
294
531
|
|
|
532
|
+
def _with_transport(self, http_status: int, http_headers: dict[str, str], raw_body: str) -> 'Response':
|
|
533
|
+
self._http_status, self._http_headers, self._raw_body = http_status, http_headers, raw_body
|
|
534
|
+
return self
|
|
535
|
+
|
|
536
|
+
@property
|
|
537
|
+
def http_status(self) -> int | None:
|
|
538
|
+
"""HTTP status of the direct call; ``None`` when parsed from a received payload."""
|
|
539
|
+
return self._http_status
|
|
540
|
+
|
|
541
|
+
@property
|
|
542
|
+
def http_headers(self) -> dict[str, str] | None:
|
|
543
|
+
"""HTTP headers of the direct call; ``None`` when parsed from a received payload."""
|
|
544
|
+
return self._http_headers
|
|
545
|
+
|
|
546
|
+
@property
|
|
547
|
+
def raw_body(self) -> str | None:
|
|
548
|
+
"""Unprocessed HTTP body of the direct call; ``None`` when parsed from a received payload."""
|
|
549
|
+
return self._raw_body
|
|
550
|
+
|
|
295
551
|
@property
|
|
296
552
|
def response_code(self):
|
|
297
|
-
# A 3DS challenge response may carry no Ds_Response.
|
|
298
|
-
# as-is; see docs/response-codes.md for the English meanings.
|
|
553
|
+
# A 3DS challenge response may carry no Ds_Response.
|
|
299
554
|
return int(self.response) if self.response not in (None, '') else None
|
|
300
555
|
|
|
556
|
+
def describe(self, language='es') -> str:
|
|
557
|
+
"""Meaning of ``Ds_Response``, or of ``Ds_ErrorCode`` without it; see ``redsys.codes.describe``."""
|
|
558
|
+
code = self.response if self.response not in (None, '') else self.error_code
|
|
559
|
+
return describe(code, language) if code else ''
|
|
560
|
+
|
|
301
561
|
def is_paid(self) -> bool:
|
|
302
|
-
return
|
|
562
|
+
return (
|
|
563
|
+
self.response_code is not None and responses.AUTHORIZED <= self.response_code <= responses.AUTHORIZED_LAST
|
|
564
|
+
)
|
|
303
565
|
|
|
304
566
|
def is_refunded(self) -> bool:
|
|
305
|
-
return self.response_code ==
|
|
567
|
+
return self.response_code == responses.REFUND_OR_CONFIRMATION_AUTHORIZED
|
|
306
568
|
|
|
307
569
|
def is_canceled(self) -> bool:
|
|
308
|
-
return self.response_code ==
|
|
570
|
+
return self.response_code == responses.CANCELLATION_AUTHORIZED
|
|
309
571
|
|
|
310
572
|
def is_authorized(self) -> bool:
|
|
311
573
|
return self.is_paid() or self.is_refunded() or self.is_canceled()
|
|
312
574
|
|
|
313
|
-
#
|
|
575
|
+
# == EMV 3DS accessors over Ds_EMV3DS ==
|
|
314
576
|
@property
|
|
315
577
|
def _emv3ds(self) -> dict:
|
|
316
578
|
return self.emv3ds or {}
|
|
@@ -336,10 +598,10 @@ class Response(BaseModel):
|
|
|
336
598
|
return self._emv3ds.get('creq')
|
|
337
599
|
|
|
338
600
|
def is_no_3ds(self) -> bool:
|
|
339
|
-
return self.protocol_version ==
|
|
601
|
+
return self.protocol_version == emv3ds.NO_3DS_V2
|
|
340
602
|
|
|
341
603
|
def requires_challenge(self) -> bool:
|
|
342
|
-
return self._emv3ds.get('threeDSInfo') ==
|
|
604
|
+
return self._emv3ds.get('threeDSInfo') == emv3ds.CHALLENGE_REQUEST
|
|
343
605
|
|
|
344
606
|
|
|
345
607
|
__all__ = [
|
redsys/orders.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Order numbers for ``Ds_Merchant_Order``."""
|
|
2
|
+
|
|
3
|
+
from secrets import choice
|
|
4
|
+
from string import ascii_letters, digits
|
|
5
|
+
|
|
6
|
+
_ALPHANUMERIC = ascii_letters + digits
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def generate_order(length: int = 12) -> str:
|
|
10
|
+
"""A random order number of ``length`` characters (4 to 12): 4 digits, then letters and digits.
|
|
11
|
+
|
|
12
|
+
RedSys recommends the 4 leading digits. A random draw makes a repeated order (SIS0051)
|
|
13
|
+
unlikely, not impossible. Raises ``ValueError`` for a length outside 4 to 12.
|
|
14
|
+
"""
|
|
15
|
+
if isinstance(length, bool) or not isinstance(length, int) or not 4 <= length <= 12:
|
|
16
|
+
raise ValueError('length must be an integer from 4 to 12.')
|
|
17
|
+
return ''.join(choice(digits) for _ in range(4)) + ''.join(choice(_ALPHANUMERIC) for _ in range(length - 4))
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
__all__ = ['generate_order']
|