# Create and Monitor Payment Requests

## The Payment Flow

Understanding the complete payment flow helps you integrate Fluxis effectively into your application:

```mermaid
sequenceDiagram
    participant M as Your App
    participant F as Fluxis API
    participant C as Customer
    participant B as Blockchain

    M->>F: Create Payment Request
    F-->>M: Payment Details + NASPIP Token
    M->>C: Display Payment (QR/Link)
    C->>B: Send Payment
    B->>F: Transaction Detected
    F->>M: Webhook: Processing
    B->>F: Transaction Confirmed
    F->>M: Webhook: Completed
    M->>C: Order Confirmed
```

### Flow Breakdown

1. **Your app creates a payment request** via Fluxis API for a specific amount
2. **Fluxis returns payment request details** including a NASPIP token
3. **Customer sees payment request** as a QR code or payment link
4. **Customer pays** using their crypto wallet
5. **Fluxis detects payment** on the blockchain and notifies you
6. **Transaction confirms** and you fulfill the order

## Creating a Payment Request

To create a payment request, you'll need:

<div
  style={{
    padding: "1.5rem",
    border: "1px solid #00e4a4",
    borderRadius: "8px",
    backgroundColor: "rgba(0, 228, 164, 0.05)",
    marginBottom: "2rem",
  }}
>
  <h4 style={{ marginTop: 0, color: "#00e4a4" }}>📋 Required Information</h4>
  <ul style={{ marginBottom: 0 }}>
    <li>
      <strong>Point of Sale ID</strong> - The UUID of your [Point of
      Sale](/docs/key-concepts/point-of-sale)
    </li>
    <li>
      <strong>Amount</strong> - Payment amount as a decimal string (e.g.,
      "49.99")
    </li>
    <li>
      <strong>Unique Asset ID (UAI)</strong> - More information about UAI
      [here](/docs/key-concepts/uai).
    </li>
    <li>
      <strong>Reference ID</strong> - <em>Optional:</em> Your internal order or
      transaction ID
    </li>
  </ul>
</div>

