Cosmo

Get Started With Cosmo

This guide walks you through how to integrate your application with the Cosmo API. It's designed for developers who want a clear, straightforward understanding of how to authenticate, work with partner programs, and issue points using Cosmo's core endpoints.

Cosmo follows a simple flow: sign up, authenticate, retrieve your partnerships, and start issuing points. Sandbox mode lets you build and test safely before you connect to real partner programs in production.

By the end of this guide, you will be able to:

  • check_circleSet up your organization and obtain API credentials
  • check_circleAuthenticate and make authorized requests
  • check_circleLoad the programs available to your business
  • check_circleValidate destination users
  • check_circlePreview and issue point transactions
  • check_circleRetrieve transactions and handle errors correctly

Account Setup

There are two paths to getting set up with Cosmo, depending on your organization's needs and preferences.

corporate_fare

Managed Setup

For enterprises that require guided onboarding, Cosmo can manage the account creation and configuration process on your behalf. This includes:

  • Provisioning your organization in Cosmo
  • Assigning API credentials
  • Enabling program partnerships
  • Completing KYB and compliance checks

Your credentials and access details will be shared once configuration is complete.

dashboard_customize

Self-Service Setup

If you prefer to set up your account directly, follow the onboarding flow in the Cosmo Portal. Steps:

  • Sign up using your business email.
  • Enter your organization's legal name.
  • Complete the automated KYB process.
  • Once approved, your organization and API credentials are created automatically.

After completion, you can immediately begin using Sandbox mode for development and testing.

Sign Up

To begin using Cosmo, your team must create an organization and complete identity verification.

  1. 1

    Provide Organization Details

    Provide your organization's legal details.

  2. 2

    Verify Email

    Verify your email address to confirm your identity.

  3. 3

    Log Into Portal

    Log into the Cosmo Portal.

  4. 4

    Submit KYB

    Submit your KYB (Know Your Business) information.

  5. 5

    Await Approval

    Await automated approval (typically minutes).

Note: Your API credentials (client_id and client_secret) will be visible once your KYB has been approved.

Sandbox Integration

Sandbox mode allows you to build and test your integration without affecting live partner programs. All transactions created in Sandbox are isolated and do not interact with production systems.

Sandbox Authentication

Sandbox uses the same authentication flow as production but with separate client credentials. Use your sandbox client_id and sandbox client_secret to obtain an access token.

Environment Behavior

  • check_circleSimulated Transactions: All transactions are simulated and do not affect real balances.
  • check_circleError Triggers: Error responses can be triggered deterministically using specific destinationUserId values.
  • check_circleMirror Production: Program configurations in Sandbox mirror the structure of Production.
  • check_circleNo Real Points: No real points are issued and no partner systems are contacted.

Note: Sandbox is designed to match production logic as closely as possible so your integration will behave identically when you switch environments.

User Flow

This section describes the complete flow your system will follow to issue points through Cosmo. Each step maps directly to a specific API endpoint, with links to the exact documentation for reference.

1

Authenticate

POST /auth/token

Your backend begins by authenticating with Cosmo using your client credentials. This returns a short-lived access token that must be included in all subsequent requests.

What happens:

  • Your backend sends client_id and client_secret
  • Cosmo returns a JWT access token
  • All future requests must include Authorization: Bearer <token>

If the token expires, re-authenticate and retry.

2

Retrieve Partnerships

GET /programs

After authentication, your backend should fetch the partner programs available to your organization. This tells you which programs you can issue points to, and provides key metadata including programId and required account fields.

What this is used for:

  • Populating available partner programs in your UI
  • Obtaining the programId needed for issuing points
  • Reading program requirements (e.g., necessary destinationUserId fields)

Your system should cache this list but refresh periodically.

3

Issue Points

This step performs the core business action: issuing loyalty points to a user for a selected partner program. The flow involves validation, optional previewing, and finally executing the transaction.

Validate User (Recommended)

POST /programs/{programId}/validate-member

Checks if the destination user is valid for the selected program. Use this before issuing points to reduce failed transactions.

Preview Transaction (Optional)

POST /transactions/preview

Returns how many points would be issued for a given value without creating a transaction. Useful for showing 'You will receive X points' in your UI.

Issue Transaction (Required)

POST /transactions

Creates the actual transaction and issues points to the user.

