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

# Credit balance, WeChat Pay, and Alipay billing

> Profy finance system: credit-based virtual currency, recharge plans, WeChat Pay and Alipay channels, and consumption tracking across tasks and Experts.

# Finance & Payments

Profy uses a **credit-based** virtual currency system for all platform transactions. Users recharge credits through real-money payment channels and consume them for tasks, agent usage, and premium features.

## Overview

```mermaid theme={null}
flowchart LR
    subgraph "Payment Channels"
        WX[WeChat Pay]
        Ali[Alipay]
    end

    subgraph "Recharge"
        Plan[Recharge Plans]
        Order[Recharge Orders]
    end

    subgraph "Credit Account"
        Bal[Balance]
        Consume[Consumption]
    end

    subgraph "Services"
        Task[Task Pay]
        Agent[Agent Credits]
        Premium[Service Plans]
    end

    WX --> Order
    Ali --> Order
    Plan --> Order
    Order -->|"Payment success"| Bal
    Bal --> Consume
    Consume --> Task
    Consume --> Agent
    Consume --> Premium
```

## Credit System

Credits are the universal unit of value on the platform. All billable operations deduct from the user's credit balance.

### Balance API

| Method | Endpoint                | Auth | Description                         |
| ------ | ----------------------- | ---- | ----------------------------------- |
| `GET`  | `/api/finance/balance`  | JWT  | Get current credit balance          |
| `POST` | `/api/finance/consume`  | JWT  | Consume credits for a service       |
| `POST` | `/api/finance/preCheck` | JWT  | Validate balance before consumption |
| `POST` | `/api/finance/records`  | JWT  | Query consumption history           |

### Consumption Types

| Type       | Use Case             | Billing Model       |
| ---------- | -------------------- | ------------------- |
| `TOKEN`    | AI agent token usage | Per-token rate      |
| `DURATION` | Time-based services  | Per-minute rate     |
| `FIXED`    | One-time operations  | Fixed credit amount |

### Idempotent Consumption

Every consumption request includes an idempotency key to prevent duplicate charges. The system checks Redis before processing:

```mermaid theme={null}
sequenceDiagram
    participant C as Caller
    participant F as Finance Service
    participant R as Redis
    participant D as PostgreSQL

    C->>F: POST /consume {idempotencyKey, amount}
    F->>R: Check consume:idem:{key}
    alt Already processed
        R-->>F: Existing result
        F-->>C: Return cached result
    else New request
        F->>D: Deduct balance (atomic)
        F->>R: Store consume:idem:{key}
        F-->>C: Consumption result
    end
```

## Recharge Flow

Users top up their credit balance by purchasing recharge plans through payment channels.

### Recharge API

| Method | Endpoint                                | Auth | Description                   |
| ------ | --------------------------------------- | ---- | ----------------------------- |
| `GET`  | `/api/finance/recharge/plans`           | JWT  | List available recharge plans |
| `GET`  | `/api/finance/recharge/preview`         | JWT  | Preview order before payment  |
| `POST` | `/api/finance/recharge/create`          | JWT  | Create a recharge order       |
| `GET`  | `/api/finance/recharge/status/:orderNo` | JWT  | Check order status            |
| `POST` | `/api/finance/recharge/summary`         | JWT  | Recharge summary statistics   |
| `POST` | `/api/finance/recharge/records`         | JWT  | Recharge history              |

### Recharge Lifecycle

```mermaid theme={null}
stateDiagram-v2
    [*] --> Preview: Select plan
    Preview --> Created: Create order
    Created --> Paying: Payment initiated
    Paying --> Paid: Payment callback
    Paying --> Expired: Timeout
    Paid --> Credited: Credits added to balance
    Credited --> [*]
    Expired --> [*]
```

1. User selects a recharge plan from the catalog
2. System creates a recharge order and a linked payment order
3. Payment channel returns a pay URL (QR code for WeChat Native Pay)
4. User completes payment on the external channel
5. Payment callback arrives at `/api/payment/notify/:channel`
6. System credits the amount to the user's balance

## Payment Channels

### WeChat Pay

Profy integrates with WeChat Pay using the **Native** payment method (QR code scan) via `wechatpay-node-v3`.

| Config Variable          | Description                       |
| ------------------------ | --------------------------------- |
| `WECHAT_PAY_APP_ID`      | WeChat application ID             |
| `WECHAT_PAY_MCH_ID`      | Merchant ID                       |
| `WECHAT_PAY_SERIAL_NO`   | API certificate serial number     |
| `WECHAT_PAY_PRIVATE_KEY` | RSA private key for signing       |
| `WECHAT_PAY_API_V3_KEY`  | APIv3 key for callback decryption |

### Alipay

Alipay integration uses `alipay-sdk` as an alternative payment strategy.

### Payment API

| Method | Endpoint                          | Auth | Description                    |
| ------ | --------------------------------- | ---- | ------------------------------ |
| `POST` | `/api/payment/create`             | JWT  | Create a payment order         |
| `GET`  | `/api/payment/status/:outTradeNo` | JWT  | Query payment status           |
| `POST` | `/api/payment/close/:outTradeNo`  | JWT  | Close an unpaid order          |
| `POST` | `/api/payment/notify/:channel`    | None | Callback from payment provider |

### Payment Callback Flow

```mermaid theme={null}
sequenceDiagram
    participant Pay as Payment Provider
    participant N as Nginx
    participant C as Core API
    participant D as PostgreSQL

    Pay->>N: POST /api/payment/notify/wechat
    N->>C: Forward (whitelisted route)
    C->>C: Verify signature
    C->>D: Update payment order status
    C->>C: rechargeService.onPaymentSuccess
    C->>D: Credit amount to user
    C-->>Pay: 200 OK
```

## Service Plans

Service plans define tiered access levels for platform services (e.g., Expert agent tiers).

| Method | Endpoint                        | Auth | Description                   |
| ------ | ------------------------------- | ---- | ----------------------------- |
| `GET`  | `/api/finance/servicePlan/list` | JWT  | List plans by `?serviceCode=` |

## Consumption Records

Users can view a detailed breakdown of their spending:

| Method | Endpoint                   | Auth | Description                 |
| ------ | -------------------------- | ---- | --------------------------- |
| `POST` | `/api/consumption/summary` | JWT  | Aggregated spending summary |
| `POST` | `/api/consumption/records` | JWT  | Detailed transaction log    |

## OpenAPI Consumption

The AutoExpert agent engine uses API Key authentication to consume credits programmatically:

| Method | Endpoint                   | Auth    | Description                         |
| ------ | -------------------------- | ------- | ----------------------------------- |
| `POST` | `/openapi/credit/consume`  | API Key | Consume credits on behalf of a user |
| `POST` | `/openapi/credit/preCheck` | API Key | Pre-validate consumption            |
| `GET`  | `/openapi/credit/balance`  | API Key | Query balance                       |

## Related Pages

<CardGroup cols={2}>
  <Card title="Authentication" icon="lock" href="/en/documentation/auth">
    JWT and API Key auth for finance endpoints
  </Card>

  <Card title="Task Orchestration" icon="list-check" href="/en/documentation/tasks">
    Tasks consume credits through pay-to-view
  </Card>

  <Card title="Agent Platform" icon="robot" href="/en/documentation/agent">
    AutoExpert uses OpenAPI credit consumption for billing
  </Card>
</CardGroup>
