# Webhook & API Reference

This document describes the webhook handling, payment inquiry, and SDK API used by Antom Payments for WooCommerce.

## Webhook

The plugin receives asynchronous payment notifications from Antom via a webhook endpoint.

### Webhook URL

```
https://your-store.com/?wc-api=antom_payment_notify
```

Configure this URL in your [Antom Merchant Portal](https://dashboard.alipay.com/global-payments/home).

### Notification Handler

The webhook is handled by the `payment_notify_handler()` method in `WC_Gateway_Antom_Common`.

**Flow:**

```
Antom API ──POST──► /?wc-api=antom_payment_notify
                        │
                        ▼
            payment_notify_handler()
                        │
                        ├─► Parse notification payload
                        ├─► Verify RSA-SHA256 signature
                        ├─► Validate payment request ID
                        ├─► Update order status
                        ├─► Return SUCCESS/FAILURE response
                        └─► Log result
```

**Response Format:**

The handler responds with a JSON-encoded result:

```json
{
  "result": {
    "resultCode": "SUCCESS",
    "resultStatus": "S",
    "resultMessage": "success"
  }
}
```

| Field | Possible Values | Description |
|---|---|---|
| `resultCode` | `SUCCESS`, `FAIL` | Processing result |
| `resultStatus` | `S`, `F` | Status code (S = Success, F = Failure) |
| `resultMessage` | Free text | Human-readable message |

### Webhook Security

1. **Signature Verification** — Each webhook payload includes a signature header. The plugin verifies this signature using the configured Antom Public Key via `Antom_Signature_Tool`.
2. **Payment Request ID** — Duplicate payment notifications are prevented by checking the unique payment request ID stored in the database.

## Payment Inquiry

As a fallback mechanism, the plugin can query the payment status directly from the Antom API when webhook notifications are delayed or missed.

### Inquiry Endpoint

```
/?wc-api=antom_inquiry_webhook
```

The inquiry is triggered by the `inquiry_handler()` method in `WC_Gateway_Antom_Common`.

### Inquiry Flow

```
Checkout page loads / AJAX calls inquiry
        │
        ▼
inquiry_handler()
        │
        ├─► Build inquiry request with payment request ID
        ├─► SDK::inquiry_payment()
        │       │
        │       └─► Antom API → payment status
        │
        └─► Update order status based on inquiry result
```

## SDK API

The Antom SDK (`includes/sdk/`) provides the communication layer with the Antom API.

### HTTP Client: `Antom_Alipay_Client`

```php
$client = new Antom_Alipay_Client(
    $gatewayUrl,        // Antom API endpoint
    $merchantPrivateKey, // Merchant's RSA private key
    $alipayPublicKey     // Antom's RSA public key
);

$response = $client->execute($request);
```

- **Constructor Parameters:**
  - `$gatewayUrl` — Antom API base URL
  - `$merchantPrivateKey` — Your RSA private key (PKCS#8)
  - `$alipayPublicKey` — Antom's RSA public key

- **`$client->execute($request)`** — Sends a signed request to the Antom API and returns the parsed response

### Signature Tool: `Antom_Signature_Tool`

Handles RSA-SHA256 signature generation and verification:

- **`sign($httpMethod, $path, $clientId, $reqTime, $reqBody, $merchantPrivateKey)`** — Generates signature for outgoing requests
- **`verify($signValue, $httpMethod, $path, $clientId, $reqTime, $reqBody, $alipayPublicKey)`** — Verifies signature on incoming responses/webhooks

### Request Builders

#### Base Request: `SDK_Antom_Alipay_Request`

```php
$request = new SDK_Antom_Alipay_Request();
$request->set_client_id($clientId);
$request->set_path($apiPath);
$request->set_http_method('POST');
$request->set_key_version(1);
```

#### Online Payment Request: `SDK_Antom_Alipay_Online_Request`

Used for creating payment sessions:

```php
$request = new SDK_Antom_Alipay_Online_Request();
$request->set_client_id($clientId);
$request->set_path('/ams/api/onlinePayment/create');
$request->set_http_method('POST');
$request->set_key_version(1);

// Set order parameters
$request->set_order($orderModel);
$request->set_payment_amount($amountModel);
$request->set_payment_redirect_url($redirectUrl);
$request->set_payment_notify_url($notifyUrl);
```

#### Inquiry Request: `SDK_Antom_Alipay_Inquiry_Request`

Used for payment status inquiry:

```php
$request = new SDK_Antom_Alipay_Inquiry_Request();
$request->set_client_id($clientId);
$request->set_path('/ams/api/inquiry/payment');
$request->set_http_method('POST');
$request->set_key_version(1);

$request->set_payment_request_id($paymentRequestId);
```

### RPC Response Model

Responses are parsed into `Antom_Http_Rpc_Result`:

- **`getRspBody()`** — Response body (decoded JSON)
- **`getRspSign()`** — Response signature value
- **`getRspTime()`** — Response timestamp

## Data Models

### Order Model (`Antom_Order_Model`)

The top-level order model that aggregates all order-related data:

```php
$order = new Antom_Order_Model();
$order->set_order_amount($amountModel);
$order->set_order_buyer($buyerModel);
$order->set_order_env($envModel);
$order->set_payment_method($paymentMethodModel);
$order->set_payment_redirect_url($redirectUrl);
$order->set_payment_notify_url($notifyUrl);
$order->set_payment_request_id($uniqueId);
$order->set_merchant_order_no($orderId);
$order->set_order_settlement_strategy($settlementStrategyModel);
```

### Sub-Models

| Model | Fields | Purpose |
|---|---|---|
| `Antom_Order_Amount_Model` | `currency`, `value` | Payment amount |
| `Antom_Order_Buyer_Model` | `buyer_id`, `buyer_name`, `buyer_phone`, `buyer_register_time` | Customer info |
| `Antom_Order_Env_Model` | `terminal_type`, `os_type`, `device_info` | Environment/device |
| `Antom_Order_Name_Model` | `first_name`, `last_name`, `full_name` | Name handling |
| `Antom_Order_Payment_Method_Model` | `payment_method_type` | Method identifier |
| `Antom_Order_Settlement_Strategy_Model` | `settlement_currency` | Settlement config |
| `Antom_Refund_Model` | `refund_amount`, `refund_reason`, `order_id` | Refund data |

## API Endpoints (Antom)

The plugin communicates with the following Antom API endpoints:

| Endpoint | Purpose |
|---|---|
| `/ams/api/onlinePayment/create` | Create payment session |
| `/ams/api/inquiry/payment` | Inquiry payment status |
| `/ams/api/onlinePayment/refund` | Process refund |

## Utility Functions

### Options Management: `Antom_Payment_Gateways_Options`

Singleton class managing plugin options in the `wp_options` table (prefix: `antom_payment_gateway_`):

```php
// Get an option
$value = Antom_Payment_Gateways_Options::get_instance()->get_option('option_name', $default);

// Set an option
Antom_Payment_Gateways_Options::get_instance()->set_option('option_name', $value);
```

### Payment Request Checker: `Antom_Payment_Request_Checker`

Manages unique payment request IDs to prevent duplicate processing:

```php
// Generate payment request ID for an order
$requestId = antom_generate_payment_request_id($order_id);

// Get order ID from payment request ID
$orderId = antom_get_order_id_by_payment_request_id($payment_request_id);
```

## See Also

- [Architecture Overview](architecture.md) — System architecture
- [Configuration Guide](configuration.md) — Settings and setup
- [Development Guide](development.md) — Build and development