Skip to main content

payOS Python SDK

PyPI version

The payOS Python library provides convenient access to the payOS Merchant API from applications written in Python. The library includes type definitions for all request params and response fields, and offers both synchronous and asynchronous clients powered by httpx.

To learn how to use payOS Merchant API, checkout our API Reference and Documentation. We also have some examples in Examples.

Requirements

Python 3.9 or higher.

Installation

# install from PyPi
pip install payos

Usage

Basic usage

First you need to initialize the client to interacting with payOS Merchant API.

from payos import PayOS

client = PayOS(
    client_id=os.getenv("PAYOS_CLIENT_ID"),
    api_key=os.getenv("PAYOS_API_KEY"),
    checksum_key=os.getenv("PAYOS_CHECKSUM_KEY"),
    # ... other options
)

Then you can interact with payOS Merchant API, example create a payment link using payment_requests.create().

from payos.types import CreatePaymentLinkRequest

response = client.payment_requests.create(payment_data=CreatePaymentLinkRequest(
    order_code=int(time.time()),
    amount=2000,
    description="Thanh toan",
    cancel_url="https://your-url.com/cancel",
    return_url="https://your-url.com/success",
))

Webhook verification

You can register an endpoint to receive the payment webhook.

confirm_result = client.webhooks.confirm('https://your-url.com/webhooks')

Then using webhooks.verify() to verify and receive webhook data.

# example using flask, more details in ./examples/webhooks_handling.py
@app.route("/webhooks", methods=["POST"])
def webhooks():
    data = request.get_data()

    try:
        webhook_data = client.webhooks.verify(data)
    except WebhookError as e:
        return jsonify({"error": str(e)}), 400

    return jsonify({"error": None, "data": webhook_data.model_dump_camel_case()})

Invalid payloads raise WebhookError with a message starting Invalid webhook data; pass the raw request body (str/bytes) to verify() for the strictest checks.

For more information about webhooks, see the API doc.

Handling errors

When the API return a non-success status code(i.e, 4xx or 5xx response) or non-success code data (any code except '00'), a subclass of payos.APIError is raised.

try:
    response = client.payment_requests.create(payment_data=payment_data)
    print(response)
except APIError as e:
    print(e.error_code)
    print(e.error_desc)
    print(e.status_code)

Asynchronous usage

Simply import AsyncPayOS instead of PayOS and use await with each API call:

import asyncio

from payos import AsyncPayOS
from payos.types import CreatePaymentLinkRequest

async def main() -> None:
    client = AsyncPayOS()
    payment_data = CreatePaymentLinkRequest(
        order_code=int(time.time()),
        amount=2000,
        description="Thanh toan",
        cancel_url="https://your-url.com/cancel",
        return_url="https://your-url.com/success",
    )
    try:
        response = await client.payment_requests.create(payment_data=payment_data)
        print(response)
    except APIError as e:
        print(e)

asyncio.run(main())

Auto pagination

List method in the payOS Merchant API are paginated, the library provides auto-paginating iterators with each response.

import os

from payos import PayOS
from payos.types import GetPayoutListParams

client = PayOS(
    client_id=os.getenv("PAYOS_PAYOUT_CLIENT_ID"),
    api_key=os.getenv("PAYOS_PAYOUT_API_KEY"),
    checksum_key=os.getenv("PAYOS_PAYOUT_CHECKSUM_KEY"),
)


def main() -> None:
    payouts = []
    for payout in client.payouts.list(GetPayoutListParams(limit=3)):
        payouts.append(payout)
    # or
    payouts_data = client.payouts.list(GetPayoutListParams(limit=3))
    payouts = payout_data.to_list()

    print(payouts)


main()

Or asynchronous:

import asyncio
import os

from payos import AsyncPayOS
from payos.types import GetPayoutListParams

client = AsyncPayOS(
    client_id=os.getenv("PAYOS_PAYOUT_CLIENT_ID"),
    api_key=os.getenv("PAYOS_PAYOUT_API_KEY"),
    checksum_key=os.getenv("PAYOS_PAYOUT_CHECKSUM_KEY"),
)


