# OAuth 2.0 API Documentation

This documentation provides a comprehensive guide to integrating with our OAuth 2.0 API.

## Getting Started

### 1. Register Your Application

Before you can use our API, you need to register your application:
1. Go to the [API Client Registration page](/api/register.php)
2. Fill out the registration form with your application details
3. After registration, you'll receive a `client_id` and `client_secret`
4. **Important**: Store your client secret securely as it won't be displayed again

### 2. OAuth 2.0 Authorization Flow

Our API uses the OAuth 2.0 Authorization Code flow, which involves the following steps:

#### Step 1: Authorization Request

Direct your users to our authorization endpoint:

```
GET /api/authorize.php?client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}&response_type=code
```

Parameters:
- `client_id`: Your application's client ID
- `redirect_uri`: Must match the one you registered
- `response_type`: Must be set to "code"

#### Step 2: User Authentication

The user will be prompted to log in (if not already) and grant permission to your application.

#### Step 3: Authorization Code

After authorization, the user will be redirected to your specified redirect URI with an authorization code:

```
{REDIRECT_URI}?code={AUTHORIZATION_CODE}
```

#### Step 4: Token Exchange

Exchange the authorization code for an access token:

```
POST /api/token.php
Content-Type: application/x-www-form-urlencoded

code={AUTHORIZATION_CODE}&client_id={CLIENT_ID}&client_secret={CLIENT_SECRET}
```

Response:
```json
{
  "access_token": "ACCESS_TOKEN",
  "token_type": "Bearer",
  "expires_in": 3600
}
```

#### Step 5: API Requests

Use the access token to make authenticated API requests:

```
GET /api/userinfo.php
Authorization: Bearer ACCESS_TOKEN
```

## Security Considerations

1. **Always use HTTPS** for all API communication
2. Never expose your client secret in client-side code
3. Validate all redirect URIs to prevent open redirects
4. Implement CSRF protection for the authorization flow
5. Do not store access tokens in local storage; use secure HTTP-only cookies
6. Implement token rotation and expiration handling

## Error Handling

API errors are returned with appropriate HTTP status codes and a JSON response:

```json
{
  "error": "error_code",
  "error_description": "Human-readable description"
}
```

Common error codes:
- `invalid_request`: The request is missing required parameters
- `invalid_client`: Client authentication failed
- `invalid_code`: The authorization code is invalid or expired
- `invalid_token`: The access token is invalid or expired

## Example Implementation

### Web Application (PHP)

```php
<?php
// Step 1: Redirect user to authorization endpoint
$authUrl = 'https://example.com/api/authorize.php?client_id=YOUR_CLIENT_ID&redirect_uri=YOUR_REDIRECT_URI&response_type=code';
header("Location: $authUrl");
exit;

// Step 2: Handle the authorization code (on your redirect URI page)
if (isset($_GET['code'])) {
    $code = $_GET['code'];
    
    // Step 3: Exchange the code for an access token
    $ch = curl_init('https://example.com/api/token.php');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
        'code' => $code,
        'client_id' => 'YOUR_CLIENT_ID',
        'client_secret' => 'YOUR_CLIENT_SECRET'
    ]));
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    $tokenData = json_decode($response, true);
    $accessToken = $tokenData['access_token'];
    
    // Step 4: Use the access token to make API requests
    $ch = curl_init('https://example.com/api/userinfo.php');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $accessToken
    ]);
    
    $userData = curl_exec($ch);
    curl_close($ch);
    
    // Process user data
    $user = json_decode($userData, true);
    echo "Hello, " . $user['username'];
}
?>
```

### JavaScript (using fetch API)

```javascript
// Step 1: Redirect user to authorization endpoint
function authorize() {
    const authUrl = 'https://example.com/api/authorize.php?' + 
        new URLSearchParams({
            client_id: 'YOUR_CLIENT_ID',
            redirect_uri: 'YOUR_REDIRECT_URI',
            response_type: 'code'
        });
    
    window.location.href = authUrl;
}

// Step 2: Handle the authorization code (on your redirect URI page)
async function handleRedirect() {
    const urlParams = new URLSearchParams(window.location.search);
    const code = urlParams.get('code');
    
    if (code) {
        // Step 3: Exchange the code for an access token (via your backend)
        const tokenResponse = await fetch('/your-backend-endpoint', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ code })
        });
        
        const tokenData = await tokenResponse.json();
        const accessToken = tokenData.access_token;
        
        // Step 4: Use the access token to make API requests
        const userResponse = await fetch('https://example.com/api/userinfo.php', {
            headers: {
                'Authorization': `Bearer ${accessToken}`
            }
        });
        
        const userData = await userResponse.json();
        console.log('User data:', userData);
    }
}
```

## Rate Limiting

Our API implements rate limiting to ensure service availability for all users:

- 60 requests per minute for most endpoints
- 5 requests per minute for token generation endpoints

When rate limits are exceeded, the API will return a `429 Too Many Requests` status code with headers indicating the rate limit and when you can retry.

## Webhook Integration

You can register webhook URLs to receive notifications about specific events:

1. Register a webhook URL in your application settings
2. Subscribe to specific event types
3. We'll POST event data to your webhook URL in real-time

## Best Practices

1. Implement proper error handling for all API calls
2. Add retry logic with exponential backoff for transient errors
3. Cache frequently accessed data to minimize API calls
4. Validate all user input before sending it to the API
5. Keep your client libraries and SDK up to date

## Getting Help

If you encounter issues or have questions, please:

1. Check the [API Reference](/api/reference)
2. Visit our [Developer Community Forum](https://forum.example.com)
3. Contact our [Developer Support Team](mailto:api-support@example.com)

---

Thank you for integrating with our API! We're excited to see what you build.