# X (Twitter) OAuth 2.0 Setup Guide

## ✅ Status Terkini
OAuth 2.0 implementation untuk X publishing telah diupdate dengan credential management yang proper.

## 📋 Kredensial yang Dibutuhkan

### OAuth 2.0 Credentials di `.env`
```env
# API Credentials (dari Twitter Developer Portal)
X_API_KEY=m0HLWW06XT8WJrLNhEjrVwuSu
X_API_SECRET=9JvRI90gpUrH9NF2xkQeBx6RsHxXe4UcHiEIFMQJyjbPP27oKI

# OAuth 2.0 Tokens
X_ACCESS_TOKEN=1885551225606930432-aVcEwGMumCRYKncmvTkdi5fo3lyXEl
X_ACCESS_TOKEN_SECRET=odbegOJLQVuerlkrS9O25zSYGQ0CjLbhoe0GtQ3vrtaGT
X_REFRESH_TOKEN=Nk5QelBZQlNrN2lBQ0pISjdZQWtPWE1JbzFVMGtyc1B6LVdKN29lQUxta1huOjE3ODExODE2MzE0MTY6MToxOnJ0OjE

# Bearer Token (untuk read-only operations)
X_BEARER_TOKEN=AAAAAAAAAAAAAAAAAAAAAPiV7AEAAAAAVoTk1MJOWfpIX2jFxDIOAhl9LJk%3DHoJWT33fcxz0DjYGxmJX8VQjRfgXw1QZCI5mbzFODPAYExgZfr

# OAuth 2.0 Client Credentials (jika menggunakan OAuth 2.0 flow)
X_OAUTH2_CLIENT_ID=SG5wa0NMbkF3LXNfVkp1TLFZNEo6MTpja0
X_OAUTH2_CLIENT_SECRET=GC3YOtrsvTh6dQug9ve19MpYV49V7VNbJh1Ap7Vx6yYv77k_rH
```

## 🔑 Cara Mendapatkan Kredensial

### 1. Get API Key dan Secret
1. Buka https://developer.twitter.com/en/portal/dashboard
2. Pilih project dan app Anda
3. Ke tab "Keys and tokens"
4. Copy **API Key** dan **API Secret Key**

### 2. Generate Access Token dan Refresh Token (OAuth 2.0)
```bash
# Method 1: Menggunakan Twitter Developer Portal (Manual)
1. Buka https://developer.twitter.com/en/portal/dashboard
2. Pergi ke "Keys and tokens" → "OAuth 2.0 Settings"
3. Scroll ke "User Context" section
4. Copy Access Token dan Refresh Token

# Method 2: Programmatic (dengan authentication code)
# Ini memerlukan redirect flow untuk user authorization
```

### 3. Pastikan App Permissions
1. Buka https://developer.twitter.com/en/portal/dashboard
2. Pilih app Anda
3. Ke "User authentication settings"
4. **Pastikan permissions: "Read and Write"** atau lebih tinggi
5. Generate ulang tokens jika perlu

## 🔄 OAuth 2.0 Flow yang Diimplementasikan

### Access Token Refresh
Ketika access token expire, sistem akan:
1. Mendeteksi 401 error dari X API
2. Menggunakan refresh token untuk mendapatkan access token baru
3. Otomatis update `.env` dengan token terbaru
4. Retry request yang gagal

```php
// Di XPublishService::postTweet()
if ($statusCode === 401 && $this->refreshToken) {
    $this->refreshAccessTokenOAuth2();  // Otomatis refresh
    return $this->postTweet($text, $mediaId);  // Retry
}
```

## 📝 Implementasi di Code

### XPublishService Constructor
```php
public function __construct()
{
    $this->bearerToken = config('services.x.bearer_token');
    $this->accessToken = config('services.x.access_token');
    $this->refreshToken = config('services.x.refresh_token');
    $this->apiKey = config('services.x.api_key');
    $this->apiSecret = config('services.x.api_secret');
    
    // Auto-initialize access token dari refresh token jika kosong
    if ($this->refreshToken && empty($this->accessToken)) {
        $this->refreshAccessTokenOAuth2();
    }
}
```

### Posting Tweet
```php
// Menggunakan access token (OAuth 2.0)
$response = $this->client->post($url, [
    'headers' => [
        'Authorization' => "Bearer {$this->accessToken}",
        'Content-Type' => 'application/json',
    ],
    'json' => $payload,
]);
```

### Media Upload (OAuth 1.0a)
```php
// Upload media masih menggunakan OAuth 1.0a (v1.1 endpoint)
// Karena v2 media endpoint memerlukan setup tambahan
$authHeader = $this->generateOAuthHeader('POST', $url, []);
$response = $this->client->post($url, [
    'headers' => ['Authorization' => $authHeader],
    'multipart' => [...],
]);
```

## 🧪 Testing

### Validation Script
Gunakan file test untuk memverifikasi setup:
```bash
php test_x_oauth2_credentials.php
```

Atau dari console:
```php
$xService = app(\App\Services\XPublishService::class);
$status = $xService->validateCredentials();
dd($status);
```

### Manual Tweet Test
```php
$xService = app(\App\Services\XPublishService::class);
$tweetId = $xService->postSimpleTweet('Test tweet from Bokeplah 🎥');
echo "Tweet posted: {$tweetId}";
```

## ⚙️ Config Files

### `config/services.php`
```php
'x' => [
    'bearer_token' => env('X_BEARER_TOKEN'),
    'api_key' => env('X_API_KEY'),
    'api_secret' => env('X_API_SECRET'),
    'access_token' => env('X_ACCESS_TOKEN'),
    'access_token_secret' => env('X_ACCESS_TOKEN_SECRET'),
    'refresh_token' => env('X_REFRESH_TOKEN'),
],
```

## 🐛 Troubleshooting

### Error: "HTTP 401 Unauthorized"
**Penyebab:** Access token invalid atau expired
**Solusi:**
1. Cek apakah refresh token valid
2. Coba refresh manual: `$xService->refreshAccessTokenOAuth2()`
3. Regenerate tokens dari Twitter Developer Portal

### Error: "No valid authentication token available"
**Penyebab:** Tidak ada token di `.env`
**Solusi:**
1. Pastikan X_ACCESS_TOKEN atau X_BEARER_TOKEN ada di `.env`
2. Pastikan credentials lengkap (API Key + Secret)
3. Baca bagian "Cara Mendapatkan Kredensial" di atas

### Error: "Invalid image format"
**Penyebab:** Media tidak berformat image yang valid
**Solusi:**
1. Gunakan JPEG, PNG, GIF, atau WebP
2. Maksimal 5MB
3. Cek apakah file image corrupt

### Error: "App permissions" issue
**Penyebab:** App tidak punya write permission
**Solusi:**
1. Buka Twitter Developer Portal
2. Edit app permissions ke "Read and Write"
3. Regenerate tokens
4. Update `.env` dengan token baru

## 📊 Token Expiration

- **Access Token:** Biasanya 2 jam
- **Refresh Token:** Bisa lebih lama, tergantung konfigurasi
- **Bearer Token:** Tidak ada expiry (static)

Sistem akan otomatis refresh access token ketika expire. Jika refresh token juga expired, Anda perlu generate ulang dari Twitter Developer Portal.

## 🔐 Security Notes

1. **Jangan share credentials** di GitHub atau public places
2. **Gunakan `.env`** untuk storing sensitive data
3. **Rotate tokens** secara regular jika perlu
4. **Monitor logs** untuk error authentication
5. **Jangan hardcode** API credentials di code

## 📚 Resources

- [Twitter API v2 Documentation](https://developer.twitter.com/en/docs/twitter-api)
- [OAuth 2.0 User Context Guide](https://developer.twitter.com/en/docs/authentication/oauth-2-0/user-context-oauth2)
- [Media Upload Endpoint](https://developer.twitter.com/en/docs/twitter-api/v1/media/upload-media/api-reference/post-media-upload)

## ✨ Features Implemented

✅ OAuth 2.0 access token refresh  
✅ Automatic token validation  
✅ Automatic token persistence di .env  
✅ Error handling & retry logic  
✅ Comprehensive logging  
✅ Credential validation methods  
✅ Bearer token fallback  
✅ Media upload support  

---
Last updated: June 12, 2026
