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

# Obtaining Access Token

> Learn how to generate and manage access tokens for Phoenix integration

<Note>
  **Client Credentials Required**

  To use Phoenix payments, you'll need a client ID and client secret. You can request these by:

  * Emailing us at [main@phoenix.market](mailto:main@phoenix.market)
  * Including your company name and intended use case
  * We'll respond within 1 business day with your client credentials and additional integration support
</Note>

## Overview

To integrate Phoenix, you need to obtain an access token through an OAuth-like flow. This token must be retrieved from your backend and passed to the frontend for use in the integration.

## Token Generation

<AccordionGroup>
  <Accordion title="View Backend Code Example">
    ```javascript theme={null}
    const myHeaders = new Headers();
    myHeaders.append("Content-Type", "application/json");

    const raw = JSON.stringify({
      "client_id": "x", // Replace with your client ID from Phoenix team
      "client_secret": "y", // Replace with your client secret from Phoenix team
      "grant_type": "client_credentials" // Always use this value
    });

    const requestOptions = {
      method: "POST",
      headers: myHeaders,
      body: raw,
      redirect: "follow"
    };

    fetch("https://api.phoenix.market/oauth/token", requestOptions)
      .then((response) => response.text())
      .then((result) => console.log(result))
      .catch((error) => console.error(error));
    ```
  </Accordion>
</AccordionGroup>

### Required Parameters

| Parameter       | Description                                        | Example                    |
| --------------- | -------------------------------------------------- | -------------------------- |
| `client_id`     | Your client ID provided by the Phoenix team        | `"2SERtJ2DPnkkTQbvnqyS5y"` |
| `client_secret` | Your client secret provided by the Phoenix team    | `"a1b2c3d4e5..."`          |
| `grant_type`    | The grant type (always use `"client_credentials"`) | `"client_credentials"`     |

### Endpoint

```
https://api.phoenix.market/oauth/token
```

### Response Example

```json theme={null}
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwYXJ0bmVyIjp7ImNsaWVudF9pZCI6IjJTRVJ0SjJEUG5ra1RRYnZucXlTNXkifSwic2NvcGUiOlsiaWZyYW1lIl0sInZlcnNpb24iOiIxIiwiaWF0IjoxNzQ1MzU5MzkxLCJleHAiOjE3NDUzNjI5OTEsImp0aSI6ImY3OWQ4NzkzLTU5NmUtNDZhZi1iODRmLTA4YmRhZmRmNjQzNiJ9.2zYEIjfpV3FiV2HputAUDbbuXH0ylgQtrsjmINxjOHc",
  "token_type": "Bearer",
  "expires_in": 3600,
  "scope": [
    "iframe"
  ]
}
```

## Important Security Considerations

<Note>
  The access token does not need to be generated on a per-user basis. You can use the same access token across all your users. A recommended practice is to set up a cron job that runs every hour to refresh your access\_token and store it on your backend for all your users to share.
</Note>

1. **Store credentials securely**: Your `client_id` and `client_secret` should never be exposed in frontend code.

2. **Token lifespan**: Access tokens are valid for 1 hour (3600 seconds). Set up a cron job on your backend to refresh the token hourly.

3. **Token storage**: Store the current valid access token securely on your backend and provide an API endpoint for your frontend to retrieve it.

4. **Domain whitelisting**: Phoenix will be implementing domain whitelisting and additional security measures in the future. Keep your integration up to date by checking documentation regularly.

## Using the Access Token

Once obtained, the access token should be included in the Phoenix iframe URL:

```
https://app-partner.phoenix.market/?address=${walletAddress}&amount=${amount}&access_token=${accessToken}
```

## Implementation Best Practices

1. **Backend endpoint**: Create a secure endpoint on your backend that retrieves and returns a valid access token to your frontend.

2. **Token caching**: Cache the token on your backend with an expiration slightly shorter than the token's expiration time.

3. **Error handling**: Implement robust error handling for cases where token generation fails.

4. **Automatic refresh**: Set up automatic token refreshing before expiration to prevent disruption to your users.

## Example Backend Service

<AccordionGroup>
  <Accordion title="Node.js Example">
    ```javascript theme={null}
    const express = require('express');
    const axios = require('axios');
    const app = express();

    // Store token in memory (use Redis or another cache in production)
    let tokenCache = {
      token: null,
      expiresAt: 0
    };

    // Endpoint to get a valid token
    app.get('/api/token', async (req, res) => {
      const now = Date.now();
      
      // Return cached token if it's still valid (with 5-minute buffer)
      if (tokenCache.token && tokenCache.expiresAt > now + 300000) {
        return res.json({ access_token: tokenCache.token });
      }
      
      try {
        // Token expired or not present, get a new one
        const response = await axios.post('https://api.phoenix.market/oauth/token', {
          client_id: process.env.PHOENIX_CLIENT_ID,
          client_secret: process.env.PHOENIX_CLIENT_SECRET,
          grant_type: 'client_credentials'
        }, {
          headers: { 'Content-Type': 'application/json' }
        });
        
        // Save new token to cache
        tokenCache.token = response.data.access_token;
        tokenCache.expiresAt = now + (response.data.expires_in * 1000);
        
        return res.json({ access_token: tokenCache.token });
      } catch (error) {
        console.error('Failed to get Phoenix token:', error);
        return res.status(500).json({ error: 'Failed to get access token' });
      }
    });

    app.listen(3000, () => {
      console.log('Server running on port 3000');
    });
    ```
  </Accordion>
</AccordionGroup>