Response includes:

  • Transaction ID
  • Total points issued
  • Reference number
  • Timestamp

Your backend should store these values for reconciliation.

Error Handling

Simulating Errors

Sandbox mode supports deterministic error simulation using predefined destinationUserId values.

This allows you to test:

  • Your backend error handling
  • Frontend error messaging
  • Retry and reconciliation flows

No dedicated endpoint — triggered through the normal Issue Points flow using sandbox IDs.

Possible Error Responses

Cosmo may return errors when a request violates authentication, validation, or program rules. Common errors include:

Expired or invalid token

Missing required fields

Exceeding allowed transaction value limit

Exceeding allowed transaction points limit

Invalid program ID

No partnership with the specified program

All errors follow a structured response format, enabling consistent handling in your system.

Key API Endpoints

Cosmo provides a broad range of API endpoints beyond the essentials, enabling customized experiences throughout your user flow.

Validate User

POST

POST /programs/{programId}/validate-member

Use this endpoint before issuing points to confirm that the destination user is valid for the selected loyalty program. This step prevents failed transactions and is recommended for all production-grade flows.

When to use:

  • • Before issuing points
  • • Before running an issue-points preview
  • • To pre-check a user during onboarding flows

Key fields:

Request: destinationUserId, destinationUserEmail

Response: isValid (true/false)

Issue Points Preview

POST

POST /transactions/preview

This endpoint lets you check how many points will be issued for a given fiat value before committing a transaction. It is ideal for showing users 'You will receive X points' in your UI.

When to use:

  • • Showing point estimates in the UI
  • • Pre-validating transaction value
  • • Applying business rules before final submission

Key fields:

Request: programId, value (fiat amount)

Response: totalPoints

This call performs no transaction. You must still call the actual Issue Points endpoint to complete the operation.

Issue Points (Fiat Value)

POST

POST /transactions

This is the core transaction endpoint. Points are issued to the specified user, the transaction is recorded, and a unique transaction ID is returned.

When to use:

  • • To issue points based on a fiat amount
  • • Standard use case for most integrations

Key fields:

Request: programId, value, currency, destinationAccount, referenceNumber, description

Response: id, totalPoints, referenceNumber, date

Store these values for reconciliation.

Issue Points (Exact Number)

POST

POST /transactions (same endpoint)

Instead of sending a fiat value, you can issue an exact number of points. This is useful when your system calculates the conversion or when you need deterministic issuance.

When to use:

  • • Your application determines the exact points
  • • You want fixed-point issuance rather than value-based
  • • Promotions, bonuses, partner-specific campaigns

Key fields:

Request: programId, value, currency (POINTS), destinationAccount, referenceNumber, description

If you're unsure whether your organization has numberOfPoints mode enabled, test in sandbox or confirm with your account manager.

Get Transaction

GET

GET /transactions/{transactionId}

Use this endpoint to retrieve the full details of a previously issued transaction. This is important for reconciliation, customer support, audit trails, and verifying the final state of a transaction.

When to use:

  • • To confirm the final status of a transaction
  • • To reconcile your internal ledger with Cosmo's ledger
  • • To display transaction details in your dashboard
  • • For troubleshooting failed or partial transactions
  • • When handling webhook retries or verifying you haven't double-processed a transaction

Key fields:

Request: transactionId (path parameter)

Production Integration

Once your integration works as expected in Sandbox, you can move to Production. The production environment uses the same API structure and endpoints, so no code changes are required — only updated credentials and real program configurations.

verified_userProduction Credentials

Your production client_id and client_secret will be issued after:

  • circleYour KYB is approved
  • circleAt least one partner program is enabled for your organization

These credentials must be stored securely and should never be exposed in client-side code.

Environment Changes

Production differs from Sandbox in the following ways:

  • Transactions interact with live partner systems
  • User validation checks real member accounts
  • All issued points are financially binding
  • Error simulation is not available

Recommended Steps Before Going Live

  • Confirm your organization has active partnerships
  • Validate the required destination fields for each program
  • Ensure all error cases are handled gracefully
  • Verify your reconciliation logic
  • Test your webhook handling (if used)

Once you replace your Sandbox token flow with Production credentials, your integration is considered live.

Going Live

Going Live means your system will start issuing real points to real user accounts. To ensure a smooth launch, your backend should follow a few final checks and operational best practices.

Final Pre-Launch Checks

  • check_circleConfirm your Production authentication flow is functioning
  • check_circleValidate at least one real user account using the Validate Member endpoint
  • check_circleIssue a small live transaction for internal testing
  • check_circleConfirm that you can retrieve the transaction via GET /transactions/{transactionId}
  • check_circleVerify all transaction details are stored in your internal system

Monitoring

After launch, monitor your integration for:

Failed transaction attempts

Token expiry errors

Incorrect or missing destination user fields

Unexpected increases in traffic

Any mismatches during reconciliation

Operational Notes

  • All Production transactions are permanent and billable
  • You should alert your team on any error spikes or partner program failures
  • Keep logs for validation, preview, and issue calls to support downstream audits

Once these items are confirmed, your integration is fully operational and ready to handle real users at scale.

Point Exchange Widget

The Point Exchange widget lets you offer point purchases or exchanges without building your own frontend. You embed the widget in your web or mobile app; your backend handles authentication and post-transaction logic.

Use this if you:

  • • Want a ready-made UX for buying/exchanging points
  • • Prefer to keep all sensitive logic (auth, debits, reconciliation) on your backend

Authentication

Before launching the widget, your backend must obtain a short-lived access token.

This token:

  • Is valid for 10 minutes
  • Is passed as a query parameter to the widget URL
  • Must be obtained server-side only
  • Must never expose clientId or clientSecret in the frontend

Endpoint:

  • Method: POST
  • URL: https://api.cosmopoints.com/v1/auth/widget/point-exchange
Request Body
1{
2 "clientId": "string", // Available in the Cosmo Portal
3 "clientSecret": "string", // Available in the Cosmo Portal
4 "userId": "string", // Any unique user identifier (can be opaque)
5 "amount": number, // Amount in your chosen currency
6 "referenceNumber": "string", // Your internal reference / transaction ID
7 "currency": "string", // USD / SAR / AED
8 "description": "string | null" // (Optional) transaction description
9}
Response Body
1{
2 "accessToken": "string"
3}

Your backend should return only the accessToken (or a wrapper around it) to your frontend.

Launching the Widget

On the frontend, you embed the widget using the access token returned by your backend.

Example (web, iFrame)
1<iframe
2 src="https://purchase.cosmopoints.com?token=ACCESS_TOKEN"
3 style="width: 100%; height: 600px; border: 0;"
4></iframe>

Replace ACCESS_TOKEN with the token you obtained from the authentication step.

You can host the widget:

  • In a web app (iFrame or WebView)
  • In a mobile app via an in-app browser / webview

The widget handles:

  • Displaying available purchase/exchange options
  • Collecting any required user inputs
  • Sending the transaction request to Cosmo

Transaction Completion and Webhooks

When a transaction is completed via the Point Exchange widget, Cosmo sends a Transaction Webhook to your configured endpoint.

