smepay 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- smepay/__init__.py +30 -0
- smepay/_auth.py +63 -0
- smepay/_client.py +74 -0
- smepay/_errors.py +38 -0
- smepay/_http.py +103 -0
- smepay/_payment.py +69 -0
- smepay/_types.py +81 -0
- smepay/_version.py +2 -0
- smepay/py.typed +0 -0
- smepay-0.1.0.dist-info/METADATA +122 -0
- smepay-0.1.0.dist-info/RECORD +13 -0
- smepay-0.1.0.dist-info/WHEEL +4 -0
- smepay-0.1.0.dist-info/licenses/LICENSE +21 -0
smepay/__init__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Official Python SDK for the SMEPay External API.
|
|
2
|
+
|
|
3
|
+
Wraps the three payment calls (create, initiate, get status) and handles
|
|
4
|
+
authentication, token reuse and errors for you. Use it only on your server.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from ._client import Environment, SMEPay
|
|
8
|
+
from ._errors import SMEPayError
|
|
9
|
+
from ._payment import PaymentResource
|
|
10
|
+
from ._types import (
|
|
11
|
+
CreateResponse,
|
|
12
|
+
CustomerDetails,
|
|
13
|
+
GetStatusResponse,
|
|
14
|
+
InitiateResponse,
|
|
15
|
+
PaymentStatus,
|
|
16
|
+
)
|
|
17
|
+
from ._version import __version__
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"CreateResponse",
|
|
21
|
+
"CustomerDetails",
|
|
22
|
+
"Environment",
|
|
23
|
+
"GetStatusResponse",
|
|
24
|
+
"InitiateResponse",
|
|
25
|
+
"PaymentResource",
|
|
26
|
+
"PaymentStatus",
|
|
27
|
+
"SMEPay",
|
|
28
|
+
"SMEPayError",
|
|
29
|
+
"__version__",
|
|
30
|
+
]
|
smepay/_auth.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import threading
|
|
4
|
+
import time
|
|
5
|
+
|
|
6
|
+
from ._errors import SMEPayError
|
|
7
|
+
from ._http import post_json
|
|
8
|
+
|
|
9
|
+
_AUTH_PATH = "/api/external/auth"
|
|
10
|
+
# Fetch a new token when less than this many seconds of its lifetime are left.
|
|
11
|
+
_REFRESH_MARGIN_SECONDS = 60.0
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class TokenManager:
|
|
15
|
+
"""Logs in with client_id/client_secret and caches the access token.
|
|
16
|
+
|
|
17
|
+
The lock is held during login, so concurrent threads share a single login.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
def __init__(self, base_url: str, client_id: str, client_secret: str) -> None:
|
|
21
|
+
self._base_url = base_url
|
|
22
|
+
self._client_id = client_id
|
|
23
|
+
self._client_secret = client_secret
|
|
24
|
+
self._lock = threading.Lock()
|
|
25
|
+
self._token: str | None = None
|
|
26
|
+
self._expires_at = 0.0
|
|
27
|
+
|
|
28
|
+
def __repr__(self) -> str:
|
|
29
|
+
return "TokenManager()"
|
|
30
|
+
|
|
31
|
+
def get_token(self) -> str:
|
|
32
|
+
"""Return the cached token, or log in if there is none or it is about to expire."""
|
|
33
|
+
with self._lock:
|
|
34
|
+
if self._token and time.monotonic() < self._expires_at - _REFRESH_MARGIN_SECONDS:
|
|
35
|
+
return self._token
|
|
36
|
+
|
|
37
|
+
# Measured before the call so network time counts against the token's lifetime.
|
|
38
|
+
started_at = time.monotonic()
|
|
39
|
+
reply = post_json(
|
|
40
|
+
self._base_url,
|
|
41
|
+
_AUTH_PATH,
|
|
42
|
+
{"client_id": self._client_id, "client_secret": self._client_secret},
|
|
43
|
+
)
|
|
44
|
+
token = reply.get("access_token")
|
|
45
|
+
expires_in = reply.get("expires_in")
|
|
46
|
+
if not isinstance(token, str) or not token or not isinstance(expires_in, (int, float)) or expires_in <= 0:
|
|
47
|
+
raise SMEPayError(
|
|
48
|
+
"invalid_response",
|
|
49
|
+
"SMEPay auth reply did not contain an access token",
|
|
50
|
+
status_code=200,
|
|
51
|
+
raw=reply,
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
self._token = token
|
|
55
|
+
self._expires_at = started_at + float(expires_in)
|
|
56
|
+
return token
|
|
57
|
+
|
|
58
|
+
def invalidate(self, token: str) -> None:
|
|
59
|
+
"""Drop the cached token if it is the one the server just rejected."""
|
|
60
|
+
with self._lock:
|
|
61
|
+
if self._token == token:
|
|
62
|
+
self._token = None
|
|
63
|
+
self._expires_at = 0.0
|
smepay/_client.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, Literal, Mapping
|
|
4
|
+
|
|
5
|
+
from ._auth import TokenManager
|
|
6
|
+
from ._errors import SMEPayError
|
|
7
|
+
from ._http import post_json
|
|
8
|
+
from ._payment import PaymentResource
|
|
9
|
+
|
|
10
|
+
Environment = Literal["test", "live"]
|
|
11
|
+
|
|
12
|
+
_BASE_URLS = {
|
|
13
|
+
"test": "https://staging.smepay.in",
|
|
14
|
+
"live": "https://extranet.smepay.in",
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
# 401 codes meaning the token itself was rejected; a fresh login may fix these.
|
|
18
|
+
_TOKEN_ERROR_CODES = {"invalid_token", "invalid_external_token", "invalid_token_type"}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class ApiClient:
|
|
22
|
+
"""Authenticated POSTs with client_id added to every body."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, base_url: str, client_id: str, client_secret: str) -> None:
|
|
25
|
+
self._base_url = base_url
|
|
26
|
+
self._client_id = client_id
|
|
27
|
+
self._auth = TokenManager(base_url, client_id, client_secret)
|
|
28
|
+
|
|
29
|
+
def __repr__(self) -> str:
|
|
30
|
+
return "ApiClient()"
|
|
31
|
+
|
|
32
|
+
def post(self, path: str, params: Mapping[str, Any]) -> dict[str, Any]:
|
|
33
|
+
body: dict[str, Any] = {**params, "client_id": self._client_id}
|
|
34
|
+
token = self._auth.get_token()
|
|
35
|
+
try:
|
|
36
|
+
return post_json(self._base_url, path, body, token=token)
|
|
37
|
+
except SMEPayError as err:
|
|
38
|
+
if err.status_code != 401 or err.code not in _TOKEN_ERROR_CODES:
|
|
39
|
+
raise
|
|
40
|
+
# Token rejected (e.g. server session lost): log in again once and repeat the call once.
|
|
41
|
+
self._auth.invalidate(token)
|
|
42
|
+
return post_json(self._base_url, path, body, token=self._auth.get_token())
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class SMEPay:
|
|
46
|
+
"""SMEPay External API client. Thread-safe; create one and reuse it.
|
|
47
|
+
|
|
48
|
+
>>> client = SMEPay(client_id="...", client_secret="...", environment="test")
|
|
49
|
+
|
|
50
|
+
``environment`` is ``"test"`` (default, staging.smepay.in) or ``"live"`` (extranet.smepay.in)
|
|
51
|
+
and must match your business's mode on SMEPay. Bad config raises SMEPayError ``invalid_config``.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
def __init__(self, *, client_id: str, client_secret: str, environment: Environment = "test") -> None:
|
|
55
|
+
# Falsy check also catches None from an unset environment variable.
|
|
56
|
+
if not client_id or not client_id.strip():
|
|
57
|
+
raise SMEPayError("invalid_config", "client_id is required")
|
|
58
|
+
if not client_secret or not client_secret.strip():
|
|
59
|
+
raise SMEPayError("invalid_config", "client_secret is required")
|
|
60
|
+
if environment not in _BASE_URLS:
|
|
61
|
+
raise SMEPayError("invalid_config", f'environment must be "test" or "live", got {environment!r}')
|
|
62
|
+
|
|
63
|
+
self._environment: Environment = environment
|
|
64
|
+
self._api = ApiClient(_BASE_URLS[environment], client_id.strip(), client_secret.strip())
|
|
65
|
+
self.payment = PaymentResource(self._api)
|
|
66
|
+
"""Payment calls: ``create`` → ``initiate`` → ``get_status``."""
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def environment(self) -> Environment:
|
|
70
|
+
"""The SMEPay environment this client uses: "test" or "live"."""
|
|
71
|
+
return self._environment
|
|
72
|
+
|
|
73
|
+
def __repr__(self) -> str:
|
|
74
|
+
return f"SMEPay(environment={self._environment!r})"
|
smepay/_errors.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
# Keys that must never appear in an error, even if an API reply echoes them.
|
|
6
|
+
_SENSITIVE_KEYS = {"access_token", "client_secret", "authorization"}
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class SMEPayError(Exception):
|
|
10
|
+
"""Raised for every failed SDK call.
|
|
11
|
+
|
|
12
|
+
API errors: ``code`` is the API's ``error`` field (e.g. ``"duplicate_order_id"``),
|
|
13
|
+
``status_code`` the HTTP status and ``raw`` the API reply.
|
|
14
|
+
SDK-side errors use the codes ``"invalid_config"``, ``"network_error"``, ``"timeout"``
|
|
15
|
+
and ``"invalid_response"``; ``status_code`` is ``None`` when no reply was received.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
def __init__(self, code: str, message: str, status_code: int | None = None, raw: Any = None) -> None:
|
|
19
|
+
super().__init__(message)
|
|
20
|
+
self.code = code
|
|
21
|
+
self.message = message
|
|
22
|
+
self.status_code = status_code
|
|
23
|
+
self.raw = _redact(raw)
|
|
24
|
+
|
|
25
|
+
def __str__(self) -> str:
|
|
26
|
+
if self.status_code is not None:
|
|
27
|
+
return f"{self.code} (HTTP {self.status_code}): {self.message}"
|
|
28
|
+
return f"{self.code}: {self.message}"
|
|
29
|
+
|
|
30
|
+
def __repr__(self) -> str:
|
|
31
|
+
return f"SMEPayError(code={self.code!r}, status_code={self.status_code!r}, message={self.message!r})"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _redact(value: Any) -> Any:
|
|
35
|
+
if not isinstance(value, dict):
|
|
36
|
+
return value
|
|
37
|
+
items: dict[Any, Any] = value # pyright: ignore[reportUnknownVariableType]
|
|
38
|
+
return {k: "[redacted]" if str(k).lower() in _SENSITIVE_KEYS else v for k, v in items.items()}
|
smepay/_http.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import socket
|
|
5
|
+
import urllib.error
|
|
6
|
+
import urllib.request
|
|
7
|
+
from typing import Any, Dict, Mapping, cast
|
|
8
|
+
|
|
9
|
+
from ._errors import SMEPayError
|
|
10
|
+
from ._version import __version__
|
|
11
|
+
|
|
12
|
+
# Fixed maximum per request; deliberately not configurable.
|
|
13
|
+
TIMEOUT_SECONDS = 60.0
|
|
14
|
+
# Longest slice of a non-JSON reply kept in SMEPayError.raw.
|
|
15
|
+
_RAW_TEXT_LIMIT = 500
|
|
16
|
+
# Cap on how much of a reply is read.
|
|
17
|
+
_MAX_REPLY_BYTES = 10 * 1024 * 1024
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def post_json(
|
|
21
|
+
base_url: str,
|
|
22
|
+
path: str,
|
|
23
|
+
body: Mapping[str, Any],
|
|
24
|
+
token: str | None = None,
|
|
25
|
+
timeout: float = TIMEOUT_SECONDS,
|
|
26
|
+
) -> dict[str, Any]:
|
|
27
|
+
"""POST ``body`` as JSON and return the parsed reply. Raises SMEPayError on any failure."""
|
|
28
|
+
headers = {
|
|
29
|
+
"Content-Type": "application/json",
|
|
30
|
+
"Accept": "application/json",
|
|
31
|
+
"User-Agent": f"smepay-python/{__version__}",
|
|
32
|
+
}
|
|
33
|
+
if token:
|
|
34
|
+
headers["Authorization"] = f"Bearer {token}"
|
|
35
|
+
|
|
36
|
+
request = urllib.request.Request(
|
|
37
|
+
base_url + path,
|
|
38
|
+
data=json.dumps(body).encode("utf-8"),
|
|
39
|
+
headers=headers,
|
|
40
|
+
method="POST",
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
try:
|
|
44
|
+
with urllib.request.urlopen(request, timeout=timeout) as response:
|
|
45
|
+
status = int(response.status)
|
|
46
|
+
reply = response.read(_MAX_REPLY_BYTES)
|
|
47
|
+
except urllib.error.HTTPError as err: # non-2xx reply: still read its body
|
|
48
|
+
status = err.code
|
|
49
|
+
try:
|
|
50
|
+
reply = err.read(_MAX_REPLY_BYTES)
|
|
51
|
+
except (OSError, socket.timeout) as read_err:
|
|
52
|
+
raise _transport_error(path, read_err, timeout) from read_err
|
|
53
|
+
finally:
|
|
54
|
+
err.close()
|
|
55
|
+
except (urllib.error.URLError, OSError, socket.timeout) as err:
|
|
56
|
+
raise _transport_error(path, err, timeout) from err
|
|
57
|
+
|
|
58
|
+
text = reply.decode("utf-8", errors="replace")
|
|
59
|
+
try:
|
|
60
|
+
data = json.loads(text)
|
|
61
|
+
except ValueError:
|
|
62
|
+
raise SMEPayError(
|
|
63
|
+
"invalid_response",
|
|
64
|
+
f"SMEPay returned a non-JSON reply (HTTP {status}) for {path}",
|
|
65
|
+
status_code=status,
|
|
66
|
+
raw=text[:_RAW_TEXT_LIMIT],
|
|
67
|
+
) from None
|
|
68
|
+
|
|
69
|
+
if status < 200 or status >= 300:
|
|
70
|
+
raise _api_error(status, data)
|
|
71
|
+
if not isinstance(data, dict):
|
|
72
|
+
raise SMEPayError(
|
|
73
|
+
"invalid_response",
|
|
74
|
+
f"SMEPay reply for {path} was not a JSON object",
|
|
75
|
+
status_code=status,
|
|
76
|
+
raw=data,
|
|
77
|
+
)
|
|
78
|
+
return cast(Dict[str, Any], data)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _api_error(status: int, data: Any) -> SMEPayError:
|
|
82
|
+
"""Build an SMEPayError from an API error reply: {error, message} or {error, errors}."""
|
|
83
|
+
body = cast(Dict[str, Any], data) if isinstance(data, dict) else {}
|
|
84
|
+
error = body.get("error")
|
|
85
|
+
code = error if isinstance(error, str) and error else "api_error"
|
|
86
|
+
|
|
87
|
+
message = f"SMEPay API error (HTTP {status})"
|
|
88
|
+
if isinstance(body.get("message"), str) and body["message"]:
|
|
89
|
+
message = body["message"]
|
|
90
|
+
elif isinstance(body.get("errors"), str) and body["errors"]:
|
|
91
|
+
message = body["errors"]
|
|
92
|
+
elif body.get("errors") is not None:
|
|
93
|
+
message = json.dumps(body["errors"])
|
|
94
|
+
|
|
95
|
+
return SMEPayError(code, message, status_code=status, raw=data)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _transport_error(path: str, err: BaseException, timeout: float) -> SMEPayError:
|
|
99
|
+
"""Map a failed send/read to a timeout or network_error SMEPayError."""
|
|
100
|
+
reason = err.reason if isinstance(err, urllib.error.URLError) else err
|
|
101
|
+
if isinstance(reason, (socket.timeout, TimeoutError)):
|
|
102
|
+
return SMEPayError("timeout", f"Request to {path} timed out after {timeout:g}s")
|
|
103
|
+
return SMEPayError("network_error", f"Could not reach SMEPay ({path}): {reason}")
|
smepay/_payment.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING, Any, cast
|
|
4
|
+
|
|
5
|
+
from ._types import CreateResponse, CustomerDetails, GetStatusResponse, InitiateResponse
|
|
6
|
+
|
|
7
|
+
if TYPE_CHECKING:
|
|
8
|
+
from ._client import ApiClient
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class PaymentResource:
|
|
12
|
+
"""Payment calls: create → initiate → get_status."""
|
|
13
|
+
|
|
14
|
+
def __init__(self, api: ApiClient) -> None:
|
|
15
|
+
self._api = api
|
|
16
|
+
|
|
17
|
+
def __repr__(self) -> str:
|
|
18
|
+
return "PaymentResource()"
|
|
19
|
+
|
|
20
|
+
def create(
|
|
21
|
+
self,
|
|
22
|
+
*,
|
|
23
|
+
amount: str,
|
|
24
|
+
order_id: str,
|
|
25
|
+
callback_url: str,
|
|
26
|
+
customer_details: CustomerDetails,
|
|
27
|
+
) -> CreateResponse:
|
|
28
|
+
"""Create a payment order. Next step: ``initiate(slug=reply["order_slug"])``.
|
|
29
|
+
|
|
30
|
+
:param amount: amount in rupees, as a string, e.g. ``"100.50"``
|
|
31
|
+
:param order_id: your own reference; must be unique for your business
|
|
32
|
+
:param callback_url: URL that receives the payment result webhook
|
|
33
|
+
:param customer_details: ``{"name", "email", "mobile"}``; email or mobile required
|
|
34
|
+
"""
|
|
35
|
+
body = {
|
|
36
|
+
"amount": amount,
|
|
37
|
+
"order_id": order_id,
|
|
38
|
+
"callback_url": callback_url,
|
|
39
|
+
"customer_details": dict(customer_details),
|
|
40
|
+
}
|
|
41
|
+
return cast(CreateResponse, self._api.post("/api/external/order/create", body))
|
|
42
|
+
|
|
43
|
+
def initiate(self, *, slug: str) -> InitiateResponse:
|
|
44
|
+
"""Start the payment for an order; returns the UPI link, QR code and app intents.
|
|
45
|
+
|
|
46
|
+
:param slug: ``order_slug`` from ``create``
|
|
47
|
+
"""
|
|
48
|
+
return cast(InitiateResponse, self._api.post("/api/external/order/initiate", {"slug": slug}))
|
|
49
|
+
|
|
50
|
+
def get_status(
|
|
51
|
+
self,
|
|
52
|
+
*,
|
|
53
|
+
order_id: str | None = None,
|
|
54
|
+
external_reference_id: str | None = None,
|
|
55
|
+
callback_url: str | None = None,
|
|
56
|
+
) -> GetStatusResponse:
|
|
57
|
+
"""Fetch the current payment status of an order.
|
|
58
|
+
|
|
59
|
+
Pass ``order_id`` (SMEPay's) or ``external_reference_id`` (yours); the latter is used first if both are given.
|
|
60
|
+
``callback_url`` is saved only if the order has none yet.
|
|
61
|
+
"""
|
|
62
|
+
body: dict[str, Any] = {}
|
|
63
|
+
if order_id is not None:
|
|
64
|
+
body["order_id"] = order_id
|
|
65
|
+
if external_reference_id is not None:
|
|
66
|
+
body["external_reference_id"] = external_reference_id
|
|
67
|
+
if callback_url is not None:
|
|
68
|
+
body["callback_url"] = callback_url
|
|
69
|
+
return cast(GetStatusResponse, self._api.post("/api/external/order/status", body))
|
smepay/_types.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Type hints for request and response data. All keys are exactly the API's.
|
|
2
|
+
|
|
3
|
+
Responses are plain dicts at runtime; these TypedDicts only give editors autocomplete.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from typing import Dict, Literal, Optional, TypedDict
|
|
9
|
+
|
|
10
|
+
PaymentStatus = Literal[
|
|
11
|
+
"CREATED",
|
|
12
|
+
"INITIATED",
|
|
13
|
+
"PENDING",
|
|
14
|
+
"SUCCESS",
|
|
15
|
+
"FAILED",
|
|
16
|
+
"EXPIRED",
|
|
17
|
+
"SETTLED",
|
|
18
|
+
"REFUNDED",
|
|
19
|
+
"REFUND_PENDING",
|
|
20
|
+
# Test-mode businesses get these instead of SUCCESS / FAILED / PENDING.
|
|
21
|
+
"TEST_SUCCESS",
|
|
22
|
+
"TEST_FAILED",
|
|
23
|
+
"TEST_PENDING",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class CustomerDetails(TypedDict, total=False):
|
|
28
|
+
"""Payer details; at least ``email`` or ``mobile`` is required."""
|
|
29
|
+
|
|
30
|
+
name: str
|
|
31
|
+
email: str
|
|
32
|
+
mobile: str
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class _CreateResponseBase(TypedDict):
|
|
36
|
+
status: bool
|
|
37
|
+
order_slug: str # pass to payment.initiate(slug=...)
|
|
38
|
+
order_id: str # SMEPay's order ID
|
|
39
|
+
amount: float
|
|
40
|
+
payment_status: PaymentStatus
|
|
41
|
+
payment_url: str # hosted SMEPay payment page
|
|
42
|
+
ref_id: str # your order_id, echoed back
|
|
43
|
+
customer_details: Dict[str, str]
|
|
44
|
+
message: str
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class CreateResponse(_CreateResponseBase, total=False):
|
|
48
|
+
"""Reply of payment.create."""
|
|
49
|
+
|
|
50
|
+
callback_url: str
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class InitiateResponse(TypedDict):
|
|
54
|
+
"""Reply of payment.initiate."""
|
|
55
|
+
|
|
56
|
+
status: bool
|
|
57
|
+
order_id: str # SMEPay's order ID
|
|
58
|
+
external_reference_id: str # your order_id
|
|
59
|
+
payment_link: str # UPI payment link
|
|
60
|
+
transaction_id: str
|
|
61
|
+
qr_code: str # base64-encoded PNG
|
|
62
|
+
payment_status: PaymentStatus
|
|
63
|
+
expires_at: int # Unix seconds
|
|
64
|
+
intents: Dict[str, str] # UPI app key -> app payment link
|
|
65
|
+
message: str
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class _GetStatusResponseBase(TypedDict):
|
|
69
|
+
status: bool
|
|
70
|
+
external_reference_id: str # your order_id
|
|
71
|
+
order_id: str # SMEPay's order ID
|
|
72
|
+
payment_status: PaymentStatus
|
|
73
|
+
amount: float
|
|
74
|
+
created_at: int # Unix seconds
|
|
75
|
+
processed_at: Optional[int] # Unix seconds; None until processed
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class GetStatusResponse(_GetStatusResponseBase, total=False):
|
|
79
|
+
"""Reply of payment.get_status."""
|
|
80
|
+
|
|
81
|
+
utr: str # bank reference, when available
|
smepay/_version.py
ADDED
smepay/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: smepay
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official Python SDK for the SMEPay External API (UPI payments).
|
|
5
|
+
Project-URL: Homepage, https://github.com/mahi-qwe/smepay-python#readme
|
|
6
|
+
Project-URL: Source, https://github.com/mahi-qwe/smepay-python
|
|
7
|
+
Project-URL: Issues, https://github.com/mahi-qwe/smepay-python/issues
|
|
8
|
+
Author: Typof Technologies Pvt Ltd
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: payments,sdk,smepay,upi
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Topic :: Office/Business :: Financial
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Python: >=3.8
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# smepay
|
|
23
|
+
|
|
24
|
+
Official Python SDK for the SMEPay External API. Accept UPI payments in three calls; login, tokens and errors are handled for you.
|
|
25
|
+
|
|
26
|
+
Python 3.8+ · zero dependencies · thread-safe · type hints included.
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pip install smepay
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Usage
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
import os
|
|
36
|
+
import smepay
|
|
37
|
+
|
|
38
|
+
client = smepay.SMEPay(
|
|
39
|
+
client_id=os.environ["SMEPAY_CLIENT_ID"], # from the SMEPay dashboard
|
|
40
|
+
client_secret=os.environ["SMEPAY_CLIENT_SECRET"],
|
|
41
|
+
environment="test", # "test" (default) or "live"
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
# 1. Create an order
|
|
45
|
+
order = client.payment.create(
|
|
46
|
+
amount="100.50", # string, in rupees
|
|
47
|
+
order_id="ORD-1001", # your reference, unique per order
|
|
48
|
+
callback_url="https://yoursite.com/smepay/callback",
|
|
49
|
+
customer_details={"name": "Asha", "mobile": "9876543210"}, # email or mobile required
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
# 2. Start the payment: show payment["qr_code"] (base64 PNG) or payment["intents"] (UPI app links)
|
|
53
|
+
payment = client.payment.initiate(slug=order["order_slug"])
|
|
54
|
+
|
|
55
|
+
# 3. Check the status (or use order_id=order["order_id"])
|
|
56
|
+
status = client.payment.get_status(external_reference_id="ORD-1001")
|
|
57
|
+
print(status["payment_status"], status.get("utr")) # "SUCCESS", "123456789012"
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Create one client and reuse it. Arguments and reply keys match the API exactly; replies are plain dicts. Each request waits at most 60 seconds.
|
|
61
|
+
|
|
62
|
+
| Method | Returns |
|
|
63
|
+
|---|---|
|
|
64
|
+
| `payment.create` | `order_slug`, `order_id` (SMEPay's), `ref_id` (yours), `payment_url`, `payment_status` |
|
|
65
|
+
| `payment.initiate` | `payment_link`, `qr_code`, `intents`, `expires_at`, `payment_status` |
|
|
66
|
+
| `payment.get_status` | `payment_status`, `amount`, `created_at`, `processed_at` (`None` until processed), `utr` |
|
|
67
|
+
|
|
68
|
+
`initiate` can be called again if a payment failed or expired. Alternatively, skip `initiate` and redirect the customer to `payment_url` (the hosted page); use one or the other per order.
|
|
69
|
+
|
|
70
|
+
**Statuses:** `CREATED` → `INITIATED` / `PENDING` → `SUCCESS` or `FAILED` / `EXPIRED`; also `SETTLED`, `REFUNDED`, `REFUND_PENDING`. Test-mode businesses get `TEST_SUCCESS`, `TEST_FAILED`, `TEST_PENDING`.
|
|
71
|
+
|
|
72
|
+
## Errors
|
|
73
|
+
|
|
74
|
+
Every failure raises `smepay.SMEPayError` with `code`, `message`, `status_code` (`None` if no reply) and `raw` (API reply).
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
try:
|
|
78
|
+
client.payment.create(...)
|
|
79
|
+
except smepay.SMEPayError as e:
|
|
80
|
+
if e.code == "duplicate_order_id":
|
|
81
|
+
...
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
| Code | Meaning |
|
|
85
|
+
|---|---|
|
|
86
|
+
| `invalid_config` | Missing `client_id` / `client_secret`, or bad `environment` |
|
|
87
|
+
| `invalid_client_id`, `invalid_credentials` | Wrong credentials |
|
|
88
|
+
| `environment_mismatch` | `environment` doesn't match your business's mode |
|
|
89
|
+
| `ip_not_whitelisted` | Live: your server IP isn't whitelisted |
|
|
90
|
+
| `insufficient_wallet_balance`, `wallet_validation_failed` | Live: wallet balance too low |
|
|
91
|
+
| `invalid_request`, `validation_error` | Missing or invalid field |
|
|
92
|
+
| `amount_below_minimum`, `amount_exceeds_maximum` | Amount outside your allowed range |
|
|
93
|
+
| `duplicate_order_id` | `order_id` already used |
|
|
94
|
+
| `transaction_not_found` | No such order for your business |
|
|
95
|
+
| `payment_already_processed` | `initiate` on an order already paid / in progress |
|
|
96
|
+
| `network_error`, `timeout`, `invalid_response` | Couldn't reach SMEPay / no reply in 60s / unreadable reply |
|
|
97
|
+
|
|
98
|
+
Calls are never retried automatically, so a failed `create` is never sent twice.
|
|
99
|
+
|
|
100
|
+
## Test vs live
|
|
101
|
+
|
|
102
|
+
| | `test` | `live` |
|
|
103
|
+
|---|---|---|
|
|
104
|
+
| Server | `staging.smepay.in` | `extranet.smepay.in` |
|
|
105
|
+
| Money / fees | None | Real; fees from your SMEPay wallet |
|
|
106
|
+
| Requirements | — | Server IP whitelisted, wallet ≥ ₹10 |
|
|
107
|
+
|
|
108
|
+
## Webhooks
|
|
109
|
+
|
|
110
|
+
When a payment finishes, SMEPay POSTs `ref_id`, `transaction_id`, `status`, `amount`, `created_at`, `processed_at` and `utr` to your `callback_url`. Confirm with `payment.get_status` before marking an order paid.
|
|
111
|
+
|
|
112
|
+
## Security
|
|
113
|
+
|
|
114
|
+
Use the SDK only on your server. Keep `client_secret` in an environment variable, never in code. The SDK never logs your secret or token, and `repr(client)` doesn't show them.
|
|
115
|
+
|
|
116
|
+
## Example
|
|
117
|
+
|
|
118
|
+
[`examples/full_flow.py`](https://github.com/mahi-qwe/smepay-python/blob/main/examples/full_flow.py): put `SMEPAY_CLIENT_ID` / `SMEPAY_CLIENT_SECRET` in `.env`, then `set -a; source .env; set +a; python examples/full_flow.py`.
|
|
119
|
+
|
|
120
|
+
## License
|
|
121
|
+
|
|
122
|
+
MIT
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
smepay/__init__.py,sha256=GOeUdEGc1MGlnERcvE38KQnJeJUAmcZkNuQ5Gd1tOmw,706
|
|
2
|
+
smepay/_auth.py,sha256=APVjZrwnzTtaYMnjTQRuvQfsCPkrKHjbiigGHyUVrts,2261
|
|
3
|
+
smepay/_client.py,sha256=MtpNusGo6vjy6BtKZmg3bfNpN8N8-7h5AuOOg275DOo,3018
|
|
4
|
+
smepay/_errors.py,sha256=RIBgB49HFN9HYPIDf6rzDawvyU9grffm1cxh4ltGvHE,1491
|
|
5
|
+
smepay/_http.py,sha256=XEozTcrK6MmEW_Q3hza6pNUM1787coj6ZBWDjl6XJx8,3629
|
|
6
|
+
smepay/_payment.py,sha256=satGMNg9czeWnuzTUN6jz6KcVjv-6b4xXMmGuPZdotU,2490
|
|
7
|
+
smepay/_types.py,sha256=f9lwQpBbdFyIs2ipbjDqBkInDBWJ0jQoU4oCjWpJ-To,2096
|
|
8
|
+
smepay/_version.py,sha256=QF0h7guh2KaEc0IQu2yHTj63eT62ZUMC6PypHlyPQIo,91
|
|
9
|
+
smepay/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
10
|
+
smepay-0.1.0.dist-info/METADATA,sha256=GfBMjp-eXbYyjL2lrOHrb3W48YGKIPikwo2FhKw0JVo,5044
|
|
11
|
+
smepay-0.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
12
|
+
smepay-0.1.0.dist-info/licenses/LICENSE,sha256=P8Dlg5Q71ktaKLujjNPARFfanA1HNIRzZ9ZUCkdP8Ys,1083
|
|
13
|
+
smepay-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Typof Technologies Pvt Ltd
|
|
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.
|