Skip to main content

Service Registration Process

Before your application can send notifications through ATP, you must register your service with the ATP server. This one-time process establishes your service identity, configures response handling, and sets up security credentials.

Understanding Service Registration

Service registration serves several critical purposes:
  1. Service Identity - Establishes a unique identity for your service
  2. Response Handling - Configures how you’ll receive user responses
  3. Security - Sets up authentication and verification mechanisms
  4. User Experience - Provides details about your service to display to users
Once registered, your service will receive a unique service_id that’s used for all future interactions with the ATP system.

Registration Requirements

Before registering, make sure you have:
  1. A publicly accessible webhook endpoint to receive responses
  2. A service name and description that clearly identifies your service
  3. An icon URL for visual identification (optional but recommended)
  4. A webhook secret for verifying incoming webhooks

Creating Your Webhook Endpoint

Your webhook endpoint must:
  1. Be publicly accessible (HTTPS required for production)
  2. Respond with a 200 OK status within 5 seconds
  3. Handle POST requests with a JSON payload
  4. Verify webhook signatures for security
Here’s a simple example of a webhook endpoint:
# Python (Flask) example
from flask import Flask, request, jsonify
import hmac
import hashlib

app = Flask(__name__)

@app.route('/atp/webhook', methods=['POST'])
def atp_webhook():
    # Get the request data and signature
    payload = request.json
    signature = request.headers.get('X-ATP-Signature')
    
    # Verify signature (important for security!)
    webhook_secret = "your_webhook_secret"
    computed_signature = hmac.new(
        webhook_secret.encode(),
        request.data,
        hashlib.sha256
    ).hexdigest()
    
    if not hmac.compare_digest(signature, computed_signature):
        return jsonify({"error": "Invalid signature"}), 401
    
    # Process the notification response
    notification_id = payload.get('notification_id')
    action_id = payload.get('action_id')
    response_data = payload.get('response_data')
    
    # Your business logic to handle the response
    process_response(notification_id, action_id, response_data)
    
    return jsonify({"status": "success"}), 200
// Node.js (Express) example
const express = require('express');
const crypto = require('crypto');
const app = express();

app.use(express.json());

app.post('/atp/webhook', (req, res) => {
  // Get the request data and signature
  const payload = req.body;
  const signature = req.headers['x-atp-signature'];
  
  // Verify signature
  const webhookSecret = 'your_webhook_secret';
  const computedSignature = crypto
    .createHmac('sha256', webhookSecret)
    .update(JSON.stringify(req.body))
    .digest('hex');
  
  if (crypto.timingSafeEqual(
    Buffer.from(signature), 
    Buffer.from(computedSignature)
  ) === false) {
    return res.status(401).json({ error: 'Invalid signature' });
  }
  
  // Process the notification response
  const { notification_id, action_id, response_data } = payload;
  
  // Your business logic to handle the response
  processResponse(notification_id, action_id, response_data);
  
  return res.status(200).json({ status: 'success' });
});
For development and testing, you can use tools like ngrok or localtunnel to expose your local webhook endpoint to the internet.

Registering Your Service

Once your webhook endpoint is ready, you can register your service using your ATP client:

Python

from atp import ATPClient

client = ATPClient(api_key="sk_live_your_key_here")

registration_result = client.register_service({
    "name": "My AI Assistant",
    "description": "AI assistant that helps with data analysis and visualization",
    "icon_url": "https://your-service.com/icon.png",
    "webhook_url": "https://your-service.com/atp/webhook",
    "webhook_secret": "your_webhook_secret"  # For verifying webhook signatures
})

# Save this ID securely - you'll need it for configuration
service_id = registration_result["service_id"]
print(f"Service registered with ID: {service_id}")

JavaScript/Node.js

import { ATPClient } from '@atp/client';

const client = new ATPClient({
  apiKey: 'sk_live_your_key_here'
});

async function registerService() {
  try {
    const registration = await client.registerService({
      name: 'My AI Assistant',
      description: 'AI assistant that helps with data analysis and visualization',
      iconUrl: 'https://your-service.com/icon.png',
      webhookUrl: 'https://your-service.com/atp/webhook',
      webhookSecret: 'your_webhook_secret'
    });
    
    // Save this ID securely
    const serviceId = registration.service_id;
    console.log(`Service registered with ID: ${serviceId}`);
    
    return serviceId;
  } catch (error) {
    console.error('Registration failed:', error);
  }
}

registerService();

