# Authentication

Every request to the eCommunicate API requires a **Developer API key** in the `Authorization` header.

## How it works

The API uses a custom `apiKey` scheme. Pass your key directly in the `Authorization` header — no `Bearer` prefix, no Basic auth.

cURL
```bash
curl -X GET "https://api.payless4messaging.com/your-endpoint" \
  -H "Authorization: a1b2c3d4-e5f6-7890-abcd-ef1234567890"
```

Node.js
```javascript
const API_KEY = process.env.ECOMM_API_KEY;

const response = await fetch('https://api.payless4messaging.com/your-endpoint', {
  headers: { 'Authorization': API_KEY },
});
```

Python
```python
import os
import requests

API_KEY = os.environ["ECOMM_API_KEY"]

response = requests.get(
    "https://api.payless4messaging.com/your-endpoint",
    headers={"Authorization": API_KEY},
)
```

Java
```java
String API_KEY = System.getenv("ECOMM_API_KEY");

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.payless4messaging.com/your-endpoint"))
    .header("Authorization", API_KEY)
    .GET()
    .build();
```

## API key format

Your API key is a standard UUID:

```
a1b2c3d4-e5f6-7890-abcd-ef1234567890
```

## Retrieve your API key

Use this endpoint to obtain your API key using your account credentials. **No existing API key is required** — this is the recommended starting point for new integrations.

```
POST /payless4messaging-service/WhatsApp/authenticate/retrieveApiKey
```

**Request body:**

```json
{
  "email": "user@example.com",
  "password": "your-password",
  "clientRef": "CLIENT001"
}
```

**Response:**

```json
{
  "apiKey": "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
}
```

cURL
```bash
curl -X POST "https://api.payless4messaging.com/payless4messaging-service/WhatsApp/authenticate/retrieveApiKey" \
  -H "Content-Type: application/json" \
  -d '{"email": "user@example.com", "password": "your-password", "clientRef": "CLIENT001"}'
```

Node.js
```javascript
const response = await fetch(
  'https://api.payless4messaging.com/payless4messaging-service/WhatsApp/authenticate/retrieveApiKey',
  {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      email: 'user@example.com',
      password: 'your-password',
      clientRef: 'CLIENT001',
    }),
  }
);

const { apiKey } = await response.json();
console.log('Your API key:', apiKey);
```

Python
```python
import requests

response = requests.post(
    "https://api.payless4messaging.com/payless4messaging-service/WhatsApp/authenticate/retrieveApiKey",
    json={
        "email": "user@example.com",
        "password": "your-password",
        "clientRef": "CLIENT001",
    },
)

api_key = response.json()["apiKey"]
print("Your API key:", api_key)
```

Error response
If the credentials are invalid, the endpoint returns `401` with `{"error": "Invalid credentials"}`. Double-check your email, password, and client reference.

## Generate a new key

```
POST /payless4messaging-service/WhatsApp/SystemUsers/generateAPIKey
```

**Response:**

```json
{
  "token": "f6e5d4c3-b2a1-0987-6543-210fedcba987"
}
```

Immediate invalidation
Generating a new key **immediately invalidates** the previous one. All integrations using the old key will return `401 Unauthorized`. Update all your services before or immediately after regeneration.

## Error responses

| Status | Message | Cause | Resolution |
|  --- | --- | --- | --- |
| `401` | `Unauthorized user` | Missing or invalid API key | Check that the `Authorization` header is present and the key is correct |
| `403` | `Forbidden` | Valid key but insufficient permissions | Contact support to verify your account permissions |


## Security best practices

Protect your API key
Your API key grants full access to your eCommunicate account. Treat it like a password.

### Store keys securely

Never hardcode your API key. Use environment variables or a secrets manager:

Environment variable
```bash
# .env (never commit this file)
ECOMM_API_KEY=a1b2c3d4-e5f6-7890-abcd-ef1234567890

# Access in your code
# Node.js: process.env.ECOMM_API_KEY
# Python:  os.environ["ECOMM_API_KEY"]
# Java:    System.getenv("ECOMM_API_KEY")
```

AWS Secrets Manager
```javascript
import { SecretsManagerClient, GetSecretValueCommand } from '@aws-sdk/client-secrets-manager';

const client = new SecretsManagerClient({ region: 'af-south-1' });
const { SecretString } = await client.send(
  new GetSecretValueCommand({ SecretId: 'ecomm/api-key' })
);
const API_KEY = JSON.parse(SecretString).ECOMM_API_KEY;
```

### Key rules

| Rule | Detail |
|  --- | --- |
| **Server-side only** | Make API calls from your backend, never from browsers or mobile apps |
| **HTTPS always** | All eCommunicate endpoints require HTTPS — never downgrade to HTTP |
| **Rotate periodically** | Use the generate endpoint to rotate keys on a regular schedule |
| **Separate environments** | Use different keys for staging and production where possible |
| **Monitor usage** | Check your Analytics dashboard for unexpected activity |
| **Restrict access** | Use the User Management endpoints to control who can access your account |
| **Never log keys** | Ensure your logging framework redacts the `Authorization` header |