Metadata-Version: 2.4
Name: tangentopay
Version: 0.1.0
Summary: Official Python SDK for the TangentoPay API
Project-URL: Homepage, https://tangentopay.com
Project-URL: Documentation, https://docs.tangentopay.com
Project-URL: Repository, https://github.com/tangentopay/tangentopay-python
Project-URL: Bug Tracker, https://github.com/tangentopay/tangentopay-python/issues
Author-email: TangentoPay <dev@tangentopay.com>
License: MIT License
        
        Copyright (c) 2026 TangentoPay
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: africa,fintech,payments,stripe,tangentopay
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Office/Business :: Financial
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.9
Requires-Dist: httpx<1.0.0,>=0.27.0
Provides-Extra: async
Requires-Dist: httpx[http2]>=0.27.0; extra == 'async'
Provides-Extra: dev
Requires-Dist: mypy>=1.10.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23.0; extra == 'dev'
Requires-Dist: pytest-httpx>=0.30.0; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.4.0; extra == 'dev'
Description-Content-Type: text/markdown

# tangentopay-python

Official Python SDK for the [TangentoPay](https://tangentopay.com) API.

[![PyPI version](https://badge.fury.io/py/tangentopay.svg)](https://pypi.org/project/tangentopay/)
[![CI](https://github.com/tangentopay/tangentopay-python/actions/workflows/ci.yml/badge.svg)](https://github.com/tangentopay/tangentopay-python/actions/workflows/ci.yml)
[![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)

---

## Requirements

- Python 3.9+
- `httpx` (installed automatically)

## Installation

```bash
pip install tangentopay
```

---

## Quick start

### 1. Storefront — accept a customer payment

Use `ServiceClient` with your **public service API key** (`pk_live_...`).  
Get it from: **TangentoPay Dashboard → Services → your service → API Keys**.

```python
import tangentopay

client = tangentopay.ServiceClient("pk_live_your_key_here")

session = client.checkout.create(
    products=[
        {"name": "Pro Plan", "price": 49.99, "quantity": 1},
    ],
    currency_code="USD",
    customer_email="buyer@example.com",
    return_url="https://myshop.com/thank-you",
    cancel_url="https://myshop.com/cart",
)

# Redirect your customer to Stripe's hosted checkout:
redirect(session.redirect_url)
```

### 2. Success page — confirm payment before fulfilling

```python
# On your /thank-you page, the URL contains ?session_id=...
# Extract the transaction_uid and poll:

status = client.checkout.wait_for_completion(transaction_uid, timeout=60)
if status.is_completed:
    fulfill_order()
```

### 3. Backend — manage payments with a Bearer token

```python
import tangentopay

merchant = tangentopay.MerchantClient(api_token=os.environ["TANGENTOPAY_API_TOKEN"])

# List payments
page = merchant.payments.list(per_page=20)
for txn in page.data:
    print(txn.transaction_uid, txn.transaction_status)

# Issue a refund (Stripe)
refund = merchant.refunds.create(
    transaction_uid="TXN-ABC123",
    amount=49.99,
    reason="Customer request",
    pin="1234",
    recipient_type="stripe",
)

# Check wallet balance
balances = merchant.wallets.main_balance()
```

### 4. Verify incoming webhooks

Always verify the signature before trusting webhook payloads.

```python
import tangentopay

WEBHOOK_SECRET = os.environ["TANGENTOPAY_WEBHOOK_SECRET"]

def handle_webhook(raw_body: bytes, signature_header: str):
    try:
        event = tangentopay.Webhook.construct_event(
            payload=raw_body,
            signature=signature_header,
            secret=WEBHOOK_SECRET,
        )
    except tangentopay.WebhookSignatureError:
        return 400  # reject

    if event.event == "transaction.payment_completed":
        fulfill_order(event.payload["transaction_uid"])

    return 200
```

---

## Authentication

| Client | Auth method | When to use |
|---|---|---|
| `ServiceClient` | `X-Service-Key: pk_live_...` | Storefront, checkout, success pages |
| `MerchantClient` | `Authorization: Bearer <token>` | Backend, dashboard, refunds, payouts |

### Obtaining a Bearer token

```python
# Step 1: submit credentials (triggers OTP)
challenge = auth_http.post("/auth/sign-in", json={"email": "...", "password": "..."})

# Step 2: verify OTP
token = tangentopay.login(email="me@example.com", password="secret", otp="123456")
merchant = tangentopay.MerchantClient(api_token=token)
```

Store the token securely (environment variable or secrets manager). It does not expire on its own — call `merchant.auth.logout()` to revoke it.

---

## Resources

| Resource | Client | Methods |
|---|---|---|
| `checkout` | `ServiceClient` | `create()`, `get_status()`, `wait_for_completion()` |
| `payments` | `MerchantClient` | `list()`, `get()`, `create_manual()` |
| `refunds` | `MerchantClient` | `create()`, `list()` |
| `topups` | `MerchantClient` | `create()`, `list()` |
| `payouts` | `MerchantClient` | `create()`, `bulk()`, `list()` |
| `transfers` | `MerchantClient` | `to_main()`, `list()` |
| `wallets` | `MerchantClient` | `main_balance()`, `service_balance()`, `manual_balance()` |
| `services` | `MerchantClient` | `list()`, `get()`, `create()`, `update()`, `delete()`, `create_api_key()`, `list_api_keys()`, `revoke_api_key()`, `update_webhook()` |
| `customers` | `MerchantClient` | `list()`, `get()`, `create()`, `update()`, `delete()`, `import_csv()` |
| `analytics` | `MerchantClient` | `dashboard()`, `payments_chart()`, `gross_volume()`, `total_payouts()`, … |
| `auth` | `MerchantClient` | `login()`, `verify_otp()`, `me()`, `logout()`, `change_password()` |

---

## Async support

All clients have async equivalents — `AsyncServiceClient` and `AsyncMerchantClient`.

```python
import tangentopay

async def main():
    async with tangentopay.AsyncServiceClient("pk_live_...") as client:
        session = await client.checkout.create(
            products=[{"name": "Pro Plan", "price": 49.99, "quantity": 1}],
            currency_code="USD",
        )
        print(session.redirect_url)
```

---

## Error handling

```python
try:
    refund = merchant.refunds.create(...)
except tangentopay.ValidationError as e:
    print(e.errors)          # {"amount": ["must match original"]}
except tangentopay.AuthenticationError:
    print("Invalid token — re-login")
except tangentopay.RateLimitError as e:
    print(f"Rate limited — retry after {e.retry_after}s")
except tangentopay.TangentoPayError as e:
    print(f"API error {e.http_status}: {e.message}")
```

| Exception | HTTP status |
|---|---|
| `AuthenticationError` | 401 |
| `PermissionError` | 403 |
| `NotFoundError` | 404 |
| `ValidationError` | 422 |
| `RateLimitError` | 429 |
| `ServerError` | 5xx |
| `NetworkError` | timeout / DNS failure |
| `WebhookSignatureError` | — |

---

## Supported currencies

TangentoPay supports Stripe's full currency list including:

- `USD` — US Dollar
- `EUR` — Euro
- `GBP` — British Pound
- `XAF` — Central African CFA Franc (Cameroon, Central Africa)
- `NGN` — Nigerian Naira
- `GHS` — Ghanaian Cedi
- `KES` — Kenyan Shilling
- `ZAR` — South African Rand

---

## Development

```bash
git clone https://github.com/tangentopay/tangentopay-python
cd tangentopay-python
pip install -e ".[dev]"
pytest
```

---

## License

MIT — see [LICENSE](LICENSE).
