OsayCore Docs
Overview
The OsayCore API provides a direct and secure way to integrate our powerful backend services into your web and mobile applications. By making standard HTTP requests, you can leverage features like robust user authentication, a flexible credit system, dynamic feature flagging, and comprehensive user context.
Key Features You Can Use:
API & App Security
Secure your application's communication with OsayCore using HMAC signatures based on your unique App API Key and Secret Key. Ensures only authorized applications make requests.
Seamless User Authentication
Authenticate end-users of your application. For web, utilize the convenient OAuth pop-up flow. For mobile or server-side needs, manage user sessions with secure JSON Web Tokens (JWTs).
Flexible Credit System
Implement usage-based billing by deducting credits for specific actions or services in your app. The API allows you to track user balances, view transaction history, and manage lifetime usage.
Dynamic Feature Flagging
Control feature availability for specific users, roles, or a percentage of your audience without deploying new code. Perfect for A/B testing, phased rollouts, and granular access control.
Rich User Context
Easily retrieve comprehensive user profiles, their current credit balance, app-specific permissions, and active feature flags in a single API call, empowering personalized experiences.
Activity & Audit Logging
OsayCore automatically logs critical application and user activities, providing you with an invaluable audit trail for monitoring, debugging, and compliance purposes.
How to Use the API:
The OsayCore API endpoints are designed for server-to-server communication or direct client-to-server calls where HMAC authentication can be securely managed. Your backend (e.g., Flask, Django, PHP) or secure mobile application will make direct HTTP requests to our API endpoints.
API Authentication (HMAC Signature)
All direct API calls from your backend or trusted client to OsayCore API endpoints must include an HMAC-SHA256 signature for authentication and integrity verification. This prevents unauthorized access and tampering.
Include the following custom headers with every request:
X-OSAYCORE-API-KEY: Your unique OsayCore App API Key.X-OSAYCORE-TIMESTAMP: The current Unix timestamp (seconds since epoch) when the request is sent.X-OSAYCORE-SIGNATURE: The HMAC-SHA256 signature of the request payload.
Generating the Signature
The signature is calculated using your App Secret Key and a string composed of the timestamp and the request body (payload). This ensures the request hasn't been altered and originates from your authorized application.
// Signature Base String:
// If POST/PUT/PATCH request with a body: "{timestamp}.{request_body_as_string}"
// If GET/DELETE request (no body): "{timestamp}." (timestamp followed by a dot)
// HMAC Algorithm: HMAC-SHA256
// Key: Your App Secret Key (bytes)
// Message: The Signature Base String (bytes)
// Example (Conceptual):
// request_body = '{"user_id": "...", "amount": 10.0}'
// timestamp = "1678886400" // Current Unix timestamp
// message = `${timestamp}.${request_body}`
// signature = hmac_sha256(your_app_secret_key.encode('utf-8'), message.encode('utf-8')).hexdigest()
User Authentication
Beyond authenticating your application, you'll need to authenticate the end-users interacting with your services. OsayCore facilitates this by providing secure JSON Web Tokens (JWTs) for your users.
Web Applications (OAuth Pop-up Flow)
This is the recommended approach for web applications, offering a smooth user experience:
Initiate OAuth Flow from Your Backend
Your client-side JavaScript should trigger an endpoint on your own backend (e.g., `/api/osaycore-auth-start`). This endpoint on your server then makes a **server-to-server API call** to OsayCore's `/api/auth/oauth/initiate` endpoint (with your App HMAC authentication).
The OsayCore API will respond with an `auth_url` which your client-side JavaScript then opens in a new pop-up window.
// Conceptual JavaScript in your web app (Client-side)
async function startOsayCoreAuth(provider) {
const backendAuthEndpoint = '/your-backend-api/auth/osaycore-initiate'; // Your API
const clientRedirectUri = window.location.origin + '/auth/osaycore-callback'; // Your client-side URL
const response = await fetch(backendAuthEndpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ provider: provider, redirect_uri: clientRedirectUri })
});
const data = await response.json();
if (data.auth_url) {
const popup = window.open(data.auth_url, '_blank', 'width=600,height=700,scrollbars=yes,resizable=yes');
// IMPORTANT: Your JS on the `clientRedirectUri` page will need to receive the JWT.
// It's recommended to have your *backend* receive the JWT from OsayCore's callback
// and then securely pass it to your client, rather than directly via URL params.
} else {
console.error("Error initiating OAuth:", data.error);
}
}
// Example call: startOsayCoreAuth('google');
OsayCore Processes OAuth Callback
After the user authenticates with the OAuth provider (e.g., Google) in the pop-up, the provider redirects to OsayCore's designated callback endpoint (e.g., `/api/auth/oauth/callback/google`). OsayCore handles the token exchange, user creation/linking (if new), and generates a secure OsayCore JWT for your user.
Receive JWT and Authenticate User
OsayCore then redirects the pop-up back to your `clientRedirectUri` (the one you provided in Step 1) with the OsayCore JWT appended as a query parameter (e.g., `?osaycore_jwt=YOUR_JWT`). Your client-side JavaScript must extract this JWT and store it (e.g., in `localStorage`).
This JWT should then be included in the `Authorization` header as a Bearer token (Authorization: Bearer YOUR_JWT) for all subsequent API calls to OsayCore that require user context.
Mobile/Backend Direct User Authentication
If your application manages user credentials (e.g., traditional email/password login) or uses a different OAuth flow (e.g., native SDKs for Google/Apple), you can generate an OsayCore JWT for your users directly from your backend.
After your user successfully logs into *your* application, make a **server-to-server API call** to OsayCore's `/api/auth/generate-user-jwt` endpoint. This endpoint will accept your internal `user_id` and return an OsayCore JWT valid for that user.
# Conceptual Python code in your backend after user login validation
import requests
import hashlib
import hmac
import time
import json
OSAYCORE_API_KEY = "YOUR_APP_API_KEY"
OSAYCORE_SECRET_KEY = "YOUR_APP_SECRET_KEY"
OSAYCORE_BASE_URL = "https://api.osaycore.com/api"
def generate_hmac_signature(secret_key, timestamp, payload):
message = f"{timestamp}.{payload}".encode('utf-8')
signature = hmac.new(secret_key.encode('utf-8'), message, hashlib.sha256).hexdigest()
return signature
def get_osaycore_user_jwt(your_internal_user_id):
endpoint = f"{OSAYCORE_BASE_URL}/auth/generate-user-jwt"
timestamp = str(int(time.time()))
payload = json.dumps({"user_id": str(your_internal_user_id)})
signature = generate_hmac_signature(OSAYCORE_SECRET_KEY, timestamp, payload)
headers = {
'Content-Type': 'application/json',
'X-OSAYCORE-API-KEY': OSAYCORE_API_KEY,
'X-OSAYCORE-TIMESTAMP': timestamp,
'X-OSAYCORE-SIGNATURE': signature
}
try:
response = requests.post(endpoint, headers=headers, data=payload)
response.raise_for_status() # Raise an exception for HTTP errors
return response.json().get('jwt_token')
except requests.exceptions.RequestException as e:
print(f"Error generating OsayCore JWT: {e}")
print(f"Response: {response.text if 'response' in locals() else 'N/A'}")
return None
# Then your mobile app receives this JWT from your backend and uses it.
Credit Management
Manage user credits for usage-based billing or premium feature access directly through the OsayCore API.
Deducting Credits (POST /api/action/deduct-credits)
To charge a user credits for an action (e.g., API call, generating a report, using a premium feature), make a **server-to-server API call** to this endpoint. This call requires **API Authentication** (HMAC) and the user's **OsayCore JWT** in the Authorization header.
| Parameter | Type | Required | Description |
|---|---|---|---|
amount |
number |
Yes | The amount of credits to deduct. Must be positive. |
description |
string |
No | A description for the transaction (e.g., "Generated image #123"). |
client_reference_id |
string |
No | Your internal reference ID for this specific transaction. Useful for tracking. |
# Conceptual Python code in your backend for an API endpoint
import requests
import hashlib
import hmac
import time
import json
import uuid # For client_reference_id
OSAYCORE_API_KEY = "YOUR_APP_API_KEY"
OSAYCORE_SECRET_KEY = "YOUR_APP_SECRET_KEY"
OSAYCORE_BASE_URL = "https://api.osaycore.com/api"
def generate_hmac_signature(secret_key, timestamp, payload):
message = f"{timestamp}.{payload}".encode('utf-8')
signature = hmac.new(secret_key.encode('utf-8'), message, hashlib.sha256).hexdigest()
return signature
def deduct_user_credits_api(user_jwt, amount_to_charge, action_description):
endpoint = f"{OSAYCORE_BASE_URL}/action/deduct-credits"
timestamp = str(int(time.time()))
payload_data = {
"amount": amount_to_charge,
"description": action_description,
"client_reference_id": str(uuid.uuid4()) # Example: unique ID for this action
}
payload = json.dumps(payload_data)
signature = generate_hmac_signature(OSAYCORE_SECRET_KEY, timestamp, payload)
headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${user_jwt}`, # User's JWT
'X-OSAYCORE-API-KEY': OSAYCORE_API_KEY,
'X-OSAYCORE-TIMESTAMP': timestamp,
'X-OSAYCORE-SIGNATURE': signature
}
try:
response = requests.post(endpoint, headers=headers, data=payload)
response.raise_for_status() # Raise an exception for HTTP errors (4xx or 5xx)
return response.json()
except requests.exceptions.HTTPError as e:
print(f"HTTP Error during credit deduction: {e.response.status_code} - {e.response.text}")
return {"success": False, "error": e.response.json().get('error', 'Unknown API error')}
except requests.exceptions.RequestException as e:
print(f"Network/Connection Error during credit deduction: {e}")
return {"success": False, "error": "Network or connection error"}
Adding Credits (POST /api/credits/add-credits)
This endpoint allows you to programmatically add credits to a user's balance, typically for refunds, bonuses, or administrative adjustments. This is a privileged API call and usually made from a trusted backend service (e.g., your payment webhook handler, or admin panel).
| Parameter | Type | Required | Description |
|---|---|---|---|
user_id |
string |
Yes | The OsayCore UUID of the user to credit. |
amount |
number |
Yes | The amount of credits to add. Must be positive. |
description |
string |
No | A description for the transaction. |
transaction_type |
string |
Yes | Type of transaction: PURCHASE, BONUS, REFUND, ADJUSTMENT, EARNED. |
payment_id |
string |
No | Optional. The UUID of a related OsayCore Payment record (if credits are from a purchase). |
# Conceptual Python code in your backend for a refund or bonus
import requests
import hashlib
import hmac
import time
import json
OSAYCORE_API_KEY = "YOUR_APP_API_KEY"
OSAYCORE_SECRET_KEY = "YOUR_APP_SECRET_KEY"
OSAYCORE_BASE_URL = "https://api.osaycore.com/api"
def generate_hmac_signature(secret_key, timestamp, payload):
message = f"{timestamp}.{payload}".encode('utf-8')
signature = hmac.new(secret_key.encode('utf-8'), message, hashlib.sha256).hexdigest()
return signature
def add_user_credits_api(user_id, amount, reason, transaction_type="BONUS", payment_id=None):
endpoint = f"{OSAYCORE_BASE_URL}/credits/add-credits"
timestamp = str(int(time.time()))
payload_data = {
"user_id": str(user_id),
"amount": amount,
"description": reason,
"transaction_type": transaction_type
}
if payment_id:
payload_data["payment_id"] = str(payment_id)
payload = json.dumps(payload_data)
signature = generate_hmac_signature(OSAYCORE_SECRET_KEY, timestamp, payload)
headers = {
'Content-Type': 'application/json',
'X-OSAYCORE-API-KEY': OSAYCORE_API_KEY,
'X-OSAYCORE-TIMESTAMP': timestamp,
'X-OSAYCORE-SIGNATURE': signature
}
try:
response = requests.post(endpoint, headers=headers, data=payload)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error adding credits: {e}")
return {"success": False, "error": str(e)}
User Context & Flags
Retrieve a comprehensive snapshot of a user's status, permissions, and active features for your application by making a GET request to `/api/user/context`.
Fetching User Context (GET /api/user/context)
This endpoint provides a single point of access to:
- User profile summary (ID, email, roles, status)
- Current credit balance
- App-specific permissions (e.g., `can_use`, custom rates, scopes)
- Evaluated feature flags relevant to the user and your app.
This call requires **API Authentication** (HMAC) and the user's **OsayCore JWT** in the Authorization header.
# Conceptual Python code in your backend
import requests
import hashlib
import hmac
import time
import json
OSAYCORE_API_KEY = "YOUR_APP_API_KEY"
OSAYCORE_SECRET_KEY = "YOUR_APP_SECRET_KEY"
OSAYCORE_BASE_URL = "https://api.osaycore.com/api"
def generate_hmac_signature(secret_key, timestamp, payload=""): # Payload can be empty for GET
message = f"{timestamp}.{payload}".encode('utf-8')
signature = hmac.new(secret_key.encode('utf-8'), message, hashlib.sha256).hexdigest()
return signature
def get_user_context_api(user_jwt):
endpoint = f"{OSAYCORE_BASE_URL}/user/context"
timestamp = str(int(time.time()))
# For GET requests, the payload for signature is typically an empty string
payload = ""
signature = generate_hmac_signature(OSAYCORE_SECRET_KEY, timestamp, payload)
headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${user_jwt}`,
'X-OSAYCORE-API-KEY': OSAYCORE_API_KEY,
'X-OSAYCORE-TIMESTAMP': timestamp,
'X-OSAYCORE-SIGNATURE': signature
}
try:
response = requests.get(endpoint, headers=headers)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error fetching user context: {e}")
return {"success": False, "error": str(e)}
Understanding Feature Flags
Feature flags are returned as part of the `get_user_context` response under the `enabled_features` key. This allows your application's UI and backend logic to adapt dynamically based on user segments or A/B tests, without requiring new code deployments.
API Reference
A comprehensive list of OsayCore API endpoints, their methods, required parameters, and expected responses.
Base URL: https://api.osaycore.com/api
Description
Generates the authorization URL for an OAuth provider (e.g., Google, GitHub). Your client-side application opens this URL in a pop-up for user consent.
Authentication
App Authentication (HMAC Signature) required.
Request Body
| Parameter | Type | Required | Description |
|---|---|---|---|
provider | string | Yes | The name of the OAuth provider (e.g., "google", "github"). |
redirect_uri | string | Yes | The URL on your client-side application where OsayCore will redirect with the JWT after successful OAuth. Must be registered in your OsayCore App settings. |
Success Response (200 OK)
{ "auth_url": "https://accounts.google.com/o/oauth2/auth?client_id=..." }Error Responses
400 Bad Request: Missing parameters.401 Unauthorized: Invalid API key or signature.403 Forbidden: `redirect_uri` not registered or invalid for this app.400 Bad Request: Unsupported provider.
Description
Generates an OsayCore JWT for a specified user ID. Useful for backend-driven user authentication where you manage user credentials and need an OsayCore token for subsequent API calls.
Authentication
App Authentication (HMAC Signature) required.
Request Body
| Parameter | Type | Required | Description |
|---|---|---|---|
user_id | string | Yes | The OsayCore UUID of the user. |
expires_in_seconds | integer | No | Duration in seconds until JWT expires. Default: 3600 (1 hour). |
Success Response (200 OK)
{ "jwt_token": "eyJhbGciOiJIUzI1Ni...", "expires_at": "2025-08-06T12:00:00Z" }Error Responses
400 Bad Request: Missing `user_id`.401 Unauthorized: Invalid API key or signature.404 Not Found: User not found.
Description
Deducts a specified amount of credits from a user's balance. Performs automatic balance checks.
Authentication
App Authentication (HMAC Signature) and User Authentication (Bearer Token) required.
Request Body
| Parameter | Type | Required | Description |
|---|---|---|---|
amount | number | Yes | The amount of credits to deduct. Must be positive. |
description | string | No | A description for the transaction. |
client_reference_id | string | No | Your internal reference ID for this transaction. |
Success Response (200 OK)
{ "success": true, "transaction_id": "uuid", "new_balance": 95.00 }Error Responses
400 Bad Request: Invalid amount or parameters.401 Unauthorized: Invalid API key, signature, or user JWT.402 Payment Required: Insufficient credits or minimum balance exceeded.403 Forbidden: User not authorized to use the app feature.404 Not Found: User not found.
Description
Adds a specified amount of credits to a user's balance. Typically used for purchases, bonuses, or refunds.
Authentication
App Authentication (HMAC Signature) required. (Often a privileged call).
Request Body
| Parameter | Type | Required | Description |
|---|---|---|---|
user_id | string | Yes | The OsayCore UUID of the user to credit. |
amount | number | Yes | The amount of credits to add. Must be positive. |
description | string | No | A description for the transaction. |
transaction_type | string | Yes | Type of transaction: PURCHASE, BONUS, REFUND, ADJUSTMENT, EARNED. |
payment_id | string | No | Optional. The UUID of a related OsayCore Payment record (if credits are from a purchase). |
Success Response (200 OK)
{ "success": true, "transaction_id": "uuid", "new_balance": 120.00 }Error Responses
400 Bad Request: Invalid amount, transaction type, or parameters.401 Unauthorized: Invalid API key or signature.404 Not Found: User not found.
Description
Retrieves a comprehensive context for the authenticated user, including profile summary, credit balance, app-specific permissions, and active feature flags.
Authentication
App Authentication (HMAC Signature) and User Authentication (Bearer Token) required.
Request Parameters
None directly. User context is derived from the JWT in the `Authorization` header.
Success Response (200 OK)
{
"success": true,
"user_summary": {
"id": "uuid-of-user",
"email": "user@example.com",
"username": "user123",
"display_name": "User 123",
"role": "basic",
"status": "active",
"avatar_url": null,
"email_verified": true
},
"credit_balance": {
"balance": 95.00,
"lifetime_earned": 150.00,
"lifetime_spent": 55.00,
"currency_unit": "credits"
},
"app_context": {
"app_id": "uuid-of-app",
"app_name": "My Integrated App",
"app_permissions": {
"can_use": true,
"is_authorized": true,
"effective_credit_rate": 0.001,
"scopes": ["read_profile", "deduct_credits"],
"custom_permissions": {}
}
},
"enabled_features": {
"new_dashboard_ui": true,
"premium_analytics": false
},
"api_session_id": "jwt-jti-uuid"
}Error Responses
401 Unauthorized: Invalid API key, signature, or user JWT.404 Not Found: User not found (if JWT points to a non-existent user).
Platform-Specific Integration Guides
Learn how to integrate with the OsayCore API using standard HTTP client libraries in various popular backend and mobile platforms.
Integrating the OsayCore API into your Flask application involves making direct HTTP requests and managing HMAC signatures. You'll typically set up Flask endpoints to serve your frontend, and these endpoints will make server-to-server calls to the OsayCore API.
1. Required Libraries
pip install requests
2. Configuration
Store your API keys securely, preferably as environment variables:
# app.py or config.py
import os
import hashlib
import hmac
import time
import json
class Config:
OSAYCORE_API_KEY = os.environ.get('OSAYCORE_API_KEY', 'YOUR_APP_API_KEY')
OSAYCORE_SECRET_KEY = os.environ.get('OSAYCORE_SECRET_KEY', 'YOUR_APP_SECRET_KEY')
OSAYCORE_BASE_URL = 'https://api.osaycore.com/api'
def generate_osaycore_hmac_headers(api_key, secret_key, method, endpoint_path, payload=None):
timestamp = str(int(time.time()))
if payload:
if isinstance(payload, dict):
payload_str = json.dumps(payload, separators=(',', ':'))
else:
payload_str = payload
else:
payload_str = ""
message = f"{timestamp}.{payload_str}".encode('utf-8')
signature = hmac.new(secret_key.encode('utf-8'), message, hashlib.sha256).hexdigest()
return {
'X-OSAYCORE-API-KEY': api_key,
'X-OSAYCORE-TIMESTAMP': timestamp,
'X-OSAYCORE-SIGNATURE': signature,
'Content-Type': 'application/json' if payload else None
}
Integrating the OsayCore API into your Django application, especially with Django Rest Framework, involves handling HTTP requests and HMAC signatures within your views or serializers.
1. Required Libraries
pip install requests djangorestframework
2. Configuration (settings.py)
# settings.py
import os
import hashlib
import hmac
import time
import json
OSAYCORE_API_KEY = os.environ.get('OSAYCORE_API_KEY', 'YOUR_APP_API_KEY')
OSAYCORE_SECRET_KEY = os.environ.get('OSAYCORE_SECRET_KEY', 'YOUR_APP_SECRET_KEY')
OSAYCORE_BASE_URL = 'https://api.osaycore.com/api'
def generate_osaycore_hmac_headers(api_key, secret_key, method, endpoint_path, payload=None):
timestamp = str(int(time.time()))
if payload:
if isinstance(payload, dict):
payload_str = json.dumps(payload, separators=(',', ':'))
else:
payload_str = payload
else:
payload_str = ""
message = f"{timestamp}.{payload_str}".encode('utf-8')
signature = hmac.new(secret_key.encode('utf-8'), message, hashlib.sha256).hexdigest()
headers = {
'X-OSAYCORE-API-KEY': api_key,
'X-OSAYCORE-TIMESTAMP': timestamp,
'X-OSAYCORE-SIGNATURE': signature
}
if payload:
headers['Content-Type'] = 'application/json'
return headers
For mobile applications, the safest approach is to route all OsayCore API interactions through your own secure backend. Your mobile app authenticates with *your* backend, and your backend then makes the server-to-server HMAC-authenticated calls to the OsayCore API.
This ensures your sensitive App Secret Key is never exposed on the client (mobile app).
Integrating the OsayCore API into your PHP application (e.g., Laravel, Symfony, or custom MVC) involves using a robust HTTP client library (like Guzzle) to make requests and manually managing HMAC signatures.
Integrating the OsayCore API into your PHP application (e.g., Laravel, Symfony, or custom MVC) involves using a robust HTTP client library (like Guzzle) to make requests and manually managing HMAC signatures.
Troubleshooting
| Issue | Common Cause / Solution |
|---|---|
401 Missing API authentication headers |
Ensure X-OSAYCORE-API-KEY, X-OSAYCORE-TIMESTAMP, and X-OSAYCORE-SIGNATURE are correctly sent with all backend-to-API requests. |
401 Invalid API signature |
Your HMAC signature calculation is incorrect, or the X-OSAYCORE-TIMESTAMP is outside the allowed 5-minute window. Double-check your secret_key encoding, the timestamp, and the exact payload used for signing. For GET requests, the signed payload is an empty string (""). |
401 Unauthorized / Authentication token expired/invalid (for user JWT) |
The JWT sent by your client-side app is old, corrupted, or not included in the Authorization: Bearer header. Prompt the user to re-authenticate via the OAuth flow. |
402 Payment Required / Insufficient credits |
The user's credit balance is too low for the requested action. Implement logic in your application to prompt the user to purchase more credits or offer alternative actions. |
| OAuth pop-up does not close or redirect correctly |
1. Ensure your `IntegratedApp`'s `callback_url` in the OsayCore dashboard matches the actual URL your `OsayCore_BASE_URL/auth/oauth/callback` endpoint resides on. 2. Ensure the `redirect_uri` you send from your client-side JS to your backend (and then to OsayCore's `/auth/oauth/initiate` endpoint) is correctly configured and matches the expected domain on your client-side. 3. Check for browser pop-up blockers. |
| `500 Internal Server Error` from OsayCore API endpoint | Check your OsayCore backend logs for detailed error messages. This usually indicates an an issue with our service or a misconfiguration on our end. Provide the request ID if available. |
| Missing feature flags in user context | Ensure the feature flags are active in your OsayCore dashboard and that targeting rules (e.g., user roles, percentages) apply to the test user. |