Kotlin/Java

A Kotlin/Java client library for interacting with the CloudContactAI API.

🔑

A Java client library for interacting with the CloudContactAI API using Spring Boot.

Prerequisites

To get the most out of this guide, you'll need to:

  • Sign up for a CCAI Trial Account here
  • Get your Client ID from Account\Settings
  • Create\Copy an API Key from Account Settings

1. Install

Maven

Add the following dependency to your pom.xml :

<dependency>
    <groupId>com.cloudcontactai</groupId>
    <artifactId>ccai-java</artifactId>
    <version>1.0.5</version>
</dependency>

Gradle

Add the following to your build.gradle:

implementation 'com.cloudcontactai:ccai-java:1.0.5'

2. Configuration

Set environment variables or pass configuration directly:

export CCAI_CLIENT_ID=1231
export CCAI_API_KEY=your-api-key-here
export CCAI_USE_TEST_ENVIRONMENT=false

3. Usage

Springboot Integration

Configuration Bean

@Configuration
class CCAIConfiguration {
    
    @Bean
    fun ccaiConfig(
        @Value("\${ccai.client-id}") clientId: String,
        @Value("\${ccai.api-key}") apiKey: String,
        @Value("\${ccai.use-test-environment:false}") useTestEnvironment: Boolean
    ): CCAIConfig {
        return CCAIConfig(
            clientId = clientId,
            apiKey = apiKey,
            useTestEnvironment = useTestEnvironment
        )
    }
    
    @Bean
    fun ccaiClient(config: CCAIConfig): CCAIClient {
        return CCAIClient(config)
    }
}

Service Bean

@Service
class NotificationService(private val ccaiClient: CCAIClient) {
    
    fun sendWelcomeSMS(firstName: String, lastName: String, phone: String) {
        val response = ccaiClient.sms.sendSingle(
            firstName = firstName,
            lastName = lastName,
            phone = phone,
            message = "Welcome ${firstName}! Thanks for joining our service.",
            title = "Welcome SMS"
        )
        println("SMS sent with ID: ${response.id}")
    }
    
    fun sendWelcomeEmail(firstName: String, lastName: String, email: String) {
        val response = ccaiClient.email.sendSingle(
            firstName = firstName,
            lastName = lastName,
            email = email,
            subject = "Welcome ${firstName}!",
            htmlContent = """
                <html>
                    <body>
                        <h1>Welcome ${firstName} ${lastName}!</h1>
                        <p>Thank you for joining our service.</p>
                    </body>
                </html>
            """.trimIndent()
        )
        println("Email sent with ID: ${response.id}")
    }
}

Application Properties

ccai.client-id=${CCAI_CLIENT_ID}
ccai.api-key=${CCAI_API_KEY}
ccai.use-test-environment=false

Koltin Usage

SMS Basic Usage

import com.cloudcontactai.sdk.CCAIClient
import com.cloudcontactai.sdk.common.CCAIConfig
import com.cloudcontactai.sdk.sms.Account

// Initialize the client
val config = CCAIConfig(
    clientId = System.getenv("CCAI_CLIENT_ID") ?: throw IllegalArgumentException("CCAI_CLIENT_ID not found"),
    apiKey = System.getenv("CCAI_API_KEY") ?: throw IllegalArgumentException("CCAI_API_KEY not found")
)

val ccai = CCAIClient(config)

// Send a single SMS
val response = ccai.sms.sendSingle(
    firstName = "John",
    lastName = "Doe",
    phone = "+15551234567",
    message = "Hello John, this is a test message!",
    title = "Test Campaign"
)

println("Message sent with ID: ${response.id}")

// Send to multiple recipients
val accounts = listOf(
    Account(
        firstName = "John",
        lastName = "Doe",
        phone = "+15551234567"
    ),
    Account(
        firstName = "Jane",
        lastName = "Smith",
        phone = "+15559876543"
    )
)

val campaignResponse = ccai.sms.send(
    accounts = accounts,
    message = "Hello from our service!",
    title = "Bulk Test Campaign"
)

println("Campaign sent with ID: ${campaignResponse.id}")

ccai.close()

Email Usage

import com.cloudcontactai.sdk.email.EmailAccount

// Send a single email
val response = ccai.email.sendSingle(
    firstName = "John",
    lastName = "Doe",
    email = "[email protected]",
    subject = "Welcome John!",
    htmlContent = "<h1>Hello John Doe!</h1><p>Welcome to our service.</p>"
)

println("Email sent with ID: ${response.id}")

// Send email campaign
val emailAccounts = listOf(
    EmailAccount(
        firstName = "John",
        lastName = "Doe",
        email = "[email protected]"
    ),
    EmailAccount(
        firstName = "Jane",
        lastName = "Smith",
        email = "[email protected]"
    )
)

val campaignResponse = ccai.email.send(
    accounts = emailAccounts,
    subject = "Newsletter",
    htmlContent = "<h1>Hello!</h1><p>Here's your newsletter.</p>"
)

println("Email campaign sent with ID: ${campaignResponse.id}")

