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

> ## Agent Instructions
> Describe only the public 123hub merchant API documented on this site. The primary endpoint is POST /public/api/multihub/v1.
> Preserve API method names, field names, header names, and error codes exactly as documented. Do not invent endpoints or parameters.
> Treat every amount as an integer in minor units unless a page explicitly states otherwise.
> Never expose, request, or fabricate a merchant secret key. The SDK pages contain reference implementations, not official SDK packages.

# Python Examples

> Integrate with the 123hub API using Python

# Python Examples

Complete Python example client for integrating with the 123hub API using `requests` and `hashlib`.

> [!NOTE]
>
> This is a reference implementation, not an official SDK package. You can copy
> it into your project and adapt it as needed.

## Installation

```bash theme={null}
pip install requests
```

## Configuration

Store your credentials in environment variables:

```bash theme={null}
export PAYMENT_API_APP_ID="1"
export PAYMENT_API_SECRET_KEY="your_secret_key"
```

## PaymentApiClient Class

A complete, reusable client class for all API operations:

```python theme={null}
import hashlib
import hmac
import json
import os
import time
import uuid
import requests


class PaymentApiClient:
    """123hub API Client for Python"""

    def __init__(
        self,
        app_id: str = None,
        secret_key: str = None,
        base_url: str = "https://api.bafanglaicai88.com",
        timeout=(3.05, 30),
    ):
        self.app_id = app_id or os.environ.get("PAYMENT_API_APP_ID")
        self.secret_key = secret_key or os.environ.get("PAYMENT_API_SECRET_KEY")
        self.base_url = base_url
        self.timeout = timeout

        if not self.app_id or not self.secret_key:
            raise ValueError("app_id and secret_key are required")

    def _send(self, body: dict) -> dict:
        """Sign and send a request to the 123hub API."""
        # Serialize once: the hash must cover exactly the bytes that are sent.
        body_bytes = json.dumps(body, separators=(",", ":")).encode("utf-8")
        headers = {
            "Content-Type": "application/json",
            "X-Data-Application-Id": str(self.app_id),
            # Lowercase hex SHA-512 of (raw body + secret key)
            "X-Data-Hash": hashlib.sha512(
                body_bytes + self.secret_key.encode("utf-8")
            ).hexdigest(),
            # Optional replay protection: send both headers or neither.
            # They are not part of the hash.
            "X-Data-Timestamp": str(int(time.time())),
            "X-Data-Nonce": uuid.uuid4().hex,
        }
        response = requests.post(
            self.base_url + "/public/api/multihub/v1",
            data=body_bytes,
            headers=headers,
            timeout=self.timeout,
        )
        return self._verify_response(response)

    def _verify_response(self, response) -> dict:
        """Check the response X-Data-Hash before trusting the body."""
        raw = response.content  # exact response bytes
        received = response.headers.get("X-Data-Hash")
        if received is not None:
            expected = hashlib.sha512(raw + self.secret_key.encode("utf-8")).hexdigest()
            if not hmac.compare_digest(expected, received.strip().lower()):
                raise RuntimeError("response signature verification failed")
        try:
            result = json.loads(raw)
        except ValueError:
            result = None
        if not isinstance(result, dict) or not isinstance(result.get("success"), bool):
            # Not the standard envelope, e.g. a 503 returned before authentication
            raise RuntimeError(
                f"Unexpected HTTP {response.status_code} response: {response.text[:200]}"
            )
        if received is None and result["success"]:
            # Successful responses are always signed; never trust an unsigned one
            raise RuntimeError("response signature verification failed: X-Data-Hash missing")
        # Errors raised before authentication (e.g. 3000, 3001, 3003, 3006) are
        # unsigned and are returned as-is.
        return result

    def ping(self) -> dict:
        """Health check / connectivity test."""
        return self._send({"method": "gateway.ping", "params": {}})

    def create_deposit(
        self,
        service_id: int,
        amount: int,
        currency: str,
        c_id: str,
        **kwargs,
    ) -> dict:
        """Create a deposit (pay-in) payment."""
        return self._send({
            "method": "payment.in",
            "service_id": service_id,
            "params": {
                "payment": {
                    "identifiers": {"c_id": c_id},
                    "amount": {"value": amount, "currency": currency},
                    **kwargs,
                }
            },
        })

    def create_withdrawal(
        self,
        service_id: int,
        amount: int,
        currency: str,
        c_id: str,
        receiver: dict,
        **kwargs,
    ) -> dict:
        """Create a withdrawal (payout) payment."""
        return self._send({
            "method": "payment.out",
            "service_id": service_id,
            "params": {
                "payment": {
                    "identifiers": {"c_id": c_id},
                    "amount": {"value": amount, "currency": currency},
                    "receiver": receiver,
                    **kwargs,
                }
            },
        })

    def get_status(
        self, c_id: str = None, h_id: str = None
    ) -> dict:
        """Check payment status by identifiers."""
        identifiers = {}
        if c_id:
            identifiers["c_id"] = c_id
        if h_id:
            identifiers["h_id"] = h_id
        return self._send({
            "method": "payment.status",
            "params": {"payment": {"identifiers": identifiers}},
        })

    def get_balance(self) -> dict:
        """Retrieve account balances."""
        return self._send({"method": "balance.get", "params": {}})
```

## Usage Examples

### Ping (Health Check)

```python theme={null}
client = PaymentApiClient(app_id="1", secret_key="your_secret_key")

result = client.ping()
print(result)
# {"success": true, "result": {"message": "pong"}, ...}
```

### Create a Deposit Payment

The examples below use INR (India), but the same client works for [every supported country](https://prod-docs.123hub.pro/countries/overview.md) -- just change the `service_id`, `currency`, and `country` values.

```python theme={null}
client = PaymentApiClient(app_id="1", secret_key="your_secret_key")

result = client.create_deposit(
    service_id=14701,
    amount=10000,
    currency="INR",
    c_id="12345",
    description="Order #12345",
    payer={
        "email": "customer@example.com",
        "person": {
            "first_name": "John",
            "last_name": "Doe",
        },
    },
)

if result["success"]:
    payment = result["result"]["payment"]
    print(f"Payment created successfully")
    print(f"Request ID: {result['request_id']}")
else:
    print(f"Error: {result['error']['code']} - {result['error']['message']}")
```

### Create a Withdrawal (Payout)

```python theme={null}
result = client.create_withdrawal(
    service_id=14701,
    amount=5000,
    currency="INR",
    c_id="67890",
    receiver={
        "bank": {
            "account": {"id": "1234567890"},
            "ifsc": "SBIN0001234",
        },
        "person": {
            "first_name": "Jane",
            "last_name": "Doe",
        },
    },
    description="Payout #67890",
)

if result["success"]:
    print("Withdrawal created successfully")
else:
    print(f"Error: {result['error']['code']} - {result['error']['message']}")
```

### Check Payment Status

```python theme={null}
# Look up by client-side ID
result = client.get_status(c_id="12345")

if result["success"]:
    status = result["result"]["payment"]["status"]["status"]
    print(f"Payment status: {status}")
else:
    print(f"Error: {result['error']['code']} - {result['error']['message']}")

# Look up by the 123hub payment ID (h_id from the create response)
result = client.get_status(h_id="pay_1774892151645_abcd")

if result["success"]:
    status = result["result"]["payment"]["status"]["status"]
    print(f"Payment status: {status}")
```

### Get Balance

```python theme={null}
result = client.get_balance()

if result["success"]:
    for amount in result["result"]["balance"]["amounts"]:
        print(f"{amount['currency']}: {amount['value']}")
else:
    print(f"Error: {result['error']['code']} - {result['error']['message']}")
```

## Error Handling

Successful responses return HTTP 200. Most errors return HTTP 400; some use 403, 404, 409, 429 or 5xx (see [Error codes](https://prod-docs.123hub.pro/errors/error-codes.md)). The client returns the parsed body for every standard envelope, so always use the `success` field to determine the outcome:

```python theme={null}
client = PaymentApiClient(app_id="1", secret_key="your_secret_key")

result = client.create_deposit(
    service_id=14701,
    amount=10000,
    currency="INR",
    c_id="12345",
    payer={"email": "customer@example.com"},  # payer is required for payment.in
)

if result["success"]:
    # Operation succeeded
    payment = result["result"]
    print(f"Request ID: {result['request_id']}")
    print(f"Processing time: {result['processing_time']}ms")
else:
    # Operation failed
    error = result["error"]
    print(f"Error code: {error['code']}")
    print(f"Error message: {error['message']}")

    # Handle specific error codes
    if error["code"] == 3000:
        print("Authentication failed - check your secret key")
    elif error["code"] == 1005 or error["code"] == 9000:
        print("Invalid parameters - check request body")
    elif error["code"] == 7002:
        print("Provider unavailable - check payment.status before retrying")
```

## Handling Network Errors

Network-level errors can still occur independently of API responses:

```python theme={null}
import requests

client = PaymentApiClient(app_id="1", secret_key="your_secret_key")

try:
    result = client.ping()
    if result["success"]:
        print("API is reachable")
    else:
        print(f"API error: {result['error']['message']}")
except requests.ConnectionError:
    print("Cannot reach the API - check network connectivity")
except requests.Timeout:
    print("Request timed out - try again")
except requests.RequestException as e:
    print(f"Request failed: {e}")
except RuntimeError as e:
    # Raised by the client for a failed response signature check or a
    # non-envelope body (e.g. HTTP 503 before authentication)
    print(f"Untrusted or unexpected response: {e}")
```

## Complete Example

```python theme={null}
#!/usr/bin/env python3
"""
123hub API Integration Example

Demonstrates the complete flow: ping, check balance, create a deposit,
and poll for status.
"""
import os
import hashlib
import hmac
import json
import time
import uuid
import requests


class PaymentApiClient:
    def __init__(
        self,
        app_id,
        secret_key,
        base_url="https://api.bafanglaicai88.com",
        timeout=(3.05, 30),
    ):
        self.app_id = app_id
        self.secret_key = secret_key
        self.base_url = base_url
        self.timeout = timeout

    def _send(self, body):
        # Serialize once: the hash must cover exactly the bytes that are sent.
        body_bytes = json.dumps(body, separators=(",", ":")).encode("utf-8")
        headers = {
            "Content-Type": "application/json",
            "X-Data-Application-Id": str(self.app_id),
            "X-Data-Hash": hashlib.sha512(
                body_bytes + self.secret_key.encode("utf-8")
            ).hexdigest(),
            # Optional replay pair (both or neither); not part of the hash
            "X-Data-Timestamp": str(int(time.time())),
            "X-Data-Nonce": uuid.uuid4().hex,
        }
        response = requests.post(
            self.base_url + "/public/api/multihub/v1",
            data=body_bytes,
            headers=headers,
            timeout=self.timeout,
        )
        # Verify the response X-Data-Hash over the exact response bytes
        raw = response.content
        received = response.headers.get("X-Data-Hash")
        if received is not None:
            expected = hashlib.sha512(raw + self.secret_key.encode("utf-8")).hexdigest()
            if not hmac.compare_digest(expected, received.strip().lower()):
                raise RuntimeError("response signature verification failed")
        try:
            result = json.loads(raw)
        except ValueError:
            result = None
        if not isinstance(result, dict) or not isinstance(result.get("success"), bool):
            raise RuntimeError(
                f"Unexpected HTTP {response.status_code} response: {response.text[:200]}"
            )
        if received is None and result["success"]:
            raise RuntimeError("response signature verification failed: X-Data-Hash missing")
        return result  # unsigned errors before authentication are returned as-is

    def ping(self):
        return self._send({"method": "gateway.ping", "params": {}})

    def get_balance(self):
        return self._send({"method": "balance.get", "params": {}})

    def create_deposit(self, service_id, amount, currency, c_id, **kwargs):
        return self._send({
            "method": "payment.in",
            "service_id": service_id,
            "params": {
                "payment": {
                    "identifiers": {"c_id": c_id},
                    "amount": {"value": amount, "currency": currency},
                    **kwargs,
                }
            },
        })

    def get_status(self, c_id=None, h_id=None):
        identifiers = {}
        if c_id:
            identifiers["c_id"] = c_id
        if h_id:
            identifiers["h_id"] = h_id
        return self._send({
            "method": "payment.status",
            "params": {"payment": {"identifiers": identifiers}},
        })


def main():
    app_id = os.environ.get("PAYMENT_API_APP_ID", "1")
    secret_key = os.environ.get("PAYMENT_API_SECRET_KEY", "your_secret_key")

    client = PaymentApiClient(
        app_id=app_id,
        secret_key=secret_key,
    )

    # 1. Ping the gateway
    ping_result = client.ping()
    if not ping_result["success"]:
        print(f"Gateway unreachable: {ping_result['error']['message']}")
        return
    print("Gateway is up")

    # 2. Check balance
    balance_result = client.get_balance()
    if balance_result["success"]:
        for b in balance_result["result"]["balance"]["amounts"]:
            print(f"  {b['currency']}: {b['value']}")
    else:
        print(f"Balance check failed: {balance_result['error']['message']}")

    # 3. Create a deposit
    order_id = str(int(time.time()))
    deposit_result = client.create_deposit(
        service_id=14701,
        amount=10000,
        currency="INR",
        c_id=order_id,
        description=f"Order #{order_id}",
        payer={
            "email": "customer@example.com",
            "person": {"first_name": "John", "last_name": "Doe"},
        },
    )

    if deposit_result["success"]:
        print(f"Deposit created (request_id={deposit_result['request_id']})")
    else:
        print(f"Deposit failed: {deposit_result['error']['message']}")
        return

    # 4. Poll for status
    for _ in range(5):
        time.sleep(3)
        status_result = client.get_status(c_id=order_id)
        if status_result["success"]:
            status = status_result["result"]["payment"]["status"]["status"]
            print(f"Payment status: {status}")
            if status in ("success", "error", "canceled", "declined", "refunded", "partially_refunded"):
                break
        else:
            print(f"Status check failed: {status_result['error']['message']}")
            break


if __name__ == "__main__":
    main()
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.