Chuyển tới nội dung chính

Python SDK

Tài liệu đầy đủ

Để biết thêm chi tiết về các phương thức, tham số và tính năng nâng cao (auto-pagination, async support, error handling, v.v.), vui lòng xem GitHub Repository.

Cài đặt

Cài đặt thư viện payos thông qua pip:

# Windows
pip install payos

# Linux/macOS
pip3 install payos

Khởi tạo

Khởi tạo đối tượng PayOS từ biến môi trường hoặc truyền trực tiếp các thông số:

from payos import PayOS
import os

# Khởi tạo từ biến môi trường
payOS = PayOS(
client_id=os.environ.get('PAYOS_CLIENT_ID'),
api_key=os.environ.get('PAYOS_API_KEY'),
checksum_key=os.environ.get('PAYOS_CHECKSUM_KEY')
)

Sử dụng phương thức payment_requests.create() để tạo link thanh toán:

from payos.types import CreatePaymentLinkRequest
import time

payment_request = CreatePaymentLinkRequest(
order_code=int(time.time()),
amount=2000,
description="Thanh toán đơn hàng",
cancel_url="https://your-domain.com/cancel",
return_url="https://your-domain.com/success"
)

payment_link = payOS.payment_requests.create(payment_request)
print(payment_link.checkout_url)

Xác minh webhook

Sử dụng phương thức webhooks.verify() để xác thực dữ liệu webhook:

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def webhook_handler(request):
try:
webhook_data = payOS.webhooks.verify(request.body)
print(f"Thanh toán thành công: {webhook_data.order_code}")
return JsonResponse({"message": "OK"}, status=200)
except Exception as e:
print(f"Webhook không hợp lệ: {e}")
return JsonResponse({"message": "Invalid webhook"}, status=400)

Hỗ trợ Async

Thư viện cung cấp AsyncPayOS cho các framework async như FastAPI:

from payos import AsyncPayOS

# Khởi tạo async client
async_payos = AsyncPayOS(client_id, api_key, checksum_key)

# Sử dụng với async/await
payment_link = await async_payos.payment_requests.create(payment_request)

Tạo payout

Sử dụng phương thức payouts.batch.create() để tạo payout theo lô:

from payos.types import PayoutBatchRequest, PayoutBatchItem
import time

reference_id = f"payout_{int(time.time())}"
payout_batch = payOS.payouts.batch.create(
PayoutBatchRequest(
reference_id=reference_id,
category=["salary"],
validate_destination=True,
payouts=[
PayoutBatchItem(
reference_id=f"{reference_id}_1",
amount=2000,
description="Thanh toán lương",
to_bin="970422",
to_account_number="0123456789"
),
PayoutBatchItem(
reference_id=f"{reference_id}_2",
amount=3000,
description="Thanh toán thưởng",
to_bin="970422",
to_account_number="0987654321"
)
]
)
)

print(f"Payout ID: {payout_batch.id}")