> ## Documentation Index
> Fetch the complete documentation index at: https://docs.oneclickdz.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Python SDK Integration

> Quick setup guide for Navio Python SDK

## Overview

The Navio Python SDK provides a clean, idiomatic interface for integrating Navio payments into your Python applications. Built with Python 3.8+ type hints and dataclasses for the best developer experience.

<CardGroup cols={2}>
  <Card title="Pythonic API" icon="code" color="#0D9373">
    Clean interface with full type hints and dataclasses
  </Card>

  <Card title="Type safe" icon="shield-check" color="#0D9373">
    Full type annotations with dataclasses and enums
  </Card>

  <Card title="Input validation" icon="circle-check" color="#0D9373">
    Client-side validation for fast error feedback
  </Card>

  <Card title="Minimal dependencies" icon="box" color="#0D9373">
    Only requires the `requests` package
  </Card>
</CardGroup>

## Requirements

* Python 3.8 or higher
* pip

## Installation

Install via pip:

```bash theme={null}
pip install ocpay-python-sdk
```

Or install from source:

```bash theme={null}
git clone https://github.com/oneclickdz/ocpay-python-sdk.git
cd ocpay-python-sdk
pip install -e .
```

## Quick start

### 1. Initialize the SDK

```python theme={null}
from ocpay import OCPay

ocpay = OCPay("your-api-access-token")
```

<Warning>
  Store your API key in environment variables, never hardcoded in source code.
</Warning>

### 2. Create a payment link

```python theme={null}
from ocpay import OCPay, FeeMode
from ocpay.types import ProductInfo, CreateLinkRequest

ocpay = OCPay("your-api-key")

request = CreateLinkRequest(
    product_info=ProductInfo(
        title="Premium Subscription",
        amount=5000,  # Amount in DZD (500–500,000)
        description="Monthly access to all premium features",
    ),
    fee_mode=FeeMode.NO_FEE,
    success_message="Thank you for your purchase!",
    redirect_url="https://yourstore.com/success?orderId=12345",
)

response = ocpay.create_link(request)

# Share this URL with your customer
print("Payment URL:", response.payment_url)

# Save this reference for tracking
print("Payment Reference:", response.payment_ref)
```

### 3. Check payment status

```python theme={null}
from ocpay import OCPay

ocpay = OCPay("your-api-key")

status = ocpay.check_payment("OCPL-A1B2C3-D4E5")

if status.is_confirmed():
    print("Payment confirmed!")
    if status.transaction_details:
        print(f"Amount: {status.transaction_details.amount} DZD")
elif status.is_pending():
    print("Payment still pending...")
elif status.is_failed():
    print(f"Payment failed: {status.message}")
```

## Complete e-commerce example

<Accordion title="Full e-commerce order flow">
  ```python theme={null}
  from ocpay import (
      OCPay,
      FeeMode,
      ValidationException,
      ApiException,
  )
  from ocpay.types import ProductInfo, CreateLinkRequest

  # Initialize SDK
  ocpay = OCPay("your-api-key")

  # Step 1: Create payment link for your order
  order_id = "ORD-12345"
  response = ocpay.create_link(CreateLinkRequest(
      product_info=ProductInfo(
          title=f"Order #{order_id}",
          amount=8000,
          description=f"Payment for order #{order_id}",
      ),
      fee_mode=FeeMode.NO_FEE,
      success_message=f"Thank you! Your order #{order_id} is being processed.",
      redirect_url=f"https://yourstore.com/orders/{order_id}/success",
  ))

  # Step 2: Save payment reference to your database
  print(f"Payment URL: {response.payment_url}")
  print(f"Payment Ref: {response.payment_ref}")

  # Step 3: Check payment status (in webhook or polling job)
  status = ocpay.check_payment(response.payment_ref)

  if status.is_confirmed():
      print("✅ Payment confirmed - fulfilling order")
  elif status.is_failed():
      print("❌ Payment failed")
  else:
      print("⏳ Payment is pending")
  ```
</Accordion>

## API reference

### OCPay class

Main entry point for the SDK.

#### Constructor

```python theme={null}
OCPay(access_token: str, options: ClientOptions = None)
```

<ParamField body="access_token" type="string" required>
  Your OneClickDz API access token.
</ParamField>

<ParamField body="options" type="ClientOptions">
  Optional client configuration.

  <Expandable title="ClientOptions properties">
    <ParamField body="timeout" type="int">
      Request timeout in seconds. Default: `30`.
    </ParamField>

    <ParamField body="base_url" type="string">
      Custom base URL, mainly used for testing.
    </ParamField>

    <ParamField body="headers" type="dict">
      Additional headers to include in every request.
    </ParamField>
  </Expandable>
</ParamField>

**Example:**

```python theme={null}
from ocpay import OCPay, ClientOptions

ocpay = OCPay("your-api-key", options=ClientOptions(timeout=60))
```

#### `create_link(request)`

Creates a new payment link.

<ParamField body="request" type="CreateLinkRequest" required>
  Payment link creation request.

  <Expandable title="CreateLinkRequest properties">
    <ParamField body="product_info" type="ProductInfo" required>
      Product information.

      <Expandable title="ProductInfo properties">
        <ParamField body="title" type="string" required>
          Product or service name (1–200 characters).
        </ParamField>

        <ParamField body="amount" type="int" required>
          Amount in DZD (500–500,000). Must be a whole number.
        </ParamField>

        <ParamField body="description" type="string">
          Optional product description (max 1000 characters).
        </ParamField>
      </Expandable>
    </ParamField>

    <ParamField body="fee_mode" type="FeeMode">
      Who pays transaction fees. Default: `FeeMode.NO_FEE`.
    </ParamField>

    <ParamField body="success_message" type="string">
      Optional message shown to the customer after payment (max 500 characters).
    </ParamField>

    <ParamField body="redirect_url" type="string">
      Optional URL to redirect the customer after payment completes.
    </ParamField>
  </Expandable>
</ParamField>

**Returns:**

<ResponseField name="payment_url" type="string">
  The payment page URL to share with your customer.
</ResponseField>

<ResponseField name="payment_ref" type="string">
  Unique payment reference code (e.g., `OCPL-A1B2C3-D4E5`). Save this to track payment status.
</ResponseField>

**Raises:** `ValidationException` (400), `UnauthorizedException` (403), `ApiException`

#### `check_payment(payment_ref)`

Checks the status of a payment.

<ParamField body="payment_ref" type="string" required>
  Payment reference code returned by `create_link` (e.g., `"OCPL-A1B2C3-D4E5"`).
</ParamField>

**Returns:**

<ResponseField name="status" type="PaymentStatus">
  Current payment status: `PENDING`, `CONFIRMED`, or `FAILED`.
</ResponseField>

<ResponseField name="message" type="string">
  Human-readable status message.
</ResponseField>

<ResponseField name="transaction_details" type="TransactionDetails">
  Confirmed transaction details. Only present when `status` is `CONFIRMED`.
</ResponseField>

**Raises:** `NotFoundException` (404), `PaymentExpiredException` (410), `ApiException`

### Enums

#### FeeMode

| Value                  | Description                                    |
| ---------------------- | ---------------------------------------------- |
| `FeeMode.NO_FEE`       | Merchant pays all fees (default)               |
| `FeeMode.SPLIT_FEE`    | Fees split 50/50 between merchant and customer |
| `FeeMode.CUSTOMER_FEE` | Customer pays all fees                         |

#### PaymentStatus

| Value                     | Description                                 |
| ------------------------- | ------------------------------------------- |
| `PaymentStatus.PENDING`   | Payment is in progress                      |
| `PaymentStatus.CONFIRMED` | Payment completed successfully              |
| `PaymentStatus.FAILED`    | Payment was declined, expired, or cancelled |

### Exception classes

<AccordionGroup>
  <Accordion title="ValidationException - HTTP 400">
    Raised when the request data is invalid (e.g., amount out of range, missing required fields).

    **Properties:** `message`, `status_code`, `request_id`, `error_data`
  </Accordion>

  <Accordion title="UnauthorizedException - HTTP 403">
    Raised when authentication fails. Check that your API key is valid and active.

    **Properties:** `message`, `status_code`, `request_id`, `error_data`
  </Accordion>

  <Accordion title="NotFoundException - HTTP 404">
    Raised when the payment reference does not exist.

    **Properties:** `message`, `status_code`, `request_id`, `error_data`
  </Accordion>

  <Accordion title="PaymentExpiredException - HTTP 410">
    Raised when the payment link has expired. Links expire 20 minutes after creation.

    **Properties:** `message`, `status_code`, `request_id`, `error_data`
  </Accordion>

  <Accordion title="ApiException - various">
    Base exception for all other API errors. Catch this as a fallback.

    **Properties:** `message`, `status_code`, `request_id`, `error_data`
  </Accordion>
</AccordionGroup>

## Error handling

```python theme={null}
from ocpay import (
    OCPay,
    ApiException,
    ValidationException,
    UnauthorizedException,
    NotFoundException,
    PaymentExpiredException,
)

ocpay = OCPay("your-api-key")

try:
    response = ocpay.create_link(request)
except ValidationException as e:
    print(f"Validation error: {e.message}")
    print(f"Request ID: {e.request_id}")
except UnauthorizedException as e:
    print("Authentication failed. Check your API key.")
except NotFoundException as e:
    print(f"Not found: {e.message}")
except PaymentExpiredException as e:
    print(f"Payment expired: {e.message}")
except ApiException as e:
    print(f"API error: {e.message} (status {e.status_code})")
    print(f"Request ID: {e.request_id}")
```

## Framework integration

<Tabs>
  <Tab title="Flask">
    ```python theme={null}
    from flask import Flask, jsonify, request
    from ocpay import OCPay, FeeMode
    from ocpay.types import CreateLinkRequest, ProductInfo

    app = Flask(__name__)
    ocpay = OCPay("your-api-key")

    @app.route("/api/payment", methods=["POST"])
    def create_payment():
        data = request.json
        response = ocpay.create_link(CreateLinkRequest(
            product_info=ProductInfo(
                title=data["title"],
                amount=data["amount"],
            ),
            fee_mode=FeeMode.NO_FEE,
        ))
        return jsonify({
            "payment_url": response.payment_url,
            "payment_ref": response.payment_ref,
        })
    ```
  </Tab>

  <Tab title="Django">
    ```python theme={null}
    from ocpay import OCPay, FeeMode
    from ocpay.types import CreateLinkRequest, ProductInfo

    ocpay = OCPay(settings.OCPAY_API_KEY)

    def create_order_payment(order):
        response = ocpay.create_link(CreateLinkRequest(
            product_info=ProductInfo(
                title=f"Order #{order.id}",
                amount=order.total,
            ),
            fee_mode=FeeMode.NO_FEE,
            redirect_url=f"https://yourstore.com/orders/{order.id}/success",
        ))
        order.payment_ref = response.payment_ref
        order.save()
        return response.payment_url
    ```
  </Tab>

  <Tab title="FastAPI">
    ```python theme={null}
    from fastapi import FastAPI
    from ocpay import OCPay, FeeMode
    from ocpay.types import CreateLinkRequest, ProductInfo

    app = FastAPI()
    ocpay = OCPay("your-api-key")

    @app.post("/api/payment")
    async def create_payment(title: str, amount: int):
        response = ocpay.create_link(CreateLinkRequest(
            product_info=ProductInfo(title=title, amount=amount),
            fee_mode=FeeMode.NO_FEE,
        ))
        return {
            "payment_url": response.payment_url,
            "payment_ref": response.payment_ref,
        }
    ```
  </Tab>
</Tabs>

## Important notes

<Warning>
  **Merchant validation required** - Complete merchant validation at [app.oneclickdz.com/profile](https://app.oneclickdz.com/profile) before using the API.
</Warning>

<Warning>
  **Amount limits** - Minimum 500 DZD, maximum 500,000 DZD. Must be whole numbers (no decimals).
</Warning>

<Note>
  **Link expiration** - Payment links expire 20 minutes after creation. After expiration the status becomes `FAILED`.
</Note>

<Note>
  **Sandbox testing** - Use your sandbox API key for testing. Check `response.payment_link.is_sandbox` to confirm test mode.
</Note>

<CardGroup cols={3}>
  <Card title="API reference" icon="square-terminal" href="/en/api-reference/ocpay/create-link">
    View the Navio API endpoints
  </Card>

  <Card title="Support" icon="envelope" href="mailto:support@oneclickdz.com">
    Contact our support team
  </Card>

  <Card title="GitHub" icon="github" href="https://github.com/oneclickdz/ocpay-python-sdk">
    View the source on GitHub
  </Card>
</CardGroup>
