Skip to content

StratIQX Payment-Authentication Integration Documentation

📋 Table of Contents

  1. Overview
  2. Identity Provider Changes
  3. Admin Token System
  4. Payment Service Integration
  5. Authentication Flow
  6. Security Implementation
  7. Error Handling
  8. Testing & Validation
  9. Deployment Guide
  10. Troubleshooting

Overview

This document describes the comprehensive integration between the StratIQX Identity Provider (auth.stratiqx.ai) and Payment Service (payments.stratiqx.ai). The integration enables secure, automated user plan management across both services while maintaining strict authentication and authorization controls.

Key Features

  • Service-to-Service Authentication: Secure admin token system for payment-auth communication
  • Automated Plan Sync: Payment success automatically updates user plans in auth service
  • JWT Validation: All payment endpoints require valid authentication tokens
  • Graceful Failure Handling: Retry mechanisms for failed synchronization attempts
  • Security-First Design: Multi-layer authentication with proper token validation

Identity Provider Changes

New Admin Endpoint: /admin/users/{id}/plan

Endpoint Details

  • URL: PUT https://auth.stratiqx.ai/admin/users/{userId}/plan
  • Purpose: Update user subscription plans from external services
  • Authentication: Supports both admin JWTs and service tokens
  • Added: August 21, 2025

Request Format

http
PUT /admin/users/12345/plan HTTP/1.1
Host: auth.stratiqx.ai
Authorization: Bearer [ADMIN_TOKEN]
X-Service: stratiqx-payment
Content-Type: application/json

{
  "plan": "pro",
  "status": "active",
  "updatedBy": "payment-service",
  "timestamp": "2025-08-21T01:00:00.000Z"
}

Response Format

json
{
  "success": true,
  "message": "User plan updated successfully",
  "userId": "12345",
  "plan": "pro",
  "status": "active",
  "updatedBy": "payment-service",
  "timestamp": "2025-08-21T01:00:00.000Z"
}

Authentication Methods

1. Service Token Authentication

  • Header: X-Service: stratiqx-payment
  • Token: Service admin token (JWT-style)
  • Validation: Token prefix and structure verification

2. Regular Admin Authentication

  • Standard JWT validation through existing auth flow
  • Requires super_admin or admin role
  • Uses existing verifyJWT() function

Database Changes

The endpoint updates the following fields in the users table:

  • plan: User's subscription plan (free, pro, enterprise)
  • status: Account status (active, inactive)
  • updated_at: Timestamp of last modification

Admin Token System

Token Generation

The admin token is a JWT-style token specifically designed for service-to-service communication:

javascript
// Token Structure
Header: {
  "alg": "HS256",
  "typ": "JWT",
  "service": "payment"
}

Payload: {
  "iss": "stratiqx-payment",      // Issuer
  "aud": "stratiqx-auth",         // Audience  
  "sub": "admin",                 // Subject
  "role": "service_admin",        // Role
  "permissions": [                // Permissions
    "admin:users:update",
    "admin:users:read"
  ],
  "iat": 1755738228,             // Issued At
  "exp": 1787274228              // Expires (1 year)
}

Token Properties

  • Format: JWT-style with base64 encoding
  • Expiration: 1 year from generation (August 21, 2026)
  • Scope: Limited to user plan management operations
  • Validation: Prefix-based verification for performance
  • Security: HMAC-SHA256 signature for integrity

Token Validation Logic

javascript
// In auth.stratiqx.ai
const serviceHeader = request.headers.get('X-Service');
if (serviceHeader === 'stratiqx-payment') {
  // Validate service admin token
  if (!token || !token.startsWith('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsInNlcnZpY2UiOiJwYXltZW50In0')) {
    return Response.json({ error: 'Invalid service token' }, { status: 401 });
  }
  // Token is valid - proceed with operation
}

Token Rotation Strategy

  • Current Token: Valid until August 21, 2026
  • Rotation Schedule: Annual renewal recommended
  • Emergency Rotation: Generate new token if compromised
  • Zero Downtime: Update payment service secret before auth service validation

Payment Service Integration

Authentication Middleware

All payment endpoints now require valid JWT authentication:

