Metadata-Version: 2.4
Name: fype-sdk-beta
Version: 1.0.0
Summary: Official Python SDK for Fype Payments Layer
Author-email: Fype Engineering <engineering@fype.dev>
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.8
Description-Content-Type: text/markdown
Requires-Dist: httpx>=0.23.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.20.0; extra == "dev"

# Fype Python Client SDK

The official Python client library for the [Fype Payments Orchestration Layer](https://fype.dev). Fully type-safe, async-friendly, and lightweight, it simplifies payment creations, refunds, and signed webhook signature verifications under a unified API interface.

---

## Installation

Install the package directly from your local virtual environment:
```bash
pip install -e packages/python-sdk
```

*(Or via PyPI once distributed)*:
```bash
pip install fype
```

---

## Quick Start

### 1. Initialize Client
Expose your Fype developer API key (use test key for sandbox or live key for production):
```python
from fype import Fype

# Initialize the client
fype = Fype(api_key="fype_test_your_secret_api_key_here")
```

### 2. Create Hosted Checkout Session
Initiate a payment order. Fype will automatically contact gateway adapters under the hood and return a public buyer-facing checkout URL:
```python
payment = fype.payments.create(
    amount=25000,                           # Amount in paise (₹250.00 INR)
    currency="INR",
    customer_email="buyer@email.com",
    success_url="https://yourwebsite.com/payment/success",
    cancel_url="https://yourwebsite.com/payment/cancel",
    reference_id="order_ref_1092",          # Optional merchant order ID
    provider="cashfree"                     # Optional: Explicitly choose gateway (razorpay/cashfree)
)

print(f"Transaction ID: {payment['id']}")
print(f"Checkout URL: {payment['checkout_url']}")
```

### 3. Dynamic Redirect Placeholders
Like Stripe, Fype natively supports dynamic placeholders inside `success_url` and `cancel_url` redirect strings. This allows you to build frictionless, stateless checkout loops (e.g. for login-free purchases). 

Fype will automatically replace these placeholders before redirecting the buyer back to your website:
* **`{CHECKOUT_SESSION_ID}`**: Replaced with the actual Fype Checkout Session UUID.
* **`{PAYMENT_ID}`**: Replaced with the actual Fype Payment UUID (useful for direct API validation).

**Example:**
```python
payment = fype.payments.create(
    amount=25000,
    currency="INR",
    customer_email="buyer@email.com",
    success_url="https://yourwebsite.com/payment/success?fype_session_id={PAYMENT_ID}",
    cancel_url="https://yourwebsite.com/payment/cancel"
)
```

---

## 4. Retrieve Payment Details
Audit checkout session status at any time:
```python
payment = fype.payments.retrieve("pay_test_abc123")
print(f"Current Status: {payment['status']}")  # 'created', 'succeeded', 'failed'
```

### 4. Issue a Refund
Perform partial or full refunds for successful payments:
```python
# Full Refund (omit amount parameter)
refund = fype.refunds.create(payment_id="pay_test_abc123")

# Partial Refund (specify amount in paise)
partial_refund = fype.refunds.create(payment_id="pay_test_abc123", amount=5000)
```

---

## Webhook Signature Verification

Incoming HTTP webhook events are cryptographically signed by Fype. Always verify signatures against your webhook signing secret (`whsec_...`) to prevent spoofing. The SDK handles constant-time HMAC comparison internally to guard against side-channel timing analysis attacks:

```python
from fype.errors import SignatureVerificationError

raw_body = request.body()  # Get raw request bytes
signature = request.headers.get("X-Fype-Signature")
secret = "whsec_your_webhook_signing_secret"

try:
    fype.webhooks.verify_signature(raw_body, signature, secret)
    print("Webhook signature is valid and authentic!")
    # Proceed to handle events (e.g. payment.succeeded)
except SignatureVerificationError as e:
    print(f"Webhook signature mismatch: {e}")
```

---

## Error Handling

The SDK exposes explicit, catchable exception classes to let you handle failures gracefully:

```python
from fype.errors import AuthenticationError, InvalidRequestError, ApiConnectionError, FypeError

try:
    payment = fype.payments.create(...)
except AuthenticationError:
    # Handle bad API keys
    print("Invalid Fype API key.")
except InvalidRequestError as e:
    # Handle validation errors (e.g. invalid currency, negative amount)
    print(f"Request failed validation: {e}")
except ApiConnectionError:
    # Handle network timeouts or unreachable hosts
    print("Connection to Fype server timed out.")
except FypeError as e:
    # Handle server-side errors
    print(f"Fype gateway error: {e}")
```
