Metadata-Version: 2.4
Name: gpmpay-sdk
Version: 0.4.0
Summary: Official Python SDK for GPM Pay — VietQR codes, transaction webhooks, and payment reconciliation.
Project-URL: Homepage, https://app.gpmpay.com/docs#python-sdk
Project-URL: Documentation, https://app.gpmpay.com/docs#python-sdk
Project-URL: Changelog, https://app.gpmpay.com/docs#python-sdk
Author-email: GPM Softwares <admin@gpmsoftwares.com>
Maintainer-email: GPM Softwares <admin@gpmsoftwares.com>
License: MIT
License-File: LICENSE
Keywords: banking,gpmpay,napas,payments,vietnam,vietqr,webhook
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Topic :: Office/Business :: Financial
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: httpx>=0.27
Provides-Extra: dev
Requires-Dist: build>=1.2; extra == 'dev'
Requires-Dist: django>=4.2; extra == 'dev'
Requires-Dist: flask>=2.2; extra == 'dev'
Requires-Dist: mypy>=1.11; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
Requires-Dist: pytest-cov>=5; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Requires-Dist: starlette>=0.27; extra == 'dev'
Requires-Dist: twine>=5; extra == 'dev'
Provides-Extra: django
Requires-Dist: django>=4.2; extra == 'django'
Provides-Extra: fastapi
Requires-Dist: starlette>=0.27; extra == 'fastapi'
Provides-Extra: flask
Requires-Dist: flask>=2.2; extra == 'flask'
Description-Content-Type: text/markdown

# gpmpay-sdk

SDK Python chính thức cho **GPM Pay** — mã VietQR, webhook giao dịch, và đối soát
thanh toán.

*English: [README.en.md](README.en.md)*

```bash
pip install gpmpay-sdk
```

Yêu cầu Python 3.9+. Một dependency runtime duy nhất: `httpx`.

---

## Mô hình thanh toán, nói thẳng

GPM Pay **không có khái niệm đơn hàng**. Không có endpoint tạo order, không có mã
tham chiếu do server sinh, không có endpoint sinh QR. Luồng thật là:

1. **Bạn** chọn mã đối soát của riêng mình (`SHOP1042`, `DH2026080901`…).
2. **Bạn** dựng VietQR tại chỗ bằng SDK, nhúng mã đó vào nội dung chuyển khoản.
3. Người mua quét, chuyển tiền. Ngân hàng ghi nhận.
4. GPM Pay POST webhook về endpoint của bạn.
5. **Bạn** tìm mã của mình trong `payload.content` và tự đối soát.

Hiểu đúng bước 1 và 5 là hiểu toàn bộ tích hợp.

---

## Bắt đầu nhanh

```python
import os
from gpmpay import GpmPay, PaymentRequest, build_payment_instructions

with GpmPay(api_token=os.environ["GPMPAY_API_TOKEN"]) as client:
    # Tài khoản nhận tiền — phải lấy kèm quan hệ `bank` (VietQR cần NAPAS BIN).
    account = client.bank_accounts.retrieve("acc_...")

    instructions = build_payment_instructions(
        PaymentRequest(
            bank_account=account,
            amount=250_000,
            transfer_content="SHOP1042",  # mã của BẠN, giữ ngắn và ASCII
        )
    )

print(instructions.qr_payload)  # chuỗi EMVCo — render thành QR
print(instructions.qr_image_url)  # ảnh sẵn dùng từ img.vietqr.io
```

Token là **bí mật phía server**. Đừng bao giờ đưa xuống trình duyệt hay app di
động. Tạo token tại <https://app.gpmpay.com/api-tokens>.

### Bất đồng bộ

Cùng bề mặt API, cùng chữ ký, chỉ thêm `await`:

```python
from gpmpay import AsyncGpmPay

async with AsyncGpmPay(api_token=os.environ["GPMPAY_API_TOKEN"]) as client:
    page = await client.transactions.list(limit=10)
    async for txn in client.transactions.list_all(type="IN"):
        print(txn.reference_code)
```

Cả hai client đều sở hữu một connection pool — dùng `with` / `async with`, hoặc
gọi `close()` / `await aclose()` khi xong.

---

## Nhận webhook

Đăng ký endpoint và lấy secret (**chỉ trả về một lần**):

```python
result = client.webhook_settings.create_hmac_endpoint(
    url="https://shop.example.com/webhooks/gpmpay",
    name="Shop production",
)
print(result.secret)  # lưu ngay, ví dụ vào GPMPAY_WEBHOOK_SECRET
```

### Flask

```python
from flask import Flask
from gpmpay.webhooks import flask_webhook_view

app = Flask(__name__)


def handle(event):
    if event.payload.transfer_type != "in":
        return
    enqueue_fulfilment(event.payload.id, event.payload.content)


app.add_url_rule(
    "/webhooks/gpmpay",
    view_func=flask_webhook_view(
        secret=os.environ["GPMPAY_WEBHOOK_SECRET"], on_event=handle
    ),
    methods=["POST"],
)
```