Environment Configuration

After registering your service, you should configure your environment with the obtained credentials:

Development vs. Production

ATP supports separate environments for development and production. Use different API keys and configurations for each:
# Development environment
export ATP_API_KEY="sk_test_your_key_here"
export ATP_SERVICE_ID="dev_service_id"
export ATP_ENVIRONMENT="development"
export ATP_WEBHOOK_SECRET="dev_webhook_secret"

# Production environment
export ATP_API_KEY="sk_live_your_key_here"
export ATP_SERVICE_ID="prod_service_id"
export ATP_ENVIRONMENT="production"
export ATP_WEBHOOK_SECRET="prod_webhook_secret"

Configuration Best Practices

  1. Never hardcode API keys or secrets in your application code
  2. Use environment-specific configuration for different deployment environments
  3. Rotate webhook secrets periodically to enhance security
  4. Use a secrets management solution for production environments
  5. Always verify webhook signatures to prevent tampering
Here’s an example of loading environment-specific configuration:
# Python example
import os
from atp import ATPClient

# Determine environment
environment = os.environ.get("ATP_ENVIRONMENT", "development")

# Load appropriate configuration
if environment == "production":
    api_key = os.environ.get("ATP_PROD_API_KEY")
    service_id = os.environ.get("ATP_PROD_SERVICE_ID")
    webhook_secret = os.environ.get("ATP_PROD_WEBHOOK_SECRET")
else:
    api_key = os.environ.get("ATP_DEV_API_KEY")
    service_id = os.environ.get("ATP_DEV_SERVICE_ID")
    webhook_secret = os.environ.get("ATP_DEV_WEBHOOK_SECRET")

# Initialize ATP client with environment-specific config
client = ATPClient(
    api_key=api_key,
    service_id=service_id,
    environment=environment
)

# Configure webhook verification
client.configure_webhook(webhook_secret=webhook_secret)

Verification Notification

After registration, it’s good practice to send a verification notification to ensure everything is working properly:
# Python example
def send_verification_notification():
    try:
        response = client.send_notification({
            "title": "Service Registration Verification",
            "description": "This is a test notification to verify your service registration",
            "priority": "low",
            "actions": [
                {
                    "id": "verify",
                    "label": "Verify",
                    "response_type": "simple"
                }
            ],
            "metadata": {
                "verification": True,
                "setup_stage": "registration"
            }
        })
        
        notification_id = response["notification_id"]
        print(f"Verification notification sent successfully! ID: {notification_id}")
        return notification_id
    
    except Exception as e:
        print(f"Error sending verification notification: {e}")
        return None

# Send the verification notification
notification_id = send_verification_notification()

Webhook Testing

To verify your webhook handling, you can use the ATP test client to simulate responses:
from atp.testing import TestClient

# Create a test client
test_client = TestClient()

# Send a test response to your verification notification
test_client.respond_to(notification_id, "verify")

# This should trigger your webhook endpoint with the response

Updating Service Registration

If you need to update your service details after registration (e.g., changing the webhook URL or description), use the update method:
# Python example
updated_result = client.update_service({
    "service_id": service_id,  # Your existing service ID
    "name": "My Improved AI Assistant",
    "description": "Updated description for my service",
    "icon_url": "https://your-service.com/new-icon.png",
    "webhook_url": "https://your-service.com/new-webhook-path",
    "webhook_secret": "new_webhook_secret"  # If changing the secret
})

print(f"Service updated successfully: {updated_result['updated_at']}")

Webhook Security

Securing your webhook endpoint is critical. Always verify incoming requests using the signature header:
# Python example for webhook verification
def is_valid_webhook(request_data, signature_header, webhook_secret):
    computed_signature = hmac.new(
        webhook_secret.encode(),
        request_data,
        hashlib.sha256
    ).hexdigest()
    
    return hmac.compare_digest(signature_header, computed_signature)
Additionally, follow these security best practices:
  1. Use HTTPS for your webhook endpoint
  2. Implement rate limiting to prevent abuse
  3. Validate the payload format and values before processing
  4. Keep your webhook secret secure and rotate it periodically
  5. Implement logging for security monitoring

Verification: Knowledge Check

Before proceeding, let’s verify your understanding of the service registration process: If you understand these concepts and have successfully registered your service, you’re ready to start sending notifications.

Next Steps

Now that your service is registered and configured, you’re ready to start creating and sending notifications to your users.

Creating Notifications

Learn how to design and send effective notifications
I