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

# Refresh Token

> Refresh an expiring Fyatu API access token without re-authenticating. POST /auth/refresh.

## Overview

Refresh an existing JWT token to obtain a new one without re-authenticating with credentials. Tokens can be refreshed up to **5 minutes after expiry**.

## When to Refresh

* Token is about to expire (less than 5 minutes remaining)
* Token just expired (within 5-minute grace period)
* You want to extend an active session

<Note>
  If your token expired more than 5 minutes ago, you must obtain a new token using the [Generate Token](/v3/api-reference/auth/token) endpoint.
</Note>

## Token Refresh Strategy

Implement automatic token refresh in your application:

```javascript theme={null}
class TokenManager {
  constructor(appId, secretKey) {
    this.appId = appId;
    this.secretKey = secretKey;
    this.token = null;
    this.expiresAt = null;
  }

  async getToken() {
    if (!this.token || this.isExpiringSoon()) {
      await this.refreshOrAuthenticate();
    }
    return this.token;
  }

  isExpiringSoon() {
    if (!this.expiresAt) return true;
    const fiveMinutes = 5 * 60 * 1000;
    return (new Date(this.expiresAt) - new Date()) < fiveMinutes;
  }

  async refreshOrAuthenticate() {
    if (this.token && this.canRefresh()) {
      try {
        const res = await fetch('https://api.fyatu.com/api/v3/auth/refresh', {
          method: 'POST',
          headers: { 'Authorization': `Bearer ${this.token}` }
        });
        const data = await res.json();
        if (data.success) {
          this.token = data.data.accessToken;
          this.expiresAt = data.data.expiresAt;
          return;
        }
      } catch (e) { /* Fall through to authenticate */ }
    }
    // Get fresh token
    const res = await fetch('https://api.fyatu.com/api/v3/auth/token', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        appId: this.appId,
        secretKey: this.secretKey,
        grantType: 'client_credentials'
      })
    });
    const data = await res.json();
    if (data.success) {
      this.token = data.data.accessToken;
      this.expiresAt = data.data.expiresAt;
    }
  }
}
```

## Error Codes

| Code                        | Description                                    |
| --------------------------- | ---------------------------------------------- |
| `AUTH_TOKEN_MISSING`        | No Authorization header provided               |
| `AUTH_TOKEN_INVALID`        | Token is malformed                             |
| `AUTH_TOKEN_REFRESH_FAILED` | Token too old (>5 min after expiry) or invalid |

<Tip>
  Refresh tokens proactively before they expire to ensure uninterrupted API access.
</Tip>


## OpenAPI

````yaml v3/openapi.json POST /auth/refresh
openapi: 3.1.0
info:
  title: FYATU API v3
  description: >-
    FYATU API v3 with JWT authentication for Collections, Payouts, and Card
    Issuing.
  version: 3.0.0
  contact:
    name: FYATU Support
    url: https://fyatu.com
    email: support@fyatu.com
servers:
  - url: https://api.fyatu.com/api/v3
    description: Production
security: []
tags:
  - name: Authentication
    description: JWT token management endpoints
  - name: Account
    description: Business account, wallet, and address management
  - name: Collections
    description: Accept payments from customers via checkout sessions
  - name: Refunds
    description: Issue refunds for completed collections
  - name: Payouts
    description: Send money to Fyatu account holders
  - name: Cardholders
    description: Cardholder management for card issuing programs
  - name: Cards
    description: Issue, fund, freeze, and manage virtual cards
  - name: Webhooks
    description: Webhook configuration and management
paths:
  /auth/refresh:
    post:
      tags:
        - Authentication
      summary: Refresh Access Token
      description: >-
        Refresh an existing JWT token to obtain a new one. Tokens can be
        refreshed up to 5 minutes after expiry.
      operationId: refreshToken
      responses:
        '200':
          description: Token refreshed successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TokenResponse'
              example:
                success: true
                status: 200
                message: Token refreshed successfully
                data:
                  accessToken: >-
                    eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJBMUIyQzNENEU1RjZHN0g4IiwiYnVzIjoiTjFTMFczUThQMFYxRTVNNlE0UjNEOFo5IiwidHlwZSI6ImNvbGxlY3Rpb24iLCJzY29wZXMiOlsiY29sbGVjdDp3cml0ZSIsImNvbGxlY3Q6cmVhZCIsInBheW91dDp3cml0ZSIsInBheW91dDpyZWFkIl0sImlhdCI6MTczNjE2MjIwMCwiZXhwIjoxNzM2MjQ4NjAwLCJqdGkiOiJqd3RfMmM0ZjVhOGIxZDNlNjc5MCJ9.pR8mK3nW5vL7qY1tS0xF4gH9jB6eA2cD4uW3iZ9vX1mO
                  tokenType: Bearer
                  expiresIn: 86400
                  expiresAt: '2026-01-07T10:30:00+00:00'
                  appType: collection
                  scopes:
                    - collect:write
                    - collect:read
                    - payout:write
                    - payout:read
                meta:
                  requestId: req_2c4f5a8b1d3e6790
                  timestamp: '2026-01-06T10:30:00+00:00'
        '401':
          description: Token refresh failed
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                success: false
                status: 401
                message: Token refresh failed. Token may be too old or invalid.
                error:
                  code: AUTH_TOKEN_REFRESH_FAILED
                meta:
                  requestId: req_abc123def456
                  timestamp: '2026-01-05T10:30:00+00:00'
      security:
        - BearerAuth: []
components:
  schemas:
    TokenResponse:
      type: object
      properties:
        success:
          type: boolean
          example: true
        status:
          type: integer
          example: 200
        message:
          type: string
          example: Token generated successfully
        data:
          $ref: '#/components/schemas/TokenData'
        meta:
          $ref: '#/components/schemas/Meta'
    ErrorResponse:
      type: object
      properties:
        success:
          type: boolean
          example: false
        status:
          type: integer
          example: 401
        message:
          type: string
          example: Invalid credentials
        error:
          $ref: '#/components/schemas/Error'
        meta:
          $ref: '#/components/schemas/Meta'
    TokenData:
      type: object
      properties:
        accessToken:
          type: string
          description: JWT access token to use in Authorization header
        tokenType:
          type: string
          enum:
            - Bearer
          description: Token type (always Bearer)
        expiresIn:
          type: integer
          description: Token lifetime in seconds
          example: 86400
        expiresAt:
          type: string
          format: date-time
          description: ISO 8601 timestamp when token expires
        appType:
          type: string
          enum:
            - collection
            - issuing
          description: App type determining available APIs
        scopes:
          type: array
          items:
            type: string
          description: Permissions granted to this token
          example:
            - collect:write
            - collect:read
            - payout:write
            - payout:read
    Meta:
      type: object
      properties:
        requestId:
          type: string
          description: Unique request ID for tracking
          example: req_abc123def456
        timestamp:
          type: string
          format: date-time
          description: ISO 8601 timestamp of the response
    Error:
      type: object
      properties:
        code:
          type: string
          description: Error code for programmatic handling
          example: AUTH_INVALID_CREDENTIALS
        details:
          type: array
          items:
            $ref: '#/components/schemas/ValidationError'
          description: Validation error details (for VALIDATION_ERROR)
    ValidationError:
      type: object
      properties:
        field:
          type: string
          description: Field that failed validation
          example: appId
        message:
          type: string
          description: Validation error message
          example: AppId is required
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: JWT access token obtained from /auth/token

````