### FastAPI

```python
from fastapi import FastAPI
from gpmpay.webhooks import create_fastapi_webhook_route

app = FastAPI()


async def handle(event):
    if event.payload.transfer_type != "in":
        return
    await fulfil(event.payload.id, event.payload.content)


app.post("/webhooks/gpmpay")(
    create_fastapi_webhook_route(
        secret=os.environ["GPMPAY_WEBHOOK_SECRET"],
        on_event=handle,
        background=True,  # ack trước, xử lý sau
    )
)
```

### Django

```python
# urls.py
from gpmpay.webhooks import django_webhook_view

urlpatterns = [
    path(
        "webhooks/gpmpay",
        django_webhook_view(
            secret=os.environ["GPMPAY_WEBHOOK_SECRET"], on_event=handle
        ),
    ),
]
```

View đã được bọc `@csrf_exempt` sẵn — GPM Pay không phải trình duyệt và không
mang CSRF token.

### Ba quy tắc không thể bỏ qua

1. **Xác thực chữ ký trên đúng bytes gốc.** Không bao giờ `json.dumps(body_đã_parse)`
   — serialize lại làm đổi khoảng trắng và thứ tự khoá, chữ ký sẽ không bao giờ khớp.
   Ba adapter ở trên đã làm đúng cho bạn.
2. **Handler phải idempotent trên `payload.id`.** GPM Pay retry theo lịch
   `[10s, 30s, 2m, 10m, 1h, 6h]`, tối đa 6 lần. Bạn *sẽ* thấy cùng một giao dịch
   nhiều lần.
3. **Trả lời trong 5 giây.** Quá thời gian này GPM Pay huỷ và ghi nhận thất bại.
   Đẩy việc nặng sang queue rồi trả 200 ngay.

---

## CLI

```bash
gpmpay ping                    # token còn sống không, có những scope nào
gpmpay accounts list           # nơi lấy id cho --account
gpmpay transactions list
gpmpay simulate tx --account <id> --amount 50000 --content SHOP1042
gpmpay webhook listen --secret <s>          # receiver cục bộ, xác thực trực tiếp
gpmpay webhook send --url http://localhost:3000/hook   # ký và POST vào server bạn
gpmpay webhook history --status FAILED
```

> Cả SDK này và SDK Node đều cài một binary tên `gpmpay`. Trên máy có cả hai,
> cái nào đứng trước trong `PATH` sẽ thắng. `python -m gpmpay` là dạng không
> nhập nhằng.

Mã thoát: `0` OK · `1` lỗi · `2` sai cách dùng · `3` lỗi xác thực · `4` lỗi kết nối.

---

## Lỗi

```python
from gpmpay import GpmPayError, GpmPayPermissionError, GpmPayRateLimitError

try:
    page = client.transactions.list()
except GpmPayPermissionError as error:
    if error.reason == "scope":
        print("Token thiếu scope:", error.missing_scope)
except GpmPayRateLimitError as error:
    print("Thử lại sau", error.retry_after, "giây")
except GpmPayError as error:
    print(error.code, error)
```

`GpmPayError` bắt được tất cả. Chi tiết ở
[docs/vi/04-errors-and-testing.md](docs/vi/04-errors-and-testing.md).

---

## Vài điều dễ vấp

- **Tiền là chuỗi.** `Transaction.amount` là `str` (Prisma `Decimal` serialize ra
  chuỗi) và SDK **không bao giờ** tự ép kiểu. Dùng `to_vnd()` khi cần tính toán —
  nó trả `Decimal`, không phải `float`.
- **Mọi tham số thời lượng tính bằng giây.** `timeout=30.0`, không phải
  `timeout_ms=30000`.
- **`limit` bị chặn ở 50** phía server. SDK tự kẹp và cảnh báo một lần.
- **Giữ mã đối soát ở dạng ASCII.** CRC của VietQR tính theo UTF-16 code unit để
  khớp backend; mô tả có dấu tiếng Việt sẽ không khớp CRC mà app ngân hàng tính.

---

## Tài liệu

| | |
|---|---|
| [01 — Bắt đầu](docs/vi/01-getting-started.md) | Tạo token, cài đặt, giao dịch đầu tiên |
| [02 — Thanh toán](docs/vi/02-payments.md) | Chọn mã đối soát, VietQR, tiền tệ |
| [03 — Webhook](docs/vi/03-webhooks.md) | Đăng ký, xác thực, retry, idempotency |
| [04 — Lỗi & kiểm thử](docs/vi/04-errors-and-testing.md) | Cây lỗi, retry, mock httpx |
| [05 — Tham chiếu API](docs/vi/05-api-reference.md) | Mọi tham số, mọi method |
| [examples/](examples/) | Flask, FastAPI, Django chạy được ngay |

---

## Giấy phép

MIT © GPM Softwares