MMS Usage


Image Recommendations

For optimal MMS delivery and performance:

Dimensions:

  • Recommended: 640px × 1138px (9:16 aspect ratio)
  • Alternative: 1080px × 1920px (9:16 aspect ratio)
  • Format: Portrait or square orientation preferred

File Size:

  • Target: ~200 KB (optimal for speed and deliverability)
  • Maximum: 1 MB
  • Use image compression tools to reduce file size while maintaining quality

Supported Formats:

  • JPEG (recommended)****
  • PNG
  • GIF

Best Practice: Keep images under 500 KB with 640×1138px dimensions for optimal compatibility and performance.

Code Examples

import com.cloudcontactai.sdk.mms.Account
import java.io.File

// Send MMS with automatic image upload (recommended)
val mmsAccounts = listOf(
    Account(
        firstName = "John",
        lastName = "Doe",
        phone = "+15551234567"
    )
)

val imageFile = File("path/to/image.jpg")
val mmsResponse = ccai.mms.sendWithImage(
    accounts = mmsAccounts,
    message = "Check out this image!",
    title = "MMS Campaign",
    imageFile = imageFile
)

// Response ID may be in campaignId or id field
val responseId = mmsResponse.campaignId ?: mmsResponse.id
println("MMS sent with ID: ${responseId}")

Webhook Management

import com.cloudcontactai.sdk.webhook.WebhookRequest

// Create a webhook (auto-generated secret)
val webhook = ccai.webhook.create(WebhookRequest("https://your-app.com/webhooks/ccai"))
println("Webhook created with ID: ${webhook.id}")
println("URL: ${webhook.url}")
println("Secret Key: ${webhook.secretKey}")

// Create a webhook with custom secret
val customWebhook = ccai.webhook.create(
    WebhookRequest("https://your-app.com/webhooks/ccai", "my-custom-secret-32chars12345")
)
println("Webhook created with custom secret!")

// Get the webhook
val webhookDetails = ccai.webhook.get()
webhookDetails?.let {
    println("Current webhook URL: ${it.url}")
    println("Method: ${it.method}")
    println("Secret Key: ${it.secretKey}")
}

// Update webhook
val updated = ccai.webhook.update(
    WebhookRequest("https://your-app.com/webhooks/ccai-updated", "my-custom-secret-32chars12345")
)
println("Webhook updated to: ${updated.url}")

// Validate CloudContactAI webhook signature (using eventHash)
val payload = """
{
    "eventType": "sms.sent",
    "data": {
        "id": 12345,
        "MessageStatus": "sent",
        "To": "+15551234567",
        "Message": "Hello World"
    },
    "eventHash": "abc123def456ghi789jkl012mno345pq"
}
"""
val signature = request.getHeader("X-CCAI-Signature")
val event = ccai.webhook.parseWebhookEvent(payload)

val isValid = ccai.webhook.validateSignature(
    signature,
    webhook.secretKey!!,
    config.clientId.toLong(),
    event.eventHash
)

if (isValid) {
    println("Event type: ${event.eventType}")
    println("Event hash: ${event.eventHash}")
    println("Data: ${event.data}")
}

Java Usage

import com.cloudcontactai.sdk.CCAIClient;
import com.cloudcontactai.sdk.common.CCAIConfig;
import com.cloudcontactai.sdk.sms.SMSResponse;

// Initialize the client
CCAIConfig config = new CCAIConfig(
    System.getenv("CCAI_CLIENT_ID"),
    System.getenv("CCAI_API_KEY"),
    false  // useTestEnvironment
);

CCAIClient ccai = new CCAIClient(config);

// Send SMS
SMSResponse response = ccai.getSms().sendSingle(
    "John",
    "Doe", 
    "+15551234567",
    "Hello John, this is a test message!",
    "Test Campaign",
    null  // optional sender phone
);

System.out.println("Message sent with ID: " + response.getId());

ccai.close();

4. Configuration Options

The CCAIConfig class supports the following options:

  • clientId: Your CCAI client ID (required)
  • apiKey: Your CCAI API key (required)
  • useTestEnvironment: Whether to use test environment URLs (default: false)
  • debugMode: Enable debug logging (default: false)
  • maxRetries: Maximum retry attempts for failed requests (default: 3)
  • timeoutMs: Request timeout in milliseconds (default: 30000)

The SDK automatically configures the following URLs based on useTestEnvironment:

  • baseUrl: SMS/MMS API endpoint
  • emailBaseUrl: Email API endpoint
  • authBaseUrl: Authentication API endpoint
  • filesBaseUrl: File upload API endpoint (for MMS)

5. Error Handling

The SDK throws CCAIException for API errors:

try {
    val response = ccai.sms.sendSingle(
        firstName = "John",
        lastName = "Doe",
        phone = "invalid-phone",
        message = "Test message",
        title = "Test"
    )
} catch (e: CCAIException) {
    println("API Error: ${e.message}")
}

6. Building from Source

git clone https://github.com/cloudcontactai/ccai-java-sdk.git
cd ccai-java-sdk
mvn clean install