Your backend should:

  • Verify the webhook (see Webhooks section)
  • Confirm the transactionId, value, and destination account details
  • Only then apply post-completion logic (for example: debit the user's balance or update internal ledgers)

For the exact payload structure and signature verification, refer to the Transaction Webhook format in the Webhooks section.

Multibrand Widget

The Multibrand widget lets users manage their reward preferences for a Multibrand card.

Users can:

  • Select and edit their preferred loyalty programs
  • Decide how rewards are allocated across multiple programs
  • Update preferences over time

Authentication

The Multibrand widget uses the same pattern as the Point Exchange widget: your backend obtains a short-lived access token for a specific user, then your frontend uses that token to launch the widget.

Key points:

  • Token lifetime: 1 minute
  • Obtained via backend-to-backend call
  • Passed in the widget URL as a token query parameter
  • Never expose clientId or clientSecret to the frontend

Endpoints:

  • Method: POST
  • URL: https://api.cosmopoints.com/v1/auth/widget/multibrand
Request Body
1{
2 "clientId": "string", // Available in the Cosmo portal
3 "clientSecret": "string", // Available in the Cosmo portal
4 "userId": "string" // Your unique user ID (can be opaque)
5}
Response Body
1{
2 "accessToken": "string"
3}

Launching the Widget

On the frontend, embed the Multibrand widget using the access token provided by your backend.

Example (web, iFrame)
1<iframe
2 src="https://multibrand.cosmopoints.com/?token=ACCESS_TOKEN"
3 style="width: 100%; height: 600px; border: 0;"
4></iframe>

Once launched, the widget:

  • Displays the list of available programs for that card
  • Allows users to add, remove, or edit reward preferences

Note: Use the sandbox iFrame by replacing the URL with https://multibrand.sandbox.cosmopoints.com/?token=ACCESS_TOKEN

Webhooks

Cosmo uses webhooks to notify your backend of important events, such as completed point transactions. All webhook deliveries support multiple authentication mechanisms. You can configure your webhook endpoints in the Cosmo Portal → Developers → Webhooks

Authentication Methods

Cosmo supports three authentication modes for webhook delivery:

Basic Auth

Cosmo includes your configured username and password in the HTTP request. Your server should verify these credentials before processing the payload.

OAuth 2.0

Cosmo obtains a token from the token endpoint you provide and includes it in webhook requests. You may choose whether credentials are passed via Basic Auth header or credentials in the body.

Signature (Recommended)

Cosmo signs every webhook request using your configured secret. This enables your backend to cryptographically verify that the request is authentic and untampered. The signature is included in the x-cosmo-signature and x-cosmo-timestamp headers.

Transaction Webhook

Sent when a transaction (via API or Point Exchange widget) completes successfully. Your backend should process the transaction only after receiving this webhook.

JSON Payload
1{
2 "transactionId": "string",
3 "sourceProgramId": "string",
4 "destinationProgramId": "string",
5 "value": number,
6 "referenceNumber": "string",
7 "destinationAccount": {
8 "destinationUserEmail": "user@example.com",
9 "destinationUserId": "123456"
10 },
11 "timestamp": number,
12 "type": "string"
13}

Typical uses:

  • Debit the user's balance
  • Update your internal ledger
  • Display transaction results
  • Trigger downstream notifications

Program Connection Webhook

Sent when a user links, edits, or removes point exchange program connections. Your backend should update your internal preference model based on this message.

JSON Payload
1{
2 "destinationAccount": {
3 "destinationUserEmail": "user@example.com",
4 "destinationUserId": "123456"
5 },
6 "destinationProgramId": "string",
7 "sourceUserId": "string",
8 "timestamp": number,
9 "type": "string" // "LINKED" | "DELINKED" | "UPDATED"
10}

Verifying Webhook Signatures

Every webhook delivered using Signature-Based Authentication includes x-cosmo-signature and x-cosmo-timestamp headers. Your backend must:

  1. 1.Read the headers
  2. 2.Obtain the raw JSON body exactly as sent
  3. 3.Build the string: ${timestamp}:${rawBody}
  4. 4.Compute: HMAC_SHA-256(secret, ${timestamp}:${rawBody})
  5. 5.Compare the result with x-cosmo-signature
  6. 6.Only process the webhook if the signatures match
verify-signature.js
1import express from 'express';
2import crypto from 'crypto';
3
4const app = express();
5
6// Important: capture raw body for signature verification
7app.use(
8 express.json({
9 verify: (req, res, buf) => {
10 req.rawBody = buf.toString();
11 }
12 })
13);
14
15const WEBHOOK_SECRET = 'your_webhook_secret_here';
16
17app.post('/your/webhook/endpoint', (req, res) => {
18 const signature = req.headers['x-signature'];
19 const timestamp = req.headers['x-timestamp'];
20 const rawBody = req.rawBody;
21
22 if (!signature || !timestamp) {
23 return res.status(400).send('Missing signature headers');
24 }
25
26 const expected = crypto
27 .createHmac('sha256', WEBHOOK_SECRET)
28 .update(`${timestamp}:${rawBody}`)
29 .digest('hex');
30
31 const valid = crypto.timingSafeEqual(
32 Buffer.from(signature),
33 Buffer.from(expected)
34 );
35
36 if (!valid) {
37 return res.status(401).send('Invalid signature');
38 }
39
40 // Webhook is valid — process it
41 res.status(200).send('OK');
42});

Best Practices

  • check_circleAlways verify webhook signatures before processing any event.
  • check_circleUse timingSafeEqual to prevent timing attacks.
  • check_circleLog invalid signatures for security monitoring.
  • check_circleStore multiple versions of secrets if you rotate keys.
  • check_circleDo not parse or trust the webhook body until after signature validation.
  • check_circleEnsure your webhook endpoint is publicly reachable and uses HTTPS.