You can create your first payment request in our [API Playground - Payment Request](/api/point-of-sale#create-point-of-sale-payment-request).

Alternatively, use **hosted checkout** (`POST /v1/pos/{posID}/payment-request-checkout`) to receive a `checkout_url` you can redirect customers to without building your own NASPIP UI.

### The NASPIP Token

The NASPIP token is a cryptographically signed string that contains all the payment instructions:

```
naspip;fluxis.us;fluxis.qr.dyn.1;v4.public.IhYyMDI1LTEwLTI...
```

This token can be:

- **Encoded as a QR code** for mobile wallet scanning
- **Shared as a payment link** for web/desktop wallets
- **Shared by NFC enabled wallets** to perform proximity or offline payment

::::tip
**Display Options**

Most merchants display the NASPIP token as a QR code for easy mobile scanning.
Encode the `token` field from the create-payment-request response as a QR image in your app.
::::

### URL-based NASPIP tokens

Some tokens embed a `url` instead of inline payment instructions. Use `POST /v1/naspip/read` with the token — when the payload contains a URL without `payment_options`, Fluxis resolves payment instructions by fetching that URL server-side before returning the decoded data.

## Payment Request States

Payment requests progress through different states during their lifecycle:

### State Transition Diagram

```mermaid
stateDiagram-v2
    [*] --> created: Payment Request Created
    created --> expired: 8 minutes timeout
    created --> processing: Payment Detected
    processing --> completed: Correct Amount
    processing --> underpaid: Amount < Expected
    processing --> overpaid: Amount > Expected
    processing --> failed: Error Occurred

    completed --> [*]
    expired --> [*]
    underpaid --> [*]
    overpaid --> [*]
    failed --> [*]
```

### State Descriptions

| State        | Meaning                                            | What to Do                                      |
| ------------ | -------------------------------------------------- | ----------------------------------------------- |
| `created`    | Awaiting payment (active for ~8 minutes)           | Display to customer, monitor for changes        |
| `processing` | Payment detected, awaiting blockchain confirmation | Continue monitoring, inform customer            |
| `completed`  | Payment received and confirmed                     | Fulfill order, close payment request            |
| `expired`    | Timeout reached without payment                    | Offer to create new payment request             |
| `underpaid`  | Received less than expected amount                 | Contact support for resolution                  |
| `overpaid`   | Received more than expected amount                 | Contact support for resolution                  |
| `failed`     | Unexpected error during processing                 | Contact support, may need to create new request |

::::info
**Edge Cases**

The `underpaid`, `overpaid`, and `failed` states are edge cases that require coordination with Fluxis support for proper handling based on your business requirements.
More about that here: [Payment Flows - Edge Cases](/docs/payment-flows/edge-cases).
::::

## Monitoring Payment Status

After creating a payment request, you need to monitor its status to know when payment is received. There are two approaches:

### Option 1: Polling

Periodically check the payment request status by calling the status endpoint.

**Endpoint:** `GET /v1/pos/{posID}/payment-request/{paymentRequestID}`

Try it in our [API Playground - Get Payment Request](/api/point-of-sale#get-payment-request).

#### Polling Strategy

<div style={{ paddingLeft: "1rem", borderLeft: "3px solid #00e4a4" }}>
  <p>
    <strong>Recommended polling interval:</strong>
  </p>
  <ul>
    <li>First 2 minutes: Poll every 2-3 seconds</li>
    <li>After 2 minutes: Poll every 5 seconds</li>
    <li>
      After expiration: Stop polling or poll every 30 seconds for grace period
    </li>
  </ul>
</div>

**Pros:**

- Simple to implement
- Works with any infrastructure
- No additional setup required

**Cons:**

- Not real-time
- Creates API overhead
- May miss rapid state changes

### Option 2: Webhooks

Configure account-level webhooks to receive notifications when payment status changes. This is the **recommended approach** for production systems.

**Endpoint:** `POST /v1/account/{accountID}/webhook`

Try it in the [API Playground — Create webhook](/api/webhooks#create-webhook).

#### Webhook Setup

Register a full HTTPS URL and set `event_type` to `payment_request`:

```json
{
  "url": "https://your-server.com/webhooks/fluxis",
  "event_type": "payment_request"
}
```

Fluxis generates the signing `secret` and returns it once in the create response. Webhooks fire for `processing`, `completed`, `underpaid`, and `overpaid` — not for `expired` or `failed`.

See [Webhooks guide](/docs/developers/webhooks) and [Webhook Signature Verification](/docs/developers/webhook-signature-verification). After registration, validate your handler with `POST /v1/account/{accountID}/webhook/{webhookID}/test`.

**Pros:**

- Real-time notifications
- No polling overhead
- Efficient and scalable
- Event-driven architecture

**Cons:**

- Requires public endpoint
- Need to implement webhook handler
- Should verify webhook signatures

::::tip Best Practice
Use webhooks for production and polling as a fallback. Implement both methods to ensure you never miss a payment confirmation.
::::

## Handling Different Scenarios

### Scenario 1: Successful Payment

1. Customer scans QR code or clicks payment link
2. Customer confirms payment in their wallet
3. Payment appears on blockchain
4. Status changes to `processing`
5. Transaction receives sufficient confirmations
6. Status changes to `completed`
7. You fulfill the order

**Your action:** Fulfill the order when status is `completed`.

### Scenario 2: Expired Payment Request

1. ~8 minutes pass without payment
2. Status changes to `expired`
3. Payment request is no longer valid

**Your action:** Offer customer option to create a new payment request.

### Scenario 3: Slow Transaction

1. Customer initiates payment near expiration
2. Transaction broadcasts but isn't confirmed before timeout
3. Fluxis grace period processes the late transaction
4. Status updates to `processing` then `completed`

**Your action:** Continue monitoring even after expiration for 2-3 additional minutes.

## Best Practices

### 1. Always Use Reference IDs

<div style={{ paddingLeft: "1rem", borderLeft: "3px solid #00e4a4" }}>
  <p>
    Include your internal order or transaction ID in the{" "}
    <code>reference_id</code> field. This makes reconciliation and debugging
    much easier.
  </p>
</div>

### 2. Display Clear Payment Information

<div style={{ paddingLeft: "1rem", borderLeft: "3px solid #00e4a4" }}>
  <p>Show customers:</p>
  <ul>
    <li>Payment amount in both crypto and fiat</li>
    <li>Time remaining (countdown timer)</li>
    <li>Network being used</li>
    <li>Expected confirmation time</li>
  </ul>
</div>

### 3. Handle Expiration Gracefully

<div style={{ paddingLeft: "1rem", borderLeft: "3px solid #00e4a4" }}>
  <p>
    Don't abandon the customer if a payment expires. Offer a clear option to
    create a new payment request with one click.
  </p>
</div>

### 4. Never Trust Status Alone

<div style={{ paddingLeft: "1rem", borderLeft: "3px solid #00e4a4" }}>
  <p>
    Always verify the <code>amount</code> field matches your expected amount.
    Don't fulfill orders for <code>underpaid</code> or <code>failed</code>{" "}
    payments without coordination.
  </p>
</div>

### 5. Store Payment Request Data

<div style={{ paddingLeft: "1rem", borderLeft: "3px solid #00e4a4" }}>
  <p>Keep a record in your database linking:</p>
  <ul>
    <li>Your order ID</li>
    <li>Fluxis payment request ID</li>
    <li>Creation timestamp</li>
    <li>Current status</li>
    <li>Amount and asset</li>
  </ul>
</div>

## Common Integration Patterns

### E-commerce Checkout Flow

```mermaid
sequenceDiagram
    participant C as Customer
    participant S as Your Store
    participant F as Fluxis

    C->>S: Place Order
    S->>S: Create Order Record
    S->>F: Create Payment Request
    F-->>S: Payment Details
    S->>C: Show Payment QR

    loop Monitor
        C->>F: Send Payment
        F-->>S: Webhook: Processing
        S->>C: Update UI: Processing
        F-->>S: Webhook: Completed
        S->>C: Update UI: Confirmed
    end

    S->>S: Fulfill Order
    S->>C: Send Confirmation Email
```

### Point of Sale Terminal

```mermaid
sequenceDiagram
    participant C as Customer
    participant T as Terminal
    participant F as Fluxis

    T->>T: Cashier Enters Amount
    T->>F: Create Payment Request
    F-->>T: Display QR Code
    C->>F: Customer Scans & Pays

    loop Poll
        T->>F: Check Status
        F-->>T: Status: Processing
        T->>T: Show "Processing"
    end

    F-->>T: Status: Completed
    T->>T: Print Receipt
    T->>C: Transaction Complete
```

## Troubleshooting

### Payment Request Not Creating

**Symptoms:** Error when creating payment request

**Common causes:**

- Invalid or expired access token
- Point of Sale ID doesn't exist or doesn't belong to your organization
- Invalid UAI format
- Amount is zero or negative

**Solution:** Verify your authentication token, Point of Sale ID, and request parameters.

### Status Not Updating

**Symptoms:** Status stuck on `created` despite customer payment

**Common causes:**

- Payment sent to wrong address
- Payment sent with wrong asset/network
- Insufficient network confirmations
- Customer payment pending in wallet

**Solution:** Ask customer to verify transaction hash. Check blockchain explorer to confirm transaction status.

### Webhooks Not Received

**Symptoms:** No webhook notifications arriving

**Common causes:**

- Webhook URL not publicly accessible
- Firewall blocking Fluxis IP addresses
- Webhook endpoint returning errors
- SSL/TLS certificate issues

**Solution:** Call `POST /v1/account/{accountID}/webhook/{webhookID}/test` for a signed sample delivery. Check server logs, verify SSL, and confirm [signature verification](/docs/developers/webhook-signature-verification) passes before processing events.

## Testing Your Integration

Before going live, thoroughly test your integration:

### Test Checklist

- [ ] Create payment request with valid parameters
- [ ] Display NASPIP token as QR code
- [ ] Monitor status changes via polling
- [ ] Handle `completed` status correctly
- [ ] Handle `expired` status gracefully
- [ ] Test webhook delivery and parsing
- [ ] Verify webhook signature using secret from create response
- [ ] Test webhook via `POST /v1/account/{accountID}/webhook/{webhookID}/test`
- [ ] Handle network errors and retries
- [ ] Test edge cases (`underpaid`, `overpaid`)
- [ ] Verify amount precision (decimals)

::::tip
**Testing Environment**

Contact Fluxis support to obtain test API credentials and test network assets for integration testing before going live.
::::