7. Testing

mvn test

8. License

This project is licensed under the MIT License - see the LICENSE file for details.

9. Contact Validator

Validate email addresses and phone numbers.

Bulk endpoints accept up to 50 contacts per request and are processed server-side in chunks.

import com.cloudcontactai.sdk.contactvalidator.PhoneInput

// Validate a single email
val emailResult = ccai.contactValidator.validateEmail("[email protected]")
println(emailResult.status) // "valid" | "invalid" | "risky"

// Validate multiple emails (up to 50)
val bulkEmails = ccai.contactValidator.validateEmails(listOf(
    "[email protected]",
    "[email protected]"
))
println("Total: ${bulkEmails.summary.total}")
println("Valid: ${bulkEmails.summary.valid}")

// Validate a single phone number
val phoneResult = ccai.contactValidator.validatePhone("+15551234567", countryCode = "US")
println(phoneResult.status) // "valid" | "invalid" | "landline"

// Validate multiple phone numbers (up to 50)
val bulkPhones = ccai.contactValidator.validatePhones(listOf(
    PhoneInput(phone = "+15551234567"),
    PhoneInput(phone = "+15559876543", countryCode = "US")
))
println("Landline: ${bulkPhones.summary.landline}")

10. Brand Registration

Register and manage brands for TCR verification.

import com.cloudcontactai.sdk.brands.BrandRequest

// Create a brand
val brand = ccai.brands.create(BrandRequest(
    legalCompanyName = "Your Company LLC",
    entityType = "PRIVATE_PROFIT",
    taxId = "123456789",
    taxIdCountry = "US",
    country = "US",
    verticalType = "TECHNOLOGY",
    websiteUrl = "https://www.yourcompany.com",
    street = "123 Main St",
    city = "San Francisco",
    state = "CA",
    postalCode = "94105",
    contactFirstName = "Jane",
    contactLastName = "Smith",
    contactEmail = "[email protected]",
    contactPhone = "+14155551234"
))
println("Brand created with ID: ${brand.id}")

// List all brands
val brands = ccai.brands.list()
println("Total brands: ${brands.size}")

// Get a brand
val fetched = ccai.brands.get(brand.id)
println("Brand name: ${fetched.legalCompanyName}")

// Update a brand
ccai.brands.update(brand.id, BrandRequest(
    street = "456 Oak Avenue",
    city = "Los Angeles"
))

// Delete a brand
ccai.brands.delete(brand.id)

Entity Types: PRIVATE_PROFIT, PUBLIC_PROFIT, NON_PROFIT, GOVERNMENT, SOLE_PROPRIETOR

Vertical Types: AUTOMOTIVE, AGRICULTURE, BANKING, COMMUNICATION, CONSTRUCTION, EDUCATION, ENERGY, ENTERTAINMENT, GOVERNMENT, HEALTHCARE, HOSPITALITY, INSURANCE, LEGAL, MANUFACTURING, NON_PROFIT, PROFESSIONAL, REAL_ESTATE, RETAIL, TECHNOLOGY, TRANSPORTATION

11. Campaign Registration

Register and manage campaigns for TCR carrier vetting.

import com.cloudcontactai.sdk.campaigns.CampaignRequest

// Create a campaign
val campaign = ccai.campaigns.create(CampaignRequest(
    brandId = brand.id,
    useCase = "MARKETING",
    description = "Promotional messages for opted-in customers",
    messageFlow = "Users opt-in via web form and receive promotional SMS",
    hasEmbeddedLinks = true,
    hasEmbeddedPhone = false,
    isAgeGated = false,
    isDirectLending = false,
    optInKeywords = listOf("START", "YES"),
    optInMessage = "Welcome! Reply STOP to cancel.",
    optInProofUrl = "https://www.yourcompany.com/sms-opt-in",
    helpKeywords = listOf("HELP"),
    helpMessage = "Reply HELP for assistance. Contact [email protected].",
    optOutKeywords = listOf("STOP", "CANCEL"),
    optOutMessage = "STOP received. You are unsubscribed.",
    sampleMessages = listOf(
        "Hi Jane, check out our deals at https://example.com. Reply STOP to opt out.",
        "Your order has shipped! Reply HELP for help."
    )
))
println("Campaign created with ID: ${campaign.id}")

// List all campaigns
val campaigns = ccai.campaigns.list()
println("Total campaigns: ${campaigns.size}")

// Update a campaign
ccai.campaigns.update(campaign.id, CampaignRequest(
    description = "Updated description."
))

// Delete a campaign
ccai.campaigns.delete(campaign.id)

Use Cases: TWO_FACTOR_AUTHENTICATION, ACCOUNT_NOTIFICATION, CUSTOMER_CARE, DELIVERY_NOTIFICATION, FRAUD_ALERT, HIGHER_EDUCATION, LOW_VOLUME_MIXED, MARKETING, MIXED, POLLING_VOTING, PUBLIC_SERVICE_ANNOUNCEMENT, SECURITY_ALERT

Try it Yourself

See the full source code here.


Did this page help you?