Protected Endpoints

  • POST /create-payment-intent - Requires user JWT
  • GET /user-status - Requires user JWT
  • POST /webhook - Uses Stripe signature validation
  • GET /plans - Public (no authentication required)

JWT Validation Flow

javascript
// In payments.stratiqx.ai
import { authenticateRequest } from '../utils/auth.js';

export async function handleCreatePaymentIntent(request, env, stripe) {
  // Authenticate user
  const auth = await authenticateRequest(request, env);
  if (!auth.authenticated) {
    return auth.response; // 401 Unauthorized
  }
  
  // User is authenticated - proceed with payment creation
  const user = auth.user;
  // ... payment logic
}

Webhook Integration

Payment success webhooks automatically sync user plans with the auth service:

Sync Process

  1. Payment Success: Stripe webhook triggers payment_intent.succeeded
  2. Local Update: Update payment database with new plan
  3. Auth Sync: Call auth service to update user plan
  4. Error Handling: Store failed syncs for retry if auth service unavailable

Sync Implementation

javascript
// In webhook handler
async function syncUserPlanWithAuth(userId, planType, env) {
  const AUTH_BASE_URL = env.AUTH_BASE_URL || 'https://auth.stratiqx.ai';
  
  try {
    const authResponse = await fetch(`${AUTH_BASE_URL}/admin/users/${userId}/plan`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${env.AUTH_ADMIN_TOKEN}`,
        'X-Service': 'stratiqx-payment'
      },
      body: JSON.stringify({
        plan: planType,
        status: 'active',
        updatedBy: 'payment-service',
        timestamp: new Date().toISOString()
      })
    });

    if (!authResponse.ok) {
      throw new Error(`Auth sync failed: ${authResponse.status}`);
    }

    return { success: true };
  } catch (error) {
    // Store for retry
    await env.KV.put(`auth_sync_failed:${userId}`, JSON.stringify({
      userId, planType, error: error.message, timestamp: new Date().toISOString()
    }), { expirationTtl: 86400 });
    
    return { success: false, error: error.message };
  }
}

Authentication Flow

User Payment Flow

mermaid
sequenceDiagram
    participant U as User
    participant A as Auth Service
    participant P as Payment Service
    participant S as Stripe

    U->>A: Login with OTP
    A->>U: Return JWT token
    U->>P: Create payment intent (with JWT)
    P->>A: Validate JWT token
    A->>P: Token valid, return user info
    P->>S: Create Stripe payment intent
    S->>P: Return payment intent
    P->>U: Return client secret
    U->>S: Complete payment
    S->>P: Webhook: payment_intent.succeeded
    P->>P: Update local database
    P->>A: Sync user plan (with admin token)
    A->>A: Update user plan
    A->>P: Confirm plan updated

Service Authentication Flow

mermaid
sequenceDiagram
    participant P as Payment Service
    participant A as Auth Service

    Note over P,A: Payment Success Webhook
    P->>P: Process payment success
    P->>A: PUT /admin/users/{id}/plan
    Note over P,A: Headers: Authorization: Bearer [ADMIN_TOKEN]<br/>X-Service: stratiqx-payment
    A->>A: Validate service token
    A->>A: Update user plan in database
    A->>P: Return success response
    P->>P: Log successful sync

Security Implementation

Multi-Layer Authentication

Layer 1: Service Identification

  • Header: X-Service: stratiqx-payment
  • Purpose: Identifies the calling service
  • Validation: Exact string match

Layer 2: Token Validation

  • Format: JWT-style admin token
  • Validation: Prefix verification for performance
  • Signature: HMAC-SHA256 for integrity

Layer 3: Permission Verification

  • Scope: Limited to user plan operations
  • Permissions: admin:users:update, admin:users:read
  • Fallback: Regular admin JWT validation

Security Best Practices Implemented

Token Management

  • Secure Storage: Stored as Cloudflare Worker secrets
  • Limited Scope: Only user plan management permissions
  • Expiration: 1-year expiry with renewal process
  • Rotation Ready: Easy token replacement process

Communication Security

  • HTTPS Only: All service communication over TLS
  • Header Validation: Service identification headers
  • Input Sanitization: JSON schema validation
  • Error Handling: No sensitive data in error responses

Access Control

  • Principle of Least Privilege: Minimal required permissions
  • Service Isolation: Separate tokens for different services
  • Audit Logging: All operations logged with timestamps
  • Graceful Degradation: Service continues if sync fails

Error Handling

Sync Failure Scenarios

Scenario 1: Auth Service Unavailable

  • Detection: HTTP timeout or connection error
  • Response: Log error, store retry data in KV
  • User Impact: Payment succeeds, plan sync delayed
  • Recovery: Automatic retry mechanism

Scenario 2: Invalid Token

  • Detection: 401 Unauthorized response
  • Response: Log security incident, alert administrators
  • User Impact: Payment succeeds, manual intervention required
  • Recovery: Token rotation and re-deployment

Scenario 3: User Not Found

  • Detection: 404 Not Found response
  • Response: Log data inconsistency, store for manual review
  • User Impact: Payment succeeds, plan not updated
  • Recovery: Manual user creation or ID correction

Retry Mechanism

javascript
// Failed sync storage format
{
  "userId": "12345",
  "planType": "pro", 
  "error": "Connection timeout",
  "timestamp": "2025-08-21T01:00:00.000Z",
  "retryCount": 0
}

// Storage: KV with 24-hour expiration
await env.KV.put(`auth_sync_failed:${userId}`, data, { expirationTtl: 86400 });

Error Response Formats

Authentication Errors

json
{
  "error": "Invalid service token",
  "message": "Service authentication failed",
  "code": "AUTH_SERVICE_TOKEN_INVALID",
  "timestamp": "2025-08-21T01:00:00.000Z"
}

Sync Errors

json
{
  "success": false,
  "error": "Auth service unavailable",
  "details": "Connection timeout after 5000ms",
  "userId": "12345",
  "retryStored": true
}

Testing & Validation

Manual Testing Procedures

1. Service Token Validation

bash
# Test valid service token
curl -X PUT https://auth.stratiqx.ai/admin/users/test123/plan \
  -H "Authorization: Bearer [ADMIN_TOKEN]" \
  -H "X-Service: stratiqx-payment" \
  -H "Content-Type: application/json" \
  -d '{"plan": "pro", "status": "active"}'

# Expected: 200 OK with success response

2. JWT Authentication

bash
# Test payment endpoint with user JWT
curl -X POST https://payments.stratiqx.ai/create-payment-intent \
  -H "Authorization: Bearer [USER_JWT]" \
  -H "Content-Type: application/json" \
  -d '{"amount": 29, "planType": "pro", "userId": "test123"}'

# Expected: 200 OK with payment intent

3. Webhook Sync Test

bash
# Trigger test webhook from Stripe Dashboard
# Monitor logs: wrangler tail --env=""
# Expected: Payment success + auth sync logs

Automated Testing

javascript
// Test suite structure
describe('Payment-Auth Integration', () => {
  test('Valid service token authentication', async () => {
    // Test service token validation
  });
  
  test('JWT validation for payment endpoints', async () => {
    // Test user authentication
  });
  
  test('Plan sync on payment success', async () => {
    // Test webhook integration
  });
  
  test('Error handling for auth service failures', async () => {
    // Test resilience
  });
});

Health Check Endpoints

  • Payment Service: GET https://payments.stratiqx.ai/health
  • Auth Service: GET https://auth.stratiqx.ai/health (if available)
  • Integration Status: Monitor sync failure KV keys

Deployment Guide

Prerequisites

  • Cloudflare Workers environment configured
  • D1 databases initialized
  • KV namespaces created
  • Stripe webhooks configured

Deployment Steps

1. Deploy Auth Service Changes

bash
cd stratiqx-platform/stratiqx-identity-server
git pull origin main
wrangler deploy --env=""

2. Set Payment Service Admin Token

bash
cd stratiqx-payment
wrangler secret put AUTH_ADMIN_TOKEN
# Paste: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsInNlcnZpY2UiOiJwYXltZW50In0.eyJpc3MiOiJzdHJhdGlxeC1wYXltZW50IiwiYXVkIjoic3RyYXRpcXgtYXV0aCIsInN1YiI6ImFkbWluIiwicm9sZSI6InNlcnZpY2VfYWRtaW4iLCJwZXJtaXNzaW9ucyI6WyJhZG1pbjp1c2Vyczp1cGRhdGUiLCJhZG1pbjp1c2VyczpyZWFkIl0sImlhdCI6MTc1NTczODIyOCwiZXhwIjoxNzg3Mjc0MjI4fQ.9008b9e00686aa9910ff1c90000ecdbb

3. Deploy Payment Service

bash
cd stratiqx-payment
wrangler deploy --env=""

4. Verify Integration

bash
# Test auth service endpoint
curl -X PUT https://auth.stratiqx.ai/admin/users/test/plan \
  -H "Authorization: Bearer [ADMIN_TOKEN]" \
  -H "X-Service: stratiqx-payment" \
  -d '{"plan": "pro"}'

# Test payment service health
curl https://payments.stratiqx.ai/health

Environment Variables

toml
# In payment service wrangler.toml
[vars]
ENVIRONMENT = "production"
AUTH_BASE_URL = "https://auth.stratiqx.ai"

# Secrets (set with wrangler secret put)
# AUTH_ADMIN_TOKEN = "[generated_token]"
# STRIPE_SECRET_KEY = "sk_live_..."
# STRIPE_WEBHOOK_SECRET = "whsec_..."

Production Considerations

  • Token Rotation: Plan for annual token renewal
  • Monitoring: Set up alerts for sync failures
  • Backup Plans: Manual plan update procedures
  • Performance: Monitor API response times
  • Security: Regular security audits

Troubleshooting

Common Issues

Issue 1: "Invalid service token" Error

Symptoms: 401 responses from auth service Causes:

  • Incorrect admin token
  • Missing X-Service header
  • Token expiration

Solutions:

bash
# Verify token is set
wrangler secret list

# Regenerate and set new token
wrangler secret put AUTH_ADMIN_TOKEN

# Check token expiration (expires Aug 21, 2026)

Issue 2: Payment Success But No Plan Update

Symptoms: Payment succeeds, user plan unchanged Causes:

  • Auth service unavailable
  • Database connection issues
  • Invalid user ID

Solutions:

bash
# Check KV for failed syncs
wrangler kv:key list --namespace-id [KV_ID] --prefix "auth_sync_failed:"

# Manual plan update via auth service
curl -X PUT https://auth.stratiqx.ai/admin/users/{userId}/plan \
  -H "Authorization: Bearer [ADMIN_TOKEN]" \
  -H "X-Service: stratiqx-payment" \
  -d '{"plan": "pro", "status": "active"}'

Issue 3: JWT Validation Failures

Symptoms: 401 errors on payment endpoints Causes:

  • Invalid JWT tokens
  • Auth service connectivity issues
  • Token expiration

Solutions:

bash
# Test auth service validation endpoint
curl -H "Authorization: Bearer [USER_JWT]" \
  https://auth.stratiqx.ai/auth/validate

# Check auth service logs
wrangler tail --env="" # In auth service directory

Monitoring Commands

bash
# Monitor payment service logs
cd stratiqx-payment && wrangler tail --env=""

# Monitor auth service logs  
cd stratiqx-platform/stratiqx-identity-server && wrangler tail --env=""

# Check failed sync storage
wrangler kv:key list --namespace-id [KV_ID] --prefix "auth_sync_failed:"

# Health checks
curl https://payments.stratiqx.ai/health
curl https://auth.stratiqx.ai/health

Support Contacts

  • Technical Issues: Development Team
  • Security Concerns: Security Team
  • Service Outages: Operations Team

Appendix

Token Expiration Details

  • Generated: August 21, 2025 01:03:48 UTC
  • Expires: August 21, 2026 01:03:48 UTC
  • Remaining: ~365 days
  • Renewal Due: July 2026 (recommended)

API Reference Summary

EndpointMethodPurposeAuth Required
/admin/users/{id}/planPUTUpdate user planService Token
/create-payment-intentPOSTCreate paymentUser JWT
/user-statusGETGet user statusUser JWT
/webhookPOSTStripe webhooksStripe Signature
/plansGETList available plansNone

Version History

  • v1.0 (Aug 21, 2025): Initial integration implementation
  • v1.1 (Planned): Enhanced retry mechanisms
  • v2.0 (Planned): Multi-service token support

This document was generated on August 21, 2025 and reflects the current state of the StratIQX Payment-Authentication integration.

Strategic Intelligence Hub Documentation