async def main() -> None:
    payouts = []
    async for payout in await client.payouts.list(GetPayoutListParams(limit=3)):
        payouts.append(payout)
    # or
    payouts_data = await client.payouts.list(GetPayoutListParams(limit=3))
    payouts = await payouts_data.to_list()

    print(payouts)


asyncio.run(main())

Alternative, you can use the .has_next_page(), .get_next_page() methods for more control:

# remove `await` for non-async usage
first_page = await client.payouts.list(GetPayoutListParams(limit=3))
if first_page.has_next_page():
    next_page = await first_page.get_next_page()
    print(f"number of items we just fetched: {len(next_page.data)}")

Or just work directly with the returned data:

# remove `await` for non-async usage
first_page = await client.payouts.list(GetPayoutListParams(limit=3))
for payout in first_page.data:
    print(payout.id)

Advanced usage

Custom configuration

You can customize the PayOS client with various options:

import os
import httpx

from payos import PayOS

client = PayOS(
    client_id=os.getenv("PAYOS_CLIENT_ID"),
    api_key=os.getenv("PAYOS_API_KEY"),
    checksum_key=os.getenv("PAYOS_CHECKSUM_KEY"),
    timeout=15.0,
    max_retries=4,
    http_client=httpx.Client(
        proxy="http://my-proxy.com", transport=httpx.HTTPTransport(local_address="0.0.0.0")
    ),
)

Request-level options

You can override client-level settings for individual requests:

from payos import PayOS

client = PayOS()

client.payment_requests.get(1757060811, timeout=2, max_retries=0)

Logging

We use standard library logging module. You can enable logging by setting the environment variable PAYOS_LOG to info or debug.

export PAYOS_LOG=info

Direct API access

For advanced use cases, you can make direct API calls:

from payos import PayOS

client = PayOS()

response = client.get("/v2/payment-requests", cast_to=dict)

response = client.post(
    "/v2/payment-requests",
    body={
        "orderCode": int(time()),
        "amount": 2000,
        "description": "thanh toan",
        "returnUrl": "https://your-url.com/success",
        "cancelUrl": "https://your-url.com/cancel",
        "signature": "signature",
    },
    cast_to=dict,
)

Signature

The signature can be manually created by .crypto:

# for create payment link signature
signature = client.crypto.create_signature_of_payment_request(
    {
        "orderCode": int(time()),
        "amount": 2000,
        "description": "thanh toan",
        "returnUrl": "https://your-url.com/success",
        "cancelUrl": "https://your-url.com/cancel",
    },
    client.checksum_key,
)

# for payment-requests and webhook signature
signature = client.crypto.create_signature_from_object(
    data,
    client.checksum_key,
)

# for payouts signature
signature = client.crypto.create_signature(client.checksum_key, data)

Contributing

See the contributing documentation.

Metadata

Release files for payos 1.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for payos 1.1.1
File Size Uploaded Provenance Actions
payos-1.1.1.tar.gz 36.6 kB Without provenance Details for payos-1.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for payos 1.1.1
File Interpreter ABI Platform Actions
payos-1.1.1-py3-none-any.whl Python 3 none any Details for payos-1.1.1-py3-none-any.whl

Total release size: 93.4 kB

Release files / payos-1.1.1.tar.gz

Download URL payos-1.1.1.tar.gz
Size 36.6 kB
Tags Source
SHA-256 checksum
How to use checksums
e9173d55d2645d53237ec868438aab36f2dc2ec08da8b906ff9d6c57d2b325a4
BLAKE2b-256 checksum
How to use checksums
4f37d6209e6e55e51f321eb4df2fd1a8a47cdf6b6b5ac832351aa58479330bb3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / payos-1.1.1-py3-none-any.whl

Download URL payos-1.1.1-py3-none-any.whl
Size 56.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b3244ea34e9fd270483efcc51eec984dabb68334685fa3abf0c0635292658499
BLAKE2b-256 checksum
How to use checksums
97a632833913c0977c26e5b492955e0bb647166d1e8f72042ec2ccfce8e1147e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for payos 1.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page