kobara 2.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.
kobara-2.0.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kobara
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.
kobara-2.0.0/PKG-INFO ADDED
@@ -0,0 +1,62 @@
1
+ Metadata-Version: 2.4
2
+ Name: kobara
3
+ Version: 2.0.0
4
+ Summary: Official Python SDK for Kobara payments and MonCash/NatCash withdrawals
5
+ Author-email: Kobara Dev Team <dev@kobara.app>
6
+ License-Expression: MIT
7
+ Project-URL: Documentation, https://docs.kobara.app/docs/python-sdk
8
+ Project-URL: Homepage, https://kobara.app
9
+ Project-URL: Repository, https://github.com/L09DP01/Kobara-python
10
+ Project-URL: Issues, https://github.com/L09DP01/Kobara-python/issues
11
+ Keywords: kobara,moncash,haiti,payments,fintech,sdk
12
+ Classifier: Development Status :: 5 - Production/Stable
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.8
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Requires-Python: >=3.8
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: requests>=2.25.0
24
+ Dynamic: license-file
25
+
26
+ # Kobara Python SDK
27
+
28
+ SDK serveur officiel pour les paiements Kobara, les retraits MonCash/NatCash et la vérification des webhooks.
29
+
30
+ ```bash
31
+ pip install kobara
32
+ ```
33
+
34
+ ```python
35
+ from kobara import Kobara
36
+
37
+ client = Kobara(api_key="kbr_sk_live_...")
38
+ payment = client.payments.create({
39
+ "amount": 2500,
40
+ "currency": "HTG",
41
+ "provider": "kobara",
42
+ "success_url": "https://shop.example/success",
43
+ "cancel_url": "https://shop.example/cancel",
44
+ }, idempotency_key="payment-1001")
45
+
46
+ print(payment["data"]["checkout_url"])
47
+ ```
48
+
49
+ Les fournisseurs acceptés sont `kobara`, MonCash, NatCash, carte, PayPal, Apple Pay et Google Pay, avec leurs identifiants détaillés dans la documentation. Leur disponibilité dépend des activations du marchand et du système.
50
+
51
+ ```python
52
+ withdrawal = client.withdrawals.create({
53
+ "amount": 1000,
54
+ "method": "natcash",
55
+ "account_currency": "HTG",
56
+ "wallet": "50941234567",
57
+ }, idempotency_key="withdrawal-1001")
58
+ ```
59
+
60
+ Les retraits API acceptent uniquement `moncash` et `natcash`. L'URL par défaut est `https://api.kobara.app/v1`; une UUID d'idempotence est générée si elle est omise.
61
+
62
+ Documentation: https://docs.kobara.app/docs/python-sdk
kobara-2.0.0/README.md ADDED
@@ -0,0 +1,37 @@
1
+ # Kobara Python SDK
2
+
3
+ SDK serveur officiel pour les paiements Kobara, les retraits MonCash/NatCash et la vérification des webhooks.
4
+
5
+ ```bash
6
+ pip install kobara
7
+ ```
8
+
9
+ ```python
10
+ from kobara import Kobara
11
+
12
+ client = Kobara(api_key="kbr_sk_live_...")
13
+ payment = client.payments.create({
14
+ "amount": 2500,
15
+ "currency": "HTG",
16
+ "provider": "kobara",
17
+ "success_url": "https://shop.example/success",
18
+ "cancel_url": "https://shop.example/cancel",
19
+ }, idempotency_key="payment-1001")
20
+
21
+ print(payment["data"]["checkout_url"])
22
+ ```
23
+
24
+ Les fournisseurs acceptés sont `kobara`, MonCash, NatCash, carte, PayPal, Apple Pay et Google Pay, avec leurs identifiants détaillés dans la documentation. Leur disponibilité dépend des activations du marchand et du système.
25
+
26
+ ```python
27
+ withdrawal = client.withdrawals.create({
28
+ "amount": 1000,
29
+ "method": "natcash",
30
+ "account_currency": "HTG",
31
+ "wallet": "50941234567",
32
+ }, idempotency_key="withdrawal-1001")
33
+ ```
34
+
35
+ Les retraits API acceptent uniquement `moncash` et `natcash`. L'URL par défaut est `https://api.kobara.app/v1`; une UUID d'idempotence est générée si elle est omise.
36
+
37
+ Documentation: https://docs.kobara.app/docs/python-sdk
@@ -0,0 +1,13 @@
1
+ from kobara.client import KobaraClient, Kobara
2
+ from kobara.errors import KobaraError, KobaraAPIError, KobaraSignatureVerificationError
3
+
4
+ __version__ = "2.0.0"
5
+
6
+ __all__ = [
7
+ "KobaraClient",
8
+ "Kobara",
9
+ "KobaraError",
10
+ "KobaraAPIError",
11
+ "KobaraSignatureVerificationError",
12
+ "__version__",
13
+ ]
@@ -0,0 +1,57 @@
1
+ import requests
2
+ from typing import Optional, Dict, Any
3
+ from kobara.errors import KobaraAPIError
4
+ from kobara.resources.payments import PaymentsResource
5
+ from kobara.resources.withdrawals import WithdrawalsResource
6
+ from kobara.resources.webhooks import WebhooksResource
7
+
8
+ class KobaraClient:
9
+ def __init__(self, api_key: str, base_url: Optional[str] = None):
10
+ if not api_key:
11
+ raise ValueError("API Key (api_key) is required to initialize KobaraClient")
12
+
13
+ self.api_key = api_key
14
+ self.base_url = (base_url or "https://api.kobara.app/v1").rstrip("/")
15
+
16
+ self.session = requests.Session()
17
+ self.session.headers.update({
18
+ "Authorization": f"Bearer {self.api_key}",
19
+ "Content-Type": "application/json",
20
+ "Accept": "application/json",
21
+ "User-Agent": "Kobara-Python/2.0.0",
22
+ })
23
+
24
+ # Register Resources
25
+ self.payments = PaymentsResource(self)
26
+ self.withdrawals = WithdrawalsResource(self)
27
+ self.webhooks = WebhooksResource()
28
+
29
+ def request(self, method: str, endpoint: str, **kwargs) -> Dict[str, Any]:
30
+ """
31
+ Internal request dispatcher with error formatting and exception raised.
32
+ """
33
+ url = f"{self.base_url}/{endpoint.lstrip('/')}"
34
+
35
+ kwargs.setdefault("timeout", 30)
36
+
37
+ try:
38
+ response = self.session.request(method, url, **kwargs)
39
+ except requests.RequestException as e:
40
+ raise RuntimeError(f"Failed to connect to Kobara API: {str(e)}")
41
+
42
+ try:
43
+ data = response.json()
44
+ except ValueError:
45
+ data = {}
46
+
47
+ if not (200 <= response.status_code < 300):
48
+ message = data.get("message") or data.get("error") or response.reason or "Unknown API Error"
49
+ if not isinstance(message, str):
50
+ message = str(message)
51
+ error_type = data.get("type", "api_error")
52
+ raise KobaraAPIError(message, status_code=response.status_code, error_type=error_type)
53
+
54
+ return data
55
+
56
+ # Export alias to match traditional class names
57
+ Kobara = KobaraClient
@@ -0,0 +1,14 @@
1
+ class KobaraError(Exception):
2
+ """Base exception for all Kobara errors."""
3
+ pass
4
+
5
+ class KobaraAPIError(KobaraError):
6
+ """Exception raised when an API request returns an error response."""
7
+ def __init__(self, message, status_code=None, error_type=None):
8
+ super().__init__(message)
9
+ self.status_code = status_code
10
+ self.error_type = error_type
11
+
12
+ class KobaraSignatureVerificationError(KobaraError):
13
+ """Exception raised when webhook signature verification fails."""
14
+ pass
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,15 @@
1
+ from typing import Dict, Any, Optional
2
+ from uuid import uuid4
3
+
4
+ class PaymentsResource:
5
+ def __init__(self, client):
6
+ self.client = client
7
+
8
+ def create(self, payload: Dict[str, Any], idempotency_key: Optional[str] = None) -> Dict[str, Any]:
9
+ """
10
+ Create a payment using the unified checkout or a supported provider.
11
+ """
12
+ headers = {}
13
+ headers["Idempotency-Key"] = idempotency_key or str(uuid4())
14
+
15
+ return self.client.request("POST", "/payments", json=payload, headers=headers)
@@ -0,0 +1,46 @@
1
+ import hmac
2
+ import hashlib
3
+ import json
4
+ import re
5
+ import time
6
+ from kobara.errors import KobaraSignatureVerificationError
7
+
8
+ class WebhooksResource:
9
+ @staticmethod
10
+ def construct_event(payload: str, signature: str, secret: str, tolerance_seconds: int = 300) -> dict:
11
+ """
12
+ Securely verify webhook payload signature locally using HMAC SHA-256
13
+ """
14
+ if not payload:
15
+ raise KobaraSignatureVerificationError("Payload cannot be empty")
16
+ if not signature:
17
+ raise KobaraSignatureVerificationError("Kobara-Signature header is missing")
18
+ if not secret:
19
+ raise KobaraSignatureVerificationError("Webhook secret is missing")
20
+
21
+ parts = dict(part.strip().split("=", 1) for part in signature.split(",") if "=" in part)
22
+ try:
23
+ timestamp = int(parts["t"])
24
+ target_signature = parts["v1"]
25
+ except (KeyError, ValueError):
26
+ raise KobaraSignatureVerificationError("Invalid Kobara-Signature format")
27
+ if not re.fullmatch(r"[a-fA-F0-9]{64}", target_signature):
28
+ raise KobaraSignatureVerificationError("Invalid Kobara-Signature format")
29
+ if abs(int(time.time()) - timestamp) > tolerance_seconds:
30
+ raise KobaraSignatureVerificationError("Webhook timestamp is outside the tolerance window")
31
+
32
+ # Compute signature
33
+ computed = hmac.new(
34
+ secret.encode("utf-8"),
35
+ f"{timestamp}.{payload}".encode("utf-8"),
36
+ hashlib.sha256
37
+ ).hexdigest()
38
+
39
+ # Timing safe comparison
40
+ if not hmac.compare_digest(computed.lower(), target_signature.lower()):
41
+ raise KobaraSignatureVerificationError("Invalid signature. HMAC verification failed.")
42
+
43
+ try:
44
+ return json.loads(payload)
45
+ except Exception as e:
46
+ raise KobaraSignatureVerificationError(f"Failed to parse raw body payload as JSON: {str(e)}")
@@ -0,0 +1,15 @@
1
+ from typing import Dict, Any, Optional
2
+ from uuid import uuid4
3
+
4
+ class WithdrawalsResource:
5
+ def __init__(self, client):
6
+ self.client = client
7
+
8
+ def create(self, payload: Dict[str, Any], idempotency_key: Optional[str] = None) -> Dict[str, Any]:
9
+ """
10
+ Request a MonCash or NatCash withdrawal.
11
+ """
12
+ headers = {}
13
+ headers["Idempotency-Key"] = idempotency_key or str(uuid4())
14
+
15
+ return self.client.request("POST", "/withdrawals", json=payload, headers=headers)
@@ -0,0 +1,68 @@
1
+ from typing import TypedDict, Optional, Literal, Dict, Any
2
+
3
+ class CustomerDict(TypedDict, total=False):
4
+ name: str
5
+ email: str
6
+ phone: str
7
+
8
+ class PaymentCreateRequired(TypedDict):
9
+ amount: float
10
+
11
+ class PaymentCreatePayload(PaymentCreateRequired, total=False):
12
+ currency: str
13
+ provider: Literal["kobara", "moncash", "moncash_web", "moncash_ussd", "natcash", "natcash_web", "natcash_ussd", "card", "carte", "paypal", "apple_pay", "google_pay"]
14
+ description: str
15
+ customer: CustomerDict
16
+ success_url: str
17
+ cancel_url: str
18
+ metadata: Dict[str, Any]
19
+
20
+ class PaymentData(TypedDict):
21
+ id: str
22
+ reference: str
23
+ amount: float
24
+ net_amount: float
25
+ fee_amount: float
26
+ status: Literal["pending", "succeeded", "failed", "expired", "refunded"]
27
+ environment: Literal["test", "live"]
28
+ paid_at: Optional[str]
29
+ checkout_url: str
30
+ url: str
31
+ payment_url: str
32
+ paymentUrl: str
33
+
34
+ class PaymentCreateResponse(TypedDict):
35
+ status: Literal["success"]
36
+ data: PaymentData
37
+
38
+ class WithdrawalCreateRequired(TypedDict):
39
+ amount: float
40
+ wallet: str
41
+
42
+ class WithdrawalCreatePayload(WithdrawalCreateRequired, total=False):
43
+ method: Literal["moncash", "natcash"]
44
+ account_currency: Literal["HTG", "USD"]
45
+ description: str
46
+
47
+ class WithdrawalData(TypedDict):
48
+ id: str
49
+ reference: str
50
+ status: Literal["pending", "pending_approval", "completed"]
51
+ method: Literal["moncash", "natcash"]
52
+ amount: float
53
+ fees: float
54
+ net_amount: float
55
+ currency: Literal["HTG", "USD"]
56
+ payout_amount: float
57
+ payout_currency: Literal["HTG"]
58
+ exchange_rate: float
59
+ wallet: str
60
+ description: Optional[str]
61
+ created_at: str
62
+
63
+ class WithdrawalResponseRequired(TypedDict):
64
+ status: Literal["success"]
65
+ data: WithdrawalData
66
+
67
+ class WithdrawalResponse(WithdrawalResponseRequired, total=False):
68
+ verification_pending: bool
@@ -0,0 +1,62 @@
1
+ Metadata-Version: 2.4
2
+ Name: kobara
3
+ Version: 2.0.0
4
+ Summary: Official Python SDK for Kobara payments and MonCash/NatCash withdrawals
5
+ Author-email: Kobara Dev Team <dev@kobara.app>
6
+ License-Expression: MIT
7
+ Project-URL: Documentation, https://docs.kobara.app/docs/python-sdk
8
+ Project-URL: Homepage, https://kobara.app
9
+ Project-URL: Repository, https://github.com/L09DP01/Kobara-python
10
+ Project-URL: Issues, https://github.com/L09DP01/Kobara-python/issues
11
+ Keywords: kobara,moncash,haiti,payments,fintech,sdk
12
+ Classifier: Development Status :: 5 - Production/Stable
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.8
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Requires-Python: >=3.8
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: requests>=2.25.0
24
+ Dynamic: license-file
25
+
26
+ # Kobara Python SDK
27
+
28
+ SDK serveur officiel pour les paiements Kobara, les retraits MonCash/NatCash et la vérification des webhooks.
29
+
30
+ ```bash
31
+ pip install kobara
32
+ ```
33
+
34
+ ```python
35
+ from kobara import Kobara
36
+
37
+ client = Kobara(api_key="kbr_sk_live_...")
38
+ payment = client.payments.create({
39
+ "amount": 2500,
40
+ "currency": "HTG",
41
+ "provider": "kobara",
42
+ "success_url": "https://shop.example/success",
43
+ "cancel_url": "https://shop.example/cancel",
44
+ }, idempotency_key="payment-1001")
45
+
46
+ print(payment["data"]["checkout_url"])
47
+ ```
48
+
49
+ Les fournisseurs acceptés sont `kobara`, MonCash, NatCash, carte, PayPal, Apple Pay et Google Pay, avec leurs identifiants détaillés dans la documentation. Leur disponibilité dépend des activations du marchand et du système.
50
+
51
+ ```python
52
+ withdrawal = client.withdrawals.create({
53
+ "amount": 1000,
54
+ "method": "natcash",
55
+ "account_currency": "HTG",
56
+ "wallet": "50941234567",
57
+ }, idempotency_key="withdrawal-1001")
58
+ ```
59
+
60
+ Les retraits API acceptent uniquement `moncash` et `natcash`. L'URL par défaut est `https://api.kobara.app/v1`; une UUID d'idempotence est générée si elle est omise.
61
+
62
+ Documentation: https://docs.kobara.app/docs/python-sdk
@@ -0,0 +1,17 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ kobara/__init__.py
5
+ kobara/client.py
6
+ kobara/errors.py
7
+ kobara/py.typed
8
+ kobara/types.py
9
+ kobara.egg-info/PKG-INFO
10
+ kobara.egg-info/SOURCES.txt
11
+ kobara.egg-info/dependency_links.txt
12
+ kobara.egg-info/requires.txt
13
+ kobara.egg-info/top_level.txt
14
+ kobara/resources/payments.py
15
+ kobara/resources/webhooks.py
16
+ kobara/resources/withdrawals.py
17
+ tests/test_sdk.py
@@ -0,0 +1 @@
1
+ requests>=2.25.0
@@ -0,0 +1 @@
1
+ kobara
@@ -0,0 +1,40 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77.0.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "kobara"
7
+ version = "2.0.0"
8
+ description = "Official Python SDK for Kobara payments and MonCash/NatCash withdrawals"
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = "MIT"
12
+ authors = [
13
+ {name = "Kobara Dev Team", email = "dev@kobara.app"}
14
+ ]
15
+ keywords = ["kobara", "moncash", "haiti", "payments", "fintech", "sdk"]
16
+ classifiers = [
17
+ "Development Status :: 5 - Production/Stable",
18
+ "Intended Audience :: Developers",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.8",
21
+ "Programming Language :: Python :: 3.9",
22
+ "Programming Language :: Python :: 3.10",
23
+ "Programming Language :: Python :: 3.11",
24
+ "Topic :: Software Development :: Libraries :: Python Modules"
25
+ ]
26
+ dependencies = [
27
+ "requests>=2.25.0"
28
+ ]
29
+
30
+ [project.urls]
31
+ Documentation = "https://docs.kobara.app/docs/python-sdk"
32
+ Homepage = "https://kobara.app"
33
+ Repository = "https://github.com/L09DP01/Kobara-python"
34
+ Issues = "https://github.com/L09DP01/Kobara-python/issues"
35
+
36
+ [tool.setuptools.packages.find]
37
+ include = ["kobara*"]
38
+
39
+ [tool.setuptools.package-data]
40
+ kobara = ["py.typed"]
kobara-2.0.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,65 @@
1
+ import hashlib
2
+ import hmac
3
+ import json
4
+ import time
5
+ import unittest
6
+ from unittest.mock import Mock
7
+
8
+ from kobara import Kobara, KobaraSignatureVerificationError, __version__
9
+
10
+
11
+ class KobaraSdkV2Tests(unittest.TestCase):
12
+ def setUp(self):
13
+ self.client = Kobara("kbr_sk_live_example")
14
+ self.client.session.request = Mock()
15
+ self.client.session.request.return_value.status_code = 200
16
+ self.client.session.request.return_value.json.return_value = {
17
+ "status": "success",
18
+ "data": {"id": "example"},
19
+ }
20
+
21
+ def test_version_and_default_base_url(self):
22
+ self.assertEqual(__version__, "2.0.0")
23
+ self.assertEqual(self.client.base_url, "https://api.kobara.app/v1")
24
+
25
+ def test_payment_uses_v1_route_and_idempotency(self):
26
+ self.client.payments.create({"amount": 2500, "provider": "kobara"})
27
+ _, url = self.client.session.request.call_args.args
28
+ kwargs = self.client.session.request.call_args.kwargs
29
+ self.assertEqual(url, "https://api.kobara.app/v1/payments")
30
+ self.assertIn("Idempotency-Key", kwargs["headers"])
31
+ self.assertEqual(kwargs["timeout"], 30)
32
+
33
+ def test_withdrawal_uses_v1_route(self):
34
+ self.client.withdrawals.create({
35
+ "amount": 1000,
36
+ "method": "moncash",
37
+ "account_currency": "HTG",
38
+ "wallet": "50934567890",
39
+ })
40
+ _, url = self.client.session.request.call_args.args
41
+ self.assertEqual(url, "https://api.kobara.app/v1/withdrawals")
42
+
43
+ def test_timestamped_webhook_signature(self):
44
+ payload = json.dumps({"event_type": "payment.succeeded", "data": {"id": "pay_1"}})
45
+ secret = "whsec_example"
46
+ timestamp = int(time.time())
47
+ digest = hmac.new(
48
+ secret.encode("utf-8"),
49
+ f"{timestamp}.{payload}".encode("utf-8"),
50
+ hashlib.sha256,
51
+ ).hexdigest()
52
+
53
+ event = self.client.webhooks.construct_event(
54
+ payload,
55
+ f"t={timestamp},v1={digest}",
56
+ secret,
57
+ )
58
+ self.assertEqual(event["event_type"], "payment.succeeded")
59
+
60
+ with self.assertRaises(KobaraSignatureVerificationError):
61
+ self.client.webhooks.construct_event(payload, f"t={timestamp},v1={'0' * 64}", secret)
62
+
63
+
64
+ if __name__ == "__main__":
65
+ unittest.main()