# SMS Messaging Application - Telstra API

A modern, fully-functional web-based SMS messaging application built with PHP and the Telstra Messaging API. Features a chat-style interface with conversation threading, real-time message polling, and OAuth2 authentication.

## Features

✅ **Send & Receive SMS** - Bidirectional messaging via Telstra API  
✅ **Chat Interface** - Modern conversation threads organized by contact  
✅ **Real-time Updates** - Auto-polling for incoming messages every 5 seconds  
✅ **Responsive Design** - Works perfectly on desktop, tablet, and mobile  
✅ **OAuth2 Integration** - Automatic token management and caching  
✅ **Webhook Support** - Receive incoming SMS via webhook integration  

## Project Structure

```
├── index.php              # Main UI - chat layout and contacts
├── api.php                # Backend API endpoints for frontend
├── TelstraAPI.php         # OAuth2 & Telstra API integration
├── webhook.php            # Webhook endpoint for incoming SMS
├── app.js                 # Frontend interactivity & state management
├── style.css              # Modern, responsive styling
├── messages.json          # Local conversation storage (auto-created)
├── token_cache.json       # OAuth2 token cache (auto-created)
└── webhook_log.json       # Webhook debug log (auto-created)
```

## Setup Instructions

### Prerequisites

- PHP 7.4+ with cURL enabled
- A web server (Apache, Nginx, or PHP's built-in server)
- Telstra Developer Account with API credentials

### Step 1: Install Files

1. Download all files to your web server directory:
   ```bash
   /var/www/html/sms-app/
   ```

2. Ensure the directory is writable (for JSON files):
   ```bash
   chmod 755 /var/www/html/sms-app/
   ```

### Step 2: Verify Telstra API Credentials

The credentials are pre-configured in `TelstraAPI.php`:
- **Client ID**: `YOUR_CLIENT_ID`
- **Client Secret**: `YOUR_CLIENT_SECRET`

### Step 3: Start Your Web Server

**Using PHP Built-in Server** (Development):
```bash
cd /var/www/html/sms-app/
php -S localhost:8000
```

Then open: `http://localhost:8000`

**Using Apache/Nginx**:
Configure your virtual host to point to the directory, then access via your domain.

### Step 4: Test Sending a Message

1. Click the **`+`** button to create a new conversation
2. Enter a phone number (e.g., `+61412345678` or `0412345678`)
3. Type a message and click Send
4. Check your phone for the SMS!

### Step 5: Configure Webhook for Incoming Messages (Optional)

To receive incoming SMS, configure Telstra's webhook to point to your server:

1. Log into your Telstra Developer Account
2. Go to **Messaging API Settings**
3. Set the **Webhook URL** to:
   ```
   https://yourdomain.com/sms-app/webhook.php
   ```
4. Select **POST** as the method
5. Save settings

Incoming messages will now automatically appear in your conversations!

## API Endpoints

### Frontend API (`api.php`)

#### Get All Conversations
```
GET /api.php?action=getConversations
```

Response:
```json
{
  "conversations": [
    {
      "contact": "+61412345678",
      "messages": [
        {
          "id": "msg_123",
          "from": "me",
          "to": "+61412345678",
          "body": "Hello!",
          "timestamp": 1715857200,
          "direction": "sent"
        }
      ]
    }
  ]
}
```

#### Send Message
```
POST /api.php?action=sendMessage
Content-Type: application/json

{
  "to": "+61412345678",
  "message": "Hello there!"
}
```

Response:
```json
{
  "success": true,
  "messageId": "msg_xyz"
}
```

#### Save Conversations
```
POST /api.php?action=saveConversations
Content-Type: application/json

{
  "conversations": [...]
}
```

## Webhook Integration

### Incoming Message Format

When Telstra sends incoming SMS, the webhook expects this payload:

```json
{
  "messages": [
    {
      "from": "+61412345678",
      "to": "+61499999999",
      "body": "Hello from SMS!",
      "timestamp": "2026-05-15T12:34:56Z"
    }
  ]
}
```

The webhook will automatically:
- Parse the incoming message
- Find or create a conversation thread
- Add the message to the thread
- Log the webhook call to `webhook_log.json`

## File Breakdown

### `TelstraAPI.php`
**Handles OAuth2 authentication and API requests**
- `getAccessToken()` - Retrieves and caches OAuth2 tokens
- `sendMessage($to, $message)` - Sends SMS via Telstra API
- `getMessageStatus($messageId)` - Checks message delivery status
- Token caching prevents repeated authentication

### `api.php`
**Backend bridge between frontend and Telstra API**
- Routes frontend requests to appropriate handlers
- Manages local conversation storage
- Validates input and error handling

### `webhook.php`
**Receives and processes incoming SMS**
- Parses incoming webhook payloads
- Organizes messages into conversation threads
- Logs all webhook calls for debugging

### `index.php`
**Main user interface**
- Sidebar with contact list
- Chat message display
- Message input area
- Modal for creating new conversations

### `app.js`
**Frontend interactivity**
- DOM manipulation and event handling
- Fetch API calls to backend
- Auto-refresh polling (5-second intervals)
- Message formatting and validation

### `style.css`
**Modern, responsive styling**
- iOS-like chat design
- Mobile-optimized layout
- Smooth animations
- Dark/light mode ready with CSS variables

## Security Considerations

⚠️ **For Production Use**:
1. **Move API credentials to environment variables** or secure config:
   ```php
   $clientId = getenv('TELSTRA_CLIENT_ID');
   $clientSecret = getenv('TELSTRA_CLIENT_SECRET');
   ```

2. **Restrict file permissions**:
   ```bash
   chmod 600 webhook.php api.php TelstraAPI.php
   ```

3. **Add authentication** to `api.php` and `webhook.php`:
   ```php
   session_start();
   if (!isset($_SESSION['user'])) {
       http_response_code(401);
       exit('Unauthorized');
   }
   ```

4. **Validate webhook signatures** if Telstra provides them

5. **Use HTTPS only** - Never send credentials over HTTP

6. **Rate limiting** - Implement to prevent abuse

## Troubleshooting

### "Failed to get access token"
- Verify Client ID and Secret in `TelstraAPI.php`
- Check your Telstra Developer Account is active
- Ensure cURL is enabled in PHP: `php -m | grep curl`

### "Directory not writable"
- Check permissions: `ls -la`
- Fix: `chmod 755 /var/www/html/sms-app/`

### Messages not sending
- Check webhook logs in `webhook_log.json`
- Verify phone number format (include country code: `+61...`)
- Check Telstra API limits and balance

### Webhook not receiving messages
- Verify webhook URL is publicly accessible
- Check `webhook_log.json` for received requests
- Ensure Telstra Messaging API has webhook enabled

### Messages stuck in "Sending"
- Verify token refresh is working: `token_cache.json` should update
- Check API rate limits
- Restart PHP server: `php -S localhost:8000`

## Testing with Curl

**Send a message manually**:
```bash
curl -X POST http://localhost:8000/api.php?action=sendMessage \
  -H "Content-Type: application/json" \
  -d '{"to": "+61412345678", "message": "Test message"}'
```

**Simulate incoming message**:
```bash
curl -X POST http://localhost:8000/webhook.php \
  -H "Content-Type: application/json" \
  -d '{
    "messages": [{
      "from": "+61412345678",
      "to": "+61499999999",
      "body": "Incoming test",
      "timestamp": "2026-05-15T12:34:56Z"
    }]
  }'
```

## Performance Notes

- **Token Caching**: OAuth2 tokens cached for 1 hour to reduce API calls
- **Message Polling**: 5-second interval keeps UI fresh without overloading
- **Local Storage**: Uses JSON files; scale to database for 10K+ messages
- **Browser Caching**: Static assets (CSS, JS) should be cached

## Next Steps

1. ✅ Deploy to your server
2. ✅ Configure Telstra webhook URL
3. ✅ Test sending/receiving messages
4. ✅ Customize styling in `style.css`
5. ✅ Add database storage for scale
6. ✅ Implement user authentication

## Support & Resources

- **Telstra Messaging API Docs**: https://dev.telstra.com/apis/messaging-api
- **OAuth2 Guide**: https://dev.telstra.com/content/oauth2-authentication
- **Community Repos**: See referenced repositories in the task

---

**Built with ❤️ using PHP, JavaScript, and Telstra Messaging API**
