mundosms-sdk 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 MundoSMS
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,83 @@
1
+ Metadata-Version: 2.4
2
+ Name: mundosms-sdk
3
+ Version: 1.0.0
4
+ Summary: Cliente de la API REST v3 de MundoSMS: SMS, WhatsApp, centralita, VozPush y NumCheck. Firma cada petición y reintenta solo lo que es seguro repetir. Sin dependencias.
5
+ Author: MundoSMS
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://www.mundosms.es/api-v3
8
+ Project-URL: Documentation, https://www.mundosms.es/api-v3
9
+ Project-URL: Source, https://github.com/mundosms/mundosms-sdk
10
+ Project-URL: Changelog, https://github.com/mundosms/mundosms-sdk/blob/main/CHANGELOG.md
11
+ Project-URL: Issues, https://github.com/mundosms/mundosms-sdk/issues
12
+ Keywords: mundosms,sms,whatsapp,voip,click2dial,centralita,api,sdk
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Topic :: Communications :: Telephony
19
+ Classifier: Topic :: Software Development :: Libraries
20
+ Requires-Python: >=3.8
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Dynamic: license-file
24
+
25
+ # mundosms
26
+
27
+ Cliente Python de la [API REST v3 de MundoSMS](https://www.mundosms.es/api-v3): centralita, llamadas, SMS, VozPush,
28
+ NumCheck y WhatsApp. Firma cada petición por ti (`X-Timestamp` en milisegundos y la firma HMAC de tu API Key), pone una
29
+ `Idempotency-Key` en cada `POST` para que un reintento no envíe nada dos veces, y reintenta solo lo que es seguro repetir.
30
+ Comprueba también la firma de los avisos que te mandamos. Sin dependencias: solo la biblioteca estándar.
31
+
32
+ Requiere Python 3.8 o superior.
33
+
34
+ ```sh
35
+ pip install mundosms-sdk
36
+ ```
37
+
38
+ Las API Keys (token y clave privada) se crean en el panel de MundoSMS, en **API y Soporte → Claves de API**.
39
+
40
+ ## Uso
41
+
42
+ ```python
43
+ from mundosms import MundoSMS, MundoSMSError
44
+
45
+ api = MundoSMS("TU_TOKEN", "TU_CLAVE_PRIVADA") # la clave privada, "" si tu API Key no exige firma
46
+ r = api.post("/sms", {"to": "34600123456", "text": "Tu cita es mañana a las 10:00", "from": "MiClinica"})
47
+ print(r["data"]["id"])
48
+
49
+ for call in api.all("/calls", {"from_datetime": "2026-11-01"}):
50
+ print(call["type"], call["id"], call["state"])
51
+
52
+ try:
53
+ api.patch("/extensions/recepcion", {"record_calls": True})
54
+ except MundoSMSError as e:
55
+ print(e.http, e.status_code, e.message, e.detail, e.request_id)
56
+ ```
57
+
58
+ - `get(path, query)`, `post(path, data)`, `patch(path, data)` y `delete(path, query)` devuelven la respuesta entera
59
+ (`status`, `status_code`, `message`, `data`). La ruta va sin `/v3`. En `get` y `delete` los filtros van en la query; en
60
+ `post` y `patch`, los datos van en un cuerpo JSON. `request(method, path, data)` hace una petición cualquiera.
61
+ - `all(path, query)` recorre todas las páginas de un listado y te da los elementos uno a uno. Al acabar, el último
62
+ `next_cursor` queda en `last_cursor`.
63
+ - Las rutas que devuelven un fichero (una grabación, una locución, el PDF de un certificado) vuelven como
64
+ `{"status": "success", "content_type": …, "body": …}`, con el contenido en `bytes`.
65
+ - Cualquier error es una excepción `MundoSMSError` con `http`, `status_code`, `message`, `detail`, `data`, `request_id` y
66
+ `response` (la respuesta entera), siempre que la API contesta con `"status": "error"`. Un WhatsApp sin confirmar (`202`,
67
+ `data["state"]` `"unknown"`: puede haber salido) no es un error: vuelve la respuesta, y no se reenvía.
68
+ - Cada `POST` lleva una `Idempotency-Key`, la misma en todos sus intentos: por eso se reintenta sin miedo si se queda sin
69
+ respuesta. La tuya (el id de tu pedido, por ejemplo): `api.post(path, data, idempotency_key="pedido-881")`. Si la API
70
+ devuelve la respuesta guardada de la primera vez, trae `"idempotent_replayed": True`.
71
+ - `MundoSMS.verify_webhook(secret, header, body)` comprueba la cabecera `X-MundoSMS-Signature` de un aviso que te llega
72
+ (de `callback_url` o un webhook de WhatsApp), con el cuerpo tal cual llegó (`bytes`): `True` o `False`.
73
+ - Opciones, con nombre: `MundoSMS(token, private_key, base_url=…, retries=3, timeout=60)`.
74
+
75
+ ## Documentación
76
+
77
+ La referencia completa de cada ruta, sus parámetros y sus respuestas: **[www.mundosms.es/api-v3](https://www.mundosms.es/api-v3)**.
78
+ El código, los clientes en PHP, Node.js, Java y C# y los cambios de cada versión:
79
+ [github.com/mundosms/mundosms-sdk](https://github.com/mundosms/mundosms-sdk).
80
+
81
+ ## Licencia
82
+
83
+ MIT.
@@ -0,0 +1,59 @@
1
+ # mundosms
2
+
3
+ Cliente Python de la [API REST v3 de MundoSMS](https://www.mundosms.es/api-v3): centralita, llamadas, SMS, VozPush,
4
+ NumCheck y WhatsApp. Firma cada petición por ti (`X-Timestamp` en milisegundos y la firma HMAC de tu API Key), pone una
5
+ `Idempotency-Key` en cada `POST` para que un reintento no envíe nada dos veces, y reintenta solo lo que es seguro repetir.
6
+ Comprueba también la firma de los avisos que te mandamos. Sin dependencias: solo la biblioteca estándar.
7
+
8
+ Requiere Python 3.8 o superior.
9
+
10
+ ```sh
11
+ pip install mundosms-sdk
12
+ ```
13
+
14
+ Las API Keys (token y clave privada) se crean en el panel de MundoSMS, en **API y Soporte → Claves de API**.
15
+
16
+ ## Uso
17
+
18
+ ```python
19
+ from mundosms import MundoSMS, MundoSMSError
20
+
21
+ api = MundoSMS("TU_TOKEN", "TU_CLAVE_PRIVADA") # la clave privada, "" si tu API Key no exige firma
22
+ r = api.post("/sms", {"to": "34600123456", "text": "Tu cita es mañana a las 10:00", "from": "MiClinica"})
23
+ print(r["data"]["id"])
24
+
25
+ for call in api.all("/calls", {"from_datetime": "2026-11-01"}):
26
+ print(call["type"], call["id"], call["state"])
27
+
28
+ try:
29
+ api.patch("/extensions/recepcion", {"record_calls": True})
30
+ except MundoSMSError as e:
31
+ print(e.http, e.status_code, e.message, e.detail, e.request_id)
32
+ ```
33
+
34
+ - `get(path, query)`, `post(path, data)`, `patch(path, data)` y `delete(path, query)` devuelven la respuesta entera
35
+ (`status`, `status_code`, `message`, `data`). La ruta va sin `/v3`. En `get` y `delete` los filtros van en la query; en
36
+ `post` y `patch`, los datos van en un cuerpo JSON. `request(method, path, data)` hace una petición cualquiera.
37
+ - `all(path, query)` recorre todas las páginas de un listado y te da los elementos uno a uno. Al acabar, el último
38
+ `next_cursor` queda en `last_cursor`.
39
+ - Las rutas que devuelven un fichero (una grabación, una locución, el PDF de un certificado) vuelven como
40
+ `{"status": "success", "content_type": …, "body": …}`, con el contenido en `bytes`.
41
+ - Cualquier error es una excepción `MundoSMSError` con `http`, `status_code`, `message`, `detail`, `data`, `request_id` y
42
+ `response` (la respuesta entera), siempre que la API contesta con `"status": "error"`. Un WhatsApp sin confirmar (`202`,
43
+ `data["state"]` `"unknown"`: puede haber salido) no es un error: vuelve la respuesta, y no se reenvía.
44
+ - Cada `POST` lleva una `Idempotency-Key`, la misma en todos sus intentos: por eso se reintenta sin miedo si se queda sin
45
+ respuesta. La tuya (el id de tu pedido, por ejemplo): `api.post(path, data, idempotency_key="pedido-881")`. Si la API
46
+ devuelve la respuesta guardada de la primera vez, trae `"idempotent_replayed": True`.
47
+ - `MundoSMS.verify_webhook(secret, header, body)` comprueba la cabecera `X-MundoSMS-Signature` de un aviso que te llega
48
+ (de `callback_url` o un webhook de WhatsApp), con el cuerpo tal cual llegó (`bytes`): `True` o `False`.
49
+ - Opciones, con nombre: `MundoSMS(token, private_key, base_url=…, retries=3, timeout=60)`.
50
+
51
+ ## Documentación
52
+
53
+ La referencia completa de cada ruta, sus parámetros y sus respuestas: **[www.mundosms.es/api-v3](https://www.mundosms.es/api-v3)**.
54
+ El código, los clientes en PHP, Node.js, Java y C# y los cambios de cada versión:
55
+ [github.com/mundosms/mundosms-sdk](https://github.com/mundosms/mundosms-sdk).
56
+
57
+ ## Licencia
58
+
59
+ MIT.
@@ -0,0 +1,363 @@
1
+ """MundoSMS API v3 — cliente Python en un solo fichero (Python 3.8 o superior). Sin dependencias.
2
+ Documentación: https://www.mundosms.es/api-v3
3
+ Código y versiones: https://github.com/mundosms/mundosms-sdk (licencia MIT)
4
+
5
+ from mundosms import MundoSMS, MundoSMSError
6
+ api = MundoSMS("TOKEN", "CLAVE_PRIVADA") # la clave privada, "" si tu API Key no exige firma
7
+ r = api.post("/sms", {"to": "34600123456", "text": "Hola", "from": "MiEmpresa"})
8
+ print(r["data"]["id"])
9
+ for call in api.all("/calls", {"from_datetime": "2026-11-01", "stop_at_ongoing": True}):
10
+ ...
11
+
12
+ Errores: excepción MundoSMSError con .http (código HTTP), .status_code ("3", "4"…), .message (también str(e)), .detail,
13
+ .data, .response (la respuesta entera) y .request_id (la cabecera X-Request-Id). También cuando la API contesta con
14
+ "status": "error", venga con el código HTTP que venga. Un WhatsApp sin confirmar (202) no es un error: vuelve la respuesta,
15
+ con data["state"] "unknown".
16
+ Cada POST lleva una Idempotency-Key (un UUID nuevo en cada llamada, la misma en todos sus intentos; la tuya, con
17
+ post(path, data, idempotency_key="pedido-881")). Por eso un POST que falla por la red, o con 409 «Request in progress», se
18
+ repite sin miedo: la API no lo hace dos veces. Si la respuesta es la guardada de la primera vez, trae
19
+ "idempotent_replayed": True.
20
+ Reintenta: un 429, en cualquier método (no se hizo nada); un fallo de red, en cualquier método; un 5xx, solo en GET (un POST
21
+ con 5xx no se repite: la API no guarda los 5xx, y repetirlo lo haría otra vez). Espera lo que diga Retry-After (como mucho
22
+ 60 s) o, si no lo trae, 1, 2, 4… s.
23
+ Los avisos que te mandamos (callback_url y webhooks de WhatsApp) se comprueban con MundoSMS.verify_webhook().
24
+ """
25
+ import base64
26
+ import hashlib
27
+ import hmac
28
+ import http.client
29
+ import json
30
+ import re
31
+ import socket
32
+ import threading
33
+ import time
34
+ import uuid
35
+ import urllib.error
36
+ import urllib.parse
37
+ import urllib.request
38
+ from email.utils import parsedate_to_datetime
39
+
40
+ __version__ = "1.0.0"
41
+ MAX_RETRY_WAIT = 60 # segundos: lo más que se espera antes de un reintento, aunque Retry-After pida más
42
+ WEBHOOK_TOLERANCE = 300 # segundos: lo más que puede alejarse de tu hora la «t» de la firma de un aviso
43
+ _IDEMPOTENCY_KEY = re.compile(r"[A-Za-z0-9_.:-]{1,64}") # la forma que exige la API para la Idempotency-Key
44
+
45
+
46
+ class MundoSMSError(Exception):
47
+ """El error de cualquier petición: un 4xx o un 5xx, una respuesta 2xx con "status": "error" o, sin respuesta (la red o
48
+ el plazo agotado), http 0 y un mensaje que empieza por «No response from the API:»."""
49
+
50
+ def __init__(self, message, http=0, status_code=None, detail=None, response=None, data=None, request_id=None):
51
+ super().__init__(message)
52
+ self.message = message # el message de la API ("Call not found"…) o el del SDK
53
+ self.http = http # el código HTTP; 0 si no hubo respuesta
54
+ self.status_code = status_code # el status_code de la API, como texto ("3", "4", "12"…)
55
+ self.detail = detail # el detail de la respuesta, si lo trae
56
+ self.response = response # la respuesta entera, decodificada; None si no era JSON
57
+ self.data = data # el data de la respuesta (en WhatsApp, el id del mensaje que puede haber salido)
58
+ self.request_id = request_id # la cabecera X-Request-Id: con ella encuentras la petición en Logs API
59
+
60
+
61
+ class MundoSMS:
62
+ def __init__(self, token, private_key="", *, base_url="https://api.mundosms.es/v3", retries=3, timeout=60):
63
+ """token: el Token de tu API Key (empieza por eyJ); private_key: su clave privada si exige firma (lo normal), o "".
64
+ retries: cuántas veces se reintenta lo que es seguro repetir (0, ninguna). timeout: los segundos que puede durar cada
65
+ petición entera (conectar, mandar y recibir la respuesta)."""
66
+ self._token = token.strip()
67
+ self._private_key = (private_key or "").strip()
68
+ self.base_url = base_url.rstrip("/")
69
+ self.retries = retries
70
+ self.timeout = timeout
71
+ self.last_cursor = None # el de all(): guárdalo para la siguiente sincronización
72
+
73
+ def __repr__(self):
74
+ return "MundoSMS(base_url=%r)" % self.base_url # sin el token ni la clave: que no acaben en un log
75
+
76
+ def get(self, path, query=None):
77
+ """GET: query va en la query."""
78
+ return self.request("GET", path, query)
79
+
80
+ def post(self, path, data=None, *, idempotency_key=None):
81
+ """POST: data va en un cuerpo JSON. idempotency_key: tu clave para que repetir este POST no lo vuelva a hacer (por
82
+ ejemplo, el id de tu pedido); sin ella, un UUID nuevo en cada llamada."""
83
+ return self.request("POST", path, data, idempotency_key=idempotency_key)
84
+
85
+ def patch(self, path, data):
86
+ """PATCH: data va en un cuerpo JSON."""
87
+ return self.request("PATCH", path, data)
88
+
89
+ def delete(self, path, query=None):
90
+ """DELETE: query va en la query."""
91
+ return self.request("DELETE", path, query)
92
+
93
+ def all(self, path, query=None):
94
+ """Recorre un listado entero, página a página, siguiendo su cursor (next_cursor), elemento a elemento. Cada página
95
+ lleva los mismos filtros (y el mismo order) más el cursor. Para sincronizar, guarda tú last_cursor: la siguiente vez
96
+ empiezas desde ahí, pasándolo como cursor."""
97
+ query = dict(query or {})
98
+ list_key = None
99
+ while True:
100
+ data = self.get(path, query).get("data") or {}
101
+ if list_key is None:
102
+ list_key = next((k for k, v in data.items() if isinstance(v, list)), None)
103
+ for item in (data.get(list_key) or []) if list_key else []:
104
+ yield item
105
+ self.last_cursor = data.get("next_cursor")
106
+ if not data.get("has_more") or not data.get("results") or not data.get("next_cursor"):
107
+ return
108
+ query["cursor"] = data["next_cursor"]
109
+
110
+ def request(self, method, path, data=None, *, idempotency_key=None):
111
+ """Una petición cualquiera. path: "/calls", "/numbers/34910123456"… (sin /v3: si lo lleva, se quita). Si la ruta trae
112
+ "?…", esos parámetros se juntan con data (gana data). En GET y DELETE, data va en la query; en POST y PATCH, en el
113
+ cuerpo JSON. Devuelve la respuesta decodificada.
114
+ idempotency_key: la Idempotency-Key (en un POST, sin ella, un UUID nuevo); la API la tiene en cuenta en los POST."""
115
+ method = method.upper()
116
+ idem_key = _idempotency_key(idempotency_key, method) # antes de nada: con una clave mala no se manda nada
117
+ base_path = urllib.parse.urlsplit(self.base_url).path
118
+ encoded_path, path_query = _split_path(path, base_path.endswith("/v3"))
119
+ data = data or {}
120
+ body = ""
121
+ if method in ("GET", "DELETE"):
122
+ path_query.update(data)
123
+ elif data:
124
+ body = json.dumps(data, ensure_ascii=False, separators=(",", ":"))
125
+ query = "&".join(_q(str(k)) + "=" + _q(t) for k, t in ((k, _query_value(v)) for k, v in path_query.items()) if t is not None)
126
+ rest = encoded_path + ("?" + query if query else "")
127
+ url = self.base_url + rest
128
+ signed_path = base_path + rest # lo que se firma es justo lo que se manda
129
+ attempt = 0
130
+ while True:
131
+ attempt += 1
132
+ ts = str(int(time.time() * 1000)) # milisegundos: dos peticiones iguales seguidas no firman igual
133
+ headers = {"Authorization": "Bearer " + self._token, "X-Timestamp": ts, "Accept": "application/json",
134
+ "User-Agent": "MundoSMS-Python/" + __version__}
135
+ if body:
136
+ headers["Content-Type"] = "application/json"
137
+ if idem_key:
138
+ headers["Idempotency-Key"] = idem_key # la misma en todos los intentos de esta llamada
139
+ if self._private_key:
140
+ signed = (self._token + "." + ts + "." + method + " " + signed_path + "." + body).encode()
141
+ headers["X-Signature"] = base64.urlsafe_b64encode(
142
+ hmac.new(self._private_key.encode(), signed, hashlib.sha256).digest()).rstrip(b"=").decode()
143
+ req = urllib.request.Request(url, data=body.encode() if body else None, headers=headers, method=method)
144
+ http_, resp_headers, resp, network_error = 0, {}, b"", ""
145
+ deadline = _Deadline(self.timeout)
146
+ try:
147
+ try:
148
+ r = urllib.request.build_opener(_Http(deadline), _Https(deadline)).open(req, timeout=self.timeout)
149
+ except urllib.error.HTTPError as e:
150
+ r = e
151
+ with r:
152
+ http_, resp_headers, resp = r.getcode(), r.headers, r.read()
153
+ except (urllib.error.URLError, OSError, http.client.HTTPException) as e:
154
+ network_error = str(getattr(e, "reason", None) or e)
155
+ finally:
156
+ deadline.stop()
157
+ if deadline.expired:
158
+ network_error = "timed out after %s s" % self.timeout
159
+ j = None
160
+ if network_error:
161
+ http_ = 0 # se cortó a medias: es un fallo de red aunque llegara la cabecera
162
+ else:
163
+ try:
164
+ j = json.loads(resp)
165
+ except ValueError:
166
+ j = None
167
+ if _retryable(method, bool(network_error), http_, j, idem_key) and attempt <= self.retries:
168
+ time.sleep(_retry_wait(resp_headers.get("Retry-After"), attempt))
169
+ continue
170
+ if network_error:
171
+ raise MundoSMSError("No response from the API: " + network_error)
172
+ replayed = str(resp_headers.get("Idempotent-Replayed", "")).strip().lower() == "true"
173
+ if replayed and isinstance(j, dict):
174
+ j["idempotent_replayed"] = True # la respuesta guardada de la primera vez: no se ha vuelto a hacer
175
+ if 200 <= http_ < 300:
176
+ if not isinstance(j, dict): # un fichero
177
+ file = {"status": "success", "content_type": resp_headers.get("Content-Type", ""), "body": resp}
178
+ if replayed:
179
+ file["idempotent_replayed"] = True
180
+ return file
181
+ if j.get("status") != "error":
182
+ return j
183
+ rid = resp_headers.get("X-Request-Id")
184
+ if isinstance(j, dict):
185
+ raise MundoSMSError(j.get("message", "Error"), http_, j.get("status_code"), j.get("detail"), j, j.get("data"), rid)
186
+ raise MundoSMSError("HTTP %d" % http_, http_, request_id=rid)
187
+
188
+ @staticmethod
189
+ def verify_webhook(secret, header, body, tolerance=WEBHOOK_TOLERANCE):
190
+ """True si un aviso que te llega (callback_url o webhook de WhatsApp) es nuestro y nadie lo ha tocado.
191
+ secret: el de «API y Soporte → Webhooks» (whsec_…); header: X-MundoSMS-Signature; body: el cuerpo TAL CUAL llegó
192
+ (bytes, o str en UTF-8), sin volver a serializar el JSON; tolerance: los segundos que puede alejarse «t» de tu hora.
193
+ Una cabecera que falta o está mal formada da False, sin excepción."""
194
+ if isinstance(body, str):
195
+ body = body.encode("utf-8")
196
+ elif isinstance(body, (bytearray, memoryview)):
197
+ body = bytes(body)
198
+ elif not isinstance(body, bytes):
199
+ raise TypeError("MundoSMS.verify_webhook: pass the raw body as received (bytes or str), not a decoded value")
200
+ secret = secret.strip() if isinstance(secret, str) else ""
201
+ if not secret or not isinstance(header, str):
202
+ return False
203
+ t, signatures = None, []
204
+ for part in header.split(","):
205
+ k, equals, v = part.partition("=")
206
+ k, v = k.strip(), v.strip()
207
+ if not equals:
208
+ continue
209
+ if k == "t":
210
+ if t is not None:
211
+ return False # dos «t»: no se sabe cuál vale
212
+ t = v
213
+ elif k == "v1":
214
+ signatures.append(v.lower())
215
+ if t is None or not re.fullmatch(r"[0-9]{1,15}", t) or not signatures:
216
+ return False
217
+ if abs(int(time.time()) - int(t)) > tolerance:
218
+ return False
219
+ expected = hmac.new(secret.encode("utf-8"), t.encode() + b"." + body, hashlib.sha256).hexdigest().encode()
220
+ valid = False
221
+ for sig in signatures: # todas, sin cortar en la primera: compare_digest es de tiempo constante
222
+ if re.fullmatch(r"[0-9a-f]{64}", sig) and hmac.compare_digest(expected, sig.encode()):
223
+ valid = True
224
+ return valid
225
+
226
+
227
+ def _idempotency_key(key, method):
228
+ """La Idempotency-Key de la llamada: la tuya, si tiene la forma que exige la API; en un POST sin ella, un UUID v4 nuevo."""
229
+ if key is None:
230
+ return str(uuid.uuid4()) if method == "POST" else None
231
+ if not isinstance(key, str) or not _IDEMPOTENCY_KEY.fullmatch(key):
232
+ raise ValueError("MundoSMS: idempotency_key must be 1 to 64 characters: A-Z, a-z, 0-9 and _ . : - (nothing was sent)")
233
+ return key
234
+
235
+
236
+ def _retryable(method, network, http_, j, idem_key):
237
+ """Si se puede repetir: un 429 en cualquier método; un GET, ante un fallo de red o un 5xx; un PATCH o un DELETE, ante un
238
+ fallo de red; un POST (con su Idempotency-Key), ante un fallo de red o un 409 «Request in progress». Un 5xx de un POST no:
239
+ la API no guarda los 5xx y repetirlo lo haría otra vez. Un 409 «Duplicated request» (la MISMA petición firmada llegó dos
240
+ veces: la repitió algo entre medias, como hace un cliente HTTP con una conexión que se cerró) es un fallo de red más."""
241
+ if http_ == 429:
242
+ return True
243
+ message = j.get("message") if isinstance(j, dict) else None
244
+ network = network or (http_ == 409 and isinstance(message, str) and message.startswith("Duplicated request"))
245
+ if method == "GET":
246
+ return network or http_ >= 500
247
+ if method in ("PATCH", "DELETE"):
248
+ return network
249
+ if idem_key:
250
+ return network or (http_ == 409 and message == "Request in progress")
251
+ return False
252
+
253
+
254
+ def _q(s):
255
+ """RFC 3986: todo codificado menos A-Z a-z 0-9 - . _ ~"""
256
+ return urllib.parse.quote(s, safe="")
257
+
258
+
259
+ def _query_value(v):
260
+ """Un valor de la query: true/false, una lista separada por comas; None o una lista vacía (o solo de None), nada."""
261
+ if v is None:
262
+ return None
263
+ if isinstance(v, bool):
264
+ return "true" if v else "false"
265
+ if isinstance(v, (list, tuple)):
266
+ items = [t for t in map(_query_value, v) if t is not None]
267
+ return ",".join(items) if items else None
268
+ return str(v)
269
+
270
+
271
+ def _split_path(path, strip_v3):
272
+ """La ruta codificada trozo a trozo (un %XX ya escrito se respeta), sin el /v3 del principio si la base ya lo lleva,
273
+ y los parámetros que traiga tras «?»."""
274
+ path, _, query = str(path).partition("?")
275
+ path_query = dict(urllib.parse.parse_qsl(query, keep_blank_values=True))
276
+ path = "/" + path.lstrip("/")
277
+ if strip_v3 and (path == "/v3" or path.startswith("/v3/")):
278
+ path = "/" + path[3:].lstrip("/")
279
+ segments = ("".join(p if i % 2 else _q(p) for i, p in enumerate(re.split(r"(%[0-9A-Fa-f]{2})", seg))) for seg in path.split("/"))
280
+ return "/".join(segments), path_query
281
+
282
+
283
+ def _retry_wait(retry_after, attempt):
284
+ """Segundos antes del siguiente intento: lo que pida Retry-After (segundos o fecha HTTP), o 1, 2, 4… Como mucho 60."""
285
+ s = None
286
+ if retry_after:
287
+ try:
288
+ s = float(retry_after)
289
+ except ValueError:
290
+ try:
291
+ s = parsedate_to_datetime(retry_after).timestamp() - time.time()
292
+ except (TypeError, ValueError, IndexError, OverflowError):
293
+ s = None
294
+ if s is None or s != s: # sin cabecera, o NaN
295
+ s = 2 ** (attempt - 1)
296
+ return max(0.0, min(MAX_RETRY_WAIT, s))
297
+
298
+
299
+ class _Deadline:
300
+ """El plazo de la petición ENTERA (conectar, mandar y leer la respuesta): el timeout de urllib es por cada operación del
301
+ socket, y una respuesta que llega poco a poco no lo agota nunca. Al vencer, corta la conexión."""
302
+
303
+ def __init__(self, timeout):
304
+ self.expired = False
305
+ self._socks = []
306
+ self._lock = threading.Lock()
307
+ self._timer = threading.Timer(timeout, self._expire) if timeout is not None else None
308
+ if self._timer:
309
+ self._timer.daemon = True
310
+ self._timer.start()
311
+
312
+ def watch(self, sock):
313
+ with self._lock:
314
+ self._socks.append(sock)
315
+ if self.expired:
316
+ _shutdown(sock)
317
+
318
+ def _expire(self):
319
+ with self._lock:
320
+ self.expired = True
321
+ for s in self._socks:
322
+ _shutdown(s)
323
+
324
+ def stop(self):
325
+ if self._timer:
326
+ self._timer.cancel()
327
+
328
+
329
+ def _shutdown(sock):
330
+ try:
331
+ socket.socket.shutdown(sock, socket.SHUT_RDWR) # el del socket de debajo, también si es TLS: despierta al que lee
332
+ except OSError:
333
+ pass
334
+
335
+
336
+ class _Watched:
337
+ """Manejador de urllib que pone bajo el reloj cada conexión que abre."""
338
+
339
+ def __init__(self, deadline):
340
+ super().__init__()
341
+ self.deadline = deadline
342
+
343
+ def do_open(self, conn_class, req, **kw):
344
+ deadline = self.deadline
345
+
346
+ def open_conn(*a, **k):
347
+ c = conn_class(*a, **k)
348
+ original_connect = c.connect
349
+
350
+ def connect():
351
+ original_connect()
352
+ deadline.watch(c.sock)
353
+ c.connect = connect
354
+ return c
355
+ return super().do_open(open_conn, req, **kw)
356
+
357
+
358
+ class _Http(_Watched, urllib.request.HTTPHandler):
359
+ pass
360
+
361
+
362
+ class _Https(_Watched, urllib.request.HTTPSHandler):
363
+ pass
@@ -0,0 +1,83 @@
1
+ Metadata-Version: 2.4
2
+ Name: mundosms-sdk
3
+ Version: 1.0.0
4
+ Summary: Cliente de la API REST v3 de MundoSMS: SMS, WhatsApp, centralita, VozPush y NumCheck. Firma cada petición y reintenta solo lo que es seguro repetir. Sin dependencias.
5
+ Author: MundoSMS
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://www.mundosms.es/api-v3
8
+ Project-URL: Documentation, https://www.mundosms.es/api-v3
9
+ Project-URL: Source, https://github.com/mundosms/mundosms-sdk
10
+ Project-URL: Changelog, https://github.com/mundosms/mundosms-sdk/blob/main/CHANGELOG.md
11
+ Project-URL: Issues, https://github.com/mundosms/mundosms-sdk/issues
12
+ Keywords: mundosms,sms,whatsapp,voip,click2dial,centralita,api,sdk
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Topic :: Communications :: Telephony
19
+ Classifier: Topic :: Software Development :: Libraries
20
+ Requires-Python: >=3.8
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Dynamic: license-file
24
+
25
+ # mundosms
26
+
27
+ Cliente Python de la [API REST v3 de MundoSMS](https://www.mundosms.es/api-v3): centralita, llamadas, SMS, VozPush,
28
+ NumCheck y WhatsApp. Firma cada petición por ti (`X-Timestamp` en milisegundos y la firma HMAC de tu API Key), pone una
29
+ `Idempotency-Key` en cada `POST` para que un reintento no envíe nada dos veces, y reintenta solo lo que es seguro repetir.
30
+ Comprueba también la firma de los avisos que te mandamos. Sin dependencias: solo la biblioteca estándar.
31
+
32
+ Requiere Python 3.8 o superior.
33
+
34
+ ```sh
35
+ pip install mundosms-sdk
36
+ ```
37
+
38
+ Las API Keys (token y clave privada) se crean en el panel de MundoSMS, en **API y Soporte → Claves de API**.
39
+
40
+ ## Uso
41
+
42
+ ```python
43
+ from mundosms import MundoSMS, MundoSMSError
44
+
45
+ api = MundoSMS("TU_TOKEN", "TU_CLAVE_PRIVADA") # la clave privada, "" si tu API Key no exige firma
46
+ r = api.post("/sms", {"to": "34600123456", "text": "Tu cita es mañana a las 10:00", "from": "MiClinica"})
47
+ print(r["data"]["id"])
48
+
49
+ for call in api.all("/calls", {"from_datetime": "2026-11-01"}):
50
+ print(call["type"], call["id"], call["state"])
51
+
52
+ try:
53
+ api.patch("/extensions/recepcion", {"record_calls": True})
54
+ except MundoSMSError as e:
55
+ print(e.http, e.status_code, e.message, e.detail, e.request_id)
56
+ ```
57
+
58
+ - `get(path, query)`, `post(path, data)`, `patch(path, data)` y `delete(path, query)` devuelven la respuesta entera
59
+ (`status`, `status_code`, `message`, `data`). La ruta va sin `/v3`. En `get` y `delete` los filtros van en la query; en
60
+ `post` y `patch`, los datos van en un cuerpo JSON. `request(method, path, data)` hace una petición cualquiera.
61
+ - `all(path, query)` recorre todas las páginas de un listado y te da los elementos uno a uno. Al acabar, el último
62
+ `next_cursor` queda en `last_cursor`.
63
+ - Las rutas que devuelven un fichero (una grabación, una locución, el PDF de un certificado) vuelven como
64
+ `{"status": "success", "content_type": …, "body": …}`, con el contenido en `bytes`.
65
+ - Cualquier error es una excepción `MundoSMSError` con `http`, `status_code`, `message`, `detail`, `data`, `request_id` y
66
+ `response` (la respuesta entera), siempre que la API contesta con `"status": "error"`. Un WhatsApp sin confirmar (`202`,
67
+ `data["state"]` `"unknown"`: puede haber salido) no es un error: vuelve la respuesta, y no se reenvía.
68
+ - Cada `POST` lleva una `Idempotency-Key`, la misma en todos sus intentos: por eso se reintenta sin miedo si se queda sin
69
+ respuesta. La tuya (el id de tu pedido, por ejemplo): `api.post(path, data, idempotency_key="pedido-881")`. Si la API
70
+ devuelve la respuesta guardada de la primera vez, trae `"idempotent_replayed": True`.
71
+ - `MundoSMS.verify_webhook(secret, header, body)` comprueba la cabecera `X-MundoSMS-Signature` de un aviso que te llega
72
+ (de `callback_url` o un webhook de WhatsApp), con el cuerpo tal cual llegó (`bytes`): `True` o `False`.
73
+ - Opciones, con nombre: `MundoSMS(token, private_key, base_url=…, retries=3, timeout=60)`.
74
+
75
+ ## Documentación
76
+
77
+ La referencia completa de cada ruta, sus parámetros y sus respuestas: **[www.mundosms.es/api-v3](https://www.mundosms.es/api-v3)**.
78
+ El código, los clientes en PHP, Node.js, Java y C# y los cambios de cada versión:
79
+ [github.com/mundosms/mundosms-sdk](https://github.com/mundosms/mundosms-sdk).
80
+
81
+ ## Licencia
82
+
83
+ MIT.
@@ -0,0 +1,8 @@
1
+ LICENSE
2
+ README.md
3
+ mundosms.py
4
+ pyproject.toml
5
+ mundosms_sdk.egg-info/PKG-INFO
6
+ mundosms_sdk.egg-info/SOURCES.txt
7
+ mundosms_sdk.egg-info/dependency_links.txt
8
+ mundosms_sdk.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ mundosms
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["setuptools==80.9.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "mundosms-sdk"
7
+ dynamic = ["version"]
8
+ description = "Cliente de la API REST v3 de MundoSMS: SMS, WhatsApp, centralita, VozPush y NumCheck. Firma cada petición y reintenta solo lo que es seguro repetir. Sin dependencias."
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "MundoSMS" }]
14
+ keywords = ["mundosms", "sms", "whatsapp", "voip", "click2dial", "centralita", "api", "sdk"]
15
+ classifiers = [
16
+ "Development Status :: 5 - Production/Stable",
17
+ "Intended Audience :: Developers",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3 :: Only",
21
+ "Topic :: Communications :: Telephony",
22
+ "Topic :: Software Development :: Libraries",
23
+ ]
24
+
25
+ [project.urls]
26
+ Homepage = "https://www.mundosms.es/api-v3"
27
+ Documentation = "https://www.mundosms.es/api-v3"
28
+ Source = "https://github.com/mundosms/mundosms-sdk"
29
+ Changelog = "https://github.com/mundosms/mundosms-sdk/blob/main/CHANGELOG.md"
30
+ Issues = "https://github.com/mundosms/mundosms-sdk/issues"
31
+
32
+ [tool.setuptools]
33
+ py-modules = ["mundosms"]
34
+
35
+ [tool.setuptools.dynamic]
36
+ # la versión es la de mundosms.py (__version__)
37
+ version = { attr = "mundosms.__version__" }
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+