Third-Party Integrations API
Overview
The Integrations API provides endpoints for third-party service integrations with AuthOS. These endpoints enable external services to communicate with the platform for billing, analytics, and other automated workflows.
Currently, the platform integrates with Stripe for subscription billing and payment processing. Future integrations may include analytics services, monitoring tools, and communication platforms.
Key Features
- Stripe Webhook Integration: Automated subscription lifecycle management
- Signature Verification: Cryptographic validation of webhook authenticity
- Event Processing: Automatic handling of subscription events
- Error Handling: Robust error handling with detailed logging
- Idempotency: Safe retry of webhook deliveries
Endpoints Summary
| Method | Path | Description |
|---|---|---|
POST |
/webhooks/stripe |
Receive Stripe webhook events |
Stripe Webhook Integration
POST /webhooks/stripe
Receive and process webhook events from Stripe. This endpoint handles subscription lifecycle events, payment notifications, and customer updates to keep the platform’s billing data synchronized with Stripe.
Authentication: Stripe webhook signature verification (via stripe-signature header)
Permissions: None (webhook endpoint uses signature verification instead of authentication)
Request Headers:
| Header | Type | Required | Description |
|---|---|---|---|
stripe-signature |
string | Yes | Stripe webhook signature for verification (format: t={timestamp},v1={signature}) |
content-type |
string | Yes | Must be application/json |
Request Body:
The request body is a Stripe Event object in JSON format. The exact structure depends on the event type. Common fields:
| Field | Type | Description |
|---|---|---|
id |
string | Unique event identifier |
type |
string | Event type (e.g., customer.subscription.created) |
data |
object | Event-specific data payload |
created |
integer | Unix timestamp of event creation |
livemode |
boolean | Whether event occurred in live or test mode |
Example Request:
# This request is sent automatically by Stripe
curl -X POST https://sso.example.com/webhooks/stripe \
-H "stripe-signature: t=1614556800,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd" \
-H "Content-Type: application/json" \
-d '{
"id": "evt_1234567890",
"type": "customer.subscription.created",
"data": {
"object": {
"id": "sub_1234567890",
"customer": "cus_1234567890",
"status": "active",
"current_period_end": 1646092800,
"plan": {
"id": "price_1234567890",
"product": "prod_1234567890",
"nickname": "Pro Plan"
}
}
},
"created": 1614556800,
"livemode": false
}'
Response (200 OK):
{
"status": "success"
}
Response Fields:
status(string): Processing status, always “success” for successfully processed events
Error Responses:
-
400 Bad Request: Missing or invalid signature, invalid payload format{ "error": "Missing stripe-signature header" }{ "error": "Invalid payload encoding" } -
401 Unauthorized: Signature verification failed{ "error": "Webhook signature verification failed" } -
500 Internal Server Error: Event processing failed{ "error": "Failed to process webhook event" }
Supported Stripe Event Types
The platform processes the following Stripe webhook event types:
Subscription Events
customer.subscription.created
- Description: New subscription created
- Action: Creates subscription record in database
- Data Used: subscription ID, customer ID, status, plan details, current period end
customer.subscription.updated
- Description: Subscription details updated (plan change, status change, etc.)
- Action: Updates existing subscription record
- Data Used: subscription ID, new status, updated plan details, billing cycle dates
customer.subscription.deleted
- Description: Subscription canceled or deleted
- Action: Marks subscription as canceled in database
- Data Used: subscription ID, cancellation reason
customer.subscription.trial_will_end
- Description: Trial period ending soon (typically 3 days before)
- Action: Sends notification to user (if notification system configured)
- Data Used: subscription ID, trial end date
Payment Events
invoice.paid
- Description: Invoice payment successful
- Action: Updates subscription billing status, extends service period
- Data Used: invoice ID, subscription ID, payment amount, period end date
invoice.payment_failed
- Description: Invoice payment failed
- Action: Marks subscription as past due, may trigger retry or cancellation
- Data Used: invoice ID, subscription ID, failure reason
invoice.payment_action_required
- Description: Payment requires additional action (e.g., 3D Secure authentication)
- Action: Notifies user to complete payment authentication
- Data Used: invoice ID, subscription ID, payment intent status
Customer Events
customer.created
- Description: New Stripe customer created
- Action: Links Stripe customer ID to user account
- Data Used: customer ID, email, metadata
customer.updated
- Description: Customer details updated
- Action: Syncs customer information with local database
- Data Used: customer ID, updated fields
customer.deleted
- Description: Customer deleted from Stripe
- Action: Removes Stripe customer association, may cancel subscriptions
- Data Used: customer ID
Payment Method Events
payment_method.attached
- Description: Payment method attached to customer
- Action: Updates default payment method if applicable
- Data Used: payment method ID, customer ID, card/bank details
payment_method.detached
- Description: Payment method removed from customer
- Action: Removes payment method reference
- Data Used: payment method ID, customer ID
Webhook Configuration
Setting Up Stripe Webhooks
Step 1: Configure Webhook Endpoint in Stripe
- Log into Stripe Dashboard
- Navigate to Developers > Webhooks
- Click “Add endpoint”
- Enter endpoint URL:
https://your-domain.com/webhooks/stripe - Select events to listen for:
customer.subscription.*(all subscription events)invoice.*(all invoice events)customer.createdcustomer.updatedcustomer.deletedpayment_method.attachedpayment_method.detached
- Click “Add endpoint”
Step 2: Configure Environment Variables
Add the following environment variables to your .env file:
# Stripe API Configuration
STRIPE_SECRET_KEY=sk_live_xxxxxxxxxxxxxxxxxxxxx # Your Stripe secret key
STRIPE_WEBHOOK_SECRET=whsec_xxxxxxxxxxxxxx # Webhook signing secret from Step 1
Getting Your Webhook Secret:
- After creating the webhook endpoint in Stripe
- Click on the webhook endpoint in the Stripe Dashboard
- Reveal the “Signing secret”
- Copy the value (starts with
whsec_) - Add to your environment configuration
Step 3: Test Webhook Integration
Stripe provides testing tools to verify webhook integration:
# Install Stripe CLI
# macOS:
brew install stripe/stripe-cli/stripe
# Linux:
# Download from https://github.com/stripe/stripe-cli/releases
# Login to Stripe
stripe login
# Forward webhooks to local development server
stripe listen --forward-to localhost:3000/webhooks/stripe
# Trigger test events
stripe trigger customer.subscription.created
stripe trigger invoice.paid
stripe trigger invoice.payment_failed
Step 4: Monitor Webhook Deliveries
Monitor webhook delivery status in Stripe Dashboard:
- Navigate to Developers > Webhooks
- Click on your webhook endpoint
- View “Recent events” tab for delivery attempts
- Check response status codes and retry attempts
Webhook Security
Signature Verification
All incoming Stripe webhooks are verified using HMAC-SHA256 signature verification to ensure authenticity and prevent tampering.
Verification Process:
-
Extract Signature Header:
- Parse
stripe-signatureheader - Extract timestamp (
t) and signature (v1)
- Parse
-
Construct Signed Payload:
- Concatenate:
{timestamp}.{raw_body} - Use raw body exactly as received (no parsing or modification)
- Concatenate:
-
Compute Expected Signature:
- HMAC-SHA256(webhook_secret, signed_payload)
- Compare with signature from header
-
Validate Timestamp:
- Verify timestamp is within 5 minutes of current time
- Prevents replay attacks
Implementation Example (Conceptual):
fn verify_webhook_signature(
payload: &str,
signature_header: &str,
webhook_secret: &str,
) -> Result<bool> {
// Parse signature header
let parts: HashMap<&str, &str> = signature_header
.split(',')
.filter_map(|part| {
let mut split = part.split('=');
Some((split.next()?, split.next()?))
})
.collect();
let timestamp = parts.get("t").ok_or("Missing timestamp")?;
let signature = parts.get("v1").ok_or("Missing signature")?;
// Construct signed payload
let signed_payload = format!("{}.{}", timestamp, payload);
// Compute expected signature
let mut mac = Hmac::<Sha256>::new_from_slice(webhook_secret.as_bytes())?;
mac.update(signed_payload.as_bytes());
let expected_signature = hex::encode(mac.finalize().into_bytes());
// Constant-time comparison
Ok(constant_time_eq(signature.as_bytes(), expected_signature.as_bytes()))
}
Replay Attack Prevention
The platform prevents replay attacks by validating webhook timestamps:
- Webhooks with timestamps older than 5 minutes are rejected
- Protects against attackers replaying captured webhook requests
- Ensures events are processed in near real-time
Rate Limiting
Webhook endpoints have relaxed rate limiting compared to API endpoints:
- Rate: 1000 requests per minute per IP
- Burst: 100 requests
- Rationale: Stripe may send multiple events in quick succession
IP Allowlisting (Optional)
For additional security, you can restrict webhook access to Stripe’s IP addresses:
Stripe Webhook IP Addresses:
3.18.12.63
3.130.192.231
13.235.14.237
13.235.122.149
18.211.135.69
35.154.171.200
52.15.183.38
54.88.130.119
54.88.130.237
54.187.174.169
54.187.205.235
54.187.216.72
Note: Stripe’s IPs may change. Check Stripe documentation for current list.
Event Processing Details
Processing Flow
-
Receive Webhook:
- Webhook POST request arrives at
/webhooks/stripe - Raw body and signature header extracted
- Webhook POST request arrives at
-
Verify Signature:
- HMAC-SHA256 signature verification
- Timestamp validation (within 5 minutes)
- Reject if verification fails
-
Parse Event:
- Deserialize JSON payload into Stripe Event object
- Extract event type and data payload
-
Route to Handler:
- Event type determines handler function
- Handler processes event-specific logic
-
Update Database:
- Subscription records updated based on event
- User accounts synced with Stripe data
- Billing status updated
-
Return Success:
- 200 OK response sent to Stripe
- Stripe marks delivery as successful
Idempotency
Webhook events may be delivered multiple times by Stripe in case of network issues or timeouts. The platform handles idempotency:
- Event ID Tracking: Each Stripe event has unique ID (
evt_xxxxx) - Duplicate Detection: Events already processed are skipped
- Safe Retries: Multiple deliveries of same event have no adverse effects
Error Handling
When webhook processing fails:
- Error Logged: Detailed error logged with event ID and type
- Error Response: 500 Internal Server Error returned to Stripe
- Stripe Retry: Stripe automatically retries webhook delivery
- Initial retry: After 1 hour
- Subsequent retries: Exponential backoff up to 3 days
- Manual Intervention: Check logs and Stripe Dashboard for failures
- Event Replay: Can manually replay events from Stripe Dashboard if needed
Monitoring and Debugging
Webhook Logs
The platform logs all webhook activity for monitoring and debugging:
Log Levels:
-
INFO: Successful webhook processing
[INFO] Received Stripe webhook: customer.subscription.created (evt_1234567890) [INFO] Successfully processed webhook event evt_1234567890 -
WARN: Recoverable issues
[WARN] Webhook timestamp is close to threshold: 298 seconds old -
ERROR: Processing failures
[ERROR] Failed to process webhook event evt_1234567890: Database error [ERROR] Webhook signature verification failed
Stripe Dashboard Monitoring
Monitor webhook health in Stripe Dashboard:
- Navigate to: Developers > Webhooks
- View Metrics:
- Success rate over time
- Average response time
- Recent delivery attempts
- Investigate Failures:
- Click failed deliveries for details
- View request/response details
- Manually retry failed events
Testing Webhooks
Local Development Testing:
# Start local server
cargo run
# In another terminal, forward Stripe webhooks
stripe listen --forward-to localhost:3000/webhooks/stripe
# Trigger test event
stripe trigger customer.subscription.created
# View webhook in terminal output
# Check application logs for processing details
Staging/Production Testing:
- Use Stripe test mode for staging
- Create test subscription using Stripe Dashboard or API
- Monitor webhook delivery in Stripe Dashboard
- Verify database updates match expected behavior
Common Issues
“Webhook signature verification failed”
- Cause: Incorrect webhook secret in environment configuration
- Solution: Verify
STRIPE_WEBHOOK_SECRETmatches Stripe Dashboard value
“Missing stripe-signature header”
- Cause: Request not originating from Stripe, or reverse proxy stripping headers
- Solution: Check reverse proxy configuration preserves headers
“Failed to process webhook event: Database error”
- Cause: Database connection issues or constraint violations
- Solution: Check database connectivity and data integrity
Events not being received
- Cause: Webhook endpoint not configured in Stripe, or URL incorrect
- Solution: Verify webhook endpoint URL in Stripe Dashboard matches deployment
Best Practices
Security
-
Always Verify Signatures:
- Never process webhooks without signature verification
- Use constant-time comparison to prevent timing attacks
-
Validate Webhook Secret:
- Keep webhook secret secure and never commit to version control
- Use environment variables for configuration
- Rotate webhook secrets periodically
-
Implement IP Allowlisting:
- Restrict webhook endpoint to Stripe IP addresses (optional but recommended)
- Update allowlist when Stripe announces IP changes
-
Use HTTPS:
- Always use HTTPS for webhook endpoints in production
- Prevents man-in-the-middle attacks
Reliability
-
Idempotent Processing:
- Design handlers to safely process duplicate events
- Use event IDs to track processed events
- Avoid side effects from duplicate processing
-
Async Processing:
- Keep webhook response time under 1 second
- Queue long-running tasks for background processing
- Acknowledge receipt immediately
-
Error Handling:
- Return 2xx only when event successfully processed
- Return 5xx for temporary failures (triggers Stripe retry)
- Return 4xx for permanent failures (no retry needed)
-
Monitor Deliveries:
- Set up alerts for webhook failures
- Review Stripe Dashboard regularly
- Investigate patterns in failures
Testing
-
Use Stripe CLI:
- Test webhooks locally during development
- Trigger specific events to test edge cases
- Verify handling of all supported event types
-
Test Mode:
- Use Stripe test mode for staging environments
- Create realistic test scenarios
- Verify database state after each event
-
Integration Tests:
- Write automated tests for webhook handlers
- Mock Stripe event payloads
- Test signature verification logic
Maintenance
-
Keep Dependencies Updated:
- Update Stripe library regularly
- Monitor for security advisories
- Test thoroughly after updates
-
Document Event Handling:
- Document which events are supported
- Describe business logic for each event type
- Maintain changelog of event handling changes
-
Version Stripe API:
- Pin Stripe API version for consistency
- Test new API versions before upgrading
- Review Stripe changelog for breaking changes
Future Integrations
The Integrations API is designed to support additional third-party services in the future. Planned integrations include:
Analytics Services
- Segment: Customer data platform for analytics
- Mixpanel: Product analytics and user behavior tracking
- Google Analytics: Web analytics and conversion tracking
Communication Services
- SendGrid: Transactional email delivery
- Twilio: SMS notifications and two-factor authentication
- Slack: Team notifications and alerts
Monitoring Services
- Datadog: Application performance monitoring
- Sentry: Error tracking and debugging
- PagerDuty: Incident management and alerting
Each integration will follow similar patterns:
- Dedicated webhook endpoint
- Signature verification for security
- Event-based processing
- Comprehensive logging and monitoring
- Detailed API documentation
Support
Getting Help
Documentation:
Troubleshooting:
- Check webhook signature configuration
- Verify webhook endpoint URL is correct
- Review application logs for errors
- Check Stripe Dashboard for delivery attempts
- Test with Stripe CLI in development
Contact Support:
- Review platform audit logs for webhook events
- Provide Stripe event ID when reporting issues
- Include relevant error messages from logs
- Specify environment (development, staging, production)