Starship Rewards API

Authentication

Learn how authentication works in the Starship Rewards API

Authentication Overview

The Starship Rewards API uses JWT (JSON Web Token) based authentication to secure all endpoints for B2B integrations. This section covers the complete authentication flow and how to manage tokens in server-to-server environments.

Authentication Flow for B2B Integration

  1. API Key Setup: Obtain API credentials from your account dashboard
  2. Token Exchange: Exchange API credentials for access and refresh tokens
  3. Server-to-Server Calls: Use the access token in the Authorization header
  4. Automated Refresh: Implement automatic token refresh in your backend services
  5. Token Revocation: Invalidate tokens when rotating credentials

Token Types

Access Token

  • Purpose: Used to authenticate API requests
  • Lifetime: Short-lived (typically 15-30 minutes)
  • Usage: Include in Authorization header as Bearer {token}

Refresh Token

  • Purpose: Used to obtain new access tokens
  • Lifetime: Long-lived (typically 7-30 days)
  • Usage: Send to /auth/refresh endpoint

Headers Required

All protected endpoints require the following header:

Authorization: Bearer {your_access_token}

Error Responses

401 Unauthorized

Token is missing, invalid, or expired:

{
  "error": "Unauthorized",
  "message": "Invalid or expired token"
}

403 Forbidden

Token is valid but lacks required permissions:

{
  "error": "Forbidden",
  "message": "Insufficient permissions"
}

Quick Start for B2B Integration

  1. Authenticate with your API credentials
  2. Extract the access_token from the response
  3. Store tokens securely in your backend infrastructure
  4. Use the token in subsequent server-to-server API calls
  5. Implement automatic token refresh before expiration

Example Implementation

# Step 1: Login and get tokens
curl -X POST {{host}}/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "your-api-email@company.com",
    "password": "your-secure-password"
  }'

# Response:
# {
#   "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
#   "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
#   "expires_in": 1800
# }

# Step 2: Use access token for API calls
curl -X GET {{host}}/api/v1/products \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
  -H "Content-Type: application/json"

# Step 3: Refresh token when needed
curl -X POST {{host}}/auth/refresh \
  -H "Content-Type: application/json" \
  -d '{
    "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
  }'
class StarshipAuth {
    private $accessToken;
    private $refreshToken;
    private $expiresAt;

    public function login($email, $password) {
        $data = json_encode([
            'email' => $email,
            'password' => $password
        ]);

        $context = stream_context_create([
            'http' => [
                'method' => 'POST',
                'header' => 'Content-Type: application/json',
                'content' => $data
            ]
        ]);

        $response = file_get_contents('{{host}}/auth/login', false, $context);
        $tokenData = json_decode($response, true);

        if ($tokenData) {
            $this->accessToken = $tokenData['access_token'];
            $this->refreshToken = $tokenData['refresh_token'];
            $this->expiresAt = time() + $tokenData['expires_in'];

            // Store tokens securely (database, cache, etc.)
            $this->storeTokens();

            return true;
        }

        return false;
    }

    public function makeAuthenticatedRequest($url, $method = 'GET', $data = null) {
        // Check if token needs refresh
        if ($this->shouldRefreshToken()) {
            $this->refreshAccessToken();
        }

        $headers = [
            'Authorization: Bearer ' . $this->accessToken,
            'Content-Type: application/json'
        ];

        $context = [
            'http' => [
                'method' => $method,
                'header' => implode("\r\n", $headers)
            ]
        ];

        if ($data && in_array($method, ['POST', 'PUT', 'PATCH'])) {
            $context['http']['content'] = json_encode($data);
        }

        $response = file_get_contents($url, false, stream_context_create($context));
        return json_decode($response, true);
    }

    private function shouldRefreshToken($bufferMinutes = 5) {
        return (time() + ($bufferMinutes * 60)) >= $this->expiresAt;
    }

    private function refreshAccessToken() {
        $data = json_encode(['refresh_token' => $this->refreshToken]);

        $context = stream_context_create([
            'http' => [
                'method' => 'POST',
                'header' => 'Content-Type: application/json',
                'content' => $data
            ]
        ]);

        $response = file_get_contents('{{host}}/auth/refresh', false, $context);
        $tokenData = json_decode($response, true);

        if ($tokenData) {
            $this->accessToken = $tokenData['access_token'];
            $this->expiresAt = time() + $tokenData['expires_in'];
            $this->storeTokens();
        }
    }

    private function storeTokens() {
        // Store in your preferred secure storage
        // Examples: database, Redis, encrypted file
        $_SESSION['starship_access_token'] = $this->accessToken;
        $_SESSION['starship_refresh_token'] = $this->refreshToken;
        $_SESSION['starship_expires_at'] = $this->expiresAt;
    }
}

// Usage example
$auth = new StarshipAuth();
$auth->login('your-api-email@company.com', 'your-secure-password');

// Make authenticated API calls
$products = $auth->makeAuthenticatedRequest('{{host}}/api/v1/products');
$categories = $auth->makeAuthenticatedRequest('{{host}}/api/v1/categories');

Authentication Endpoints

Advanced Topics

For production applications, see our comprehensive guides on: