Creating Customers
This detailed guide explains how to onboard customers using the Nue Lifecycle Management API, covering single and bulk operations, advanced billing settings, enterprise features, and complete error handling. Learn how to efficiently onboard customers with full data validation and integration capabilities.
Prerequisites
Before you begin, ensure you have:
- A valid Nue API key with customer creation permissions
- Understanding of customer data requirements and validation rules
- Basic knowledge of REST APIs and JSON
- Familiarity with your business's customer onboarding process
- Knowledge of batch processing limits (200 customers per request)
- Understanding of your integration requirements (Salesforce, Stripe, etc.)
Authentication
All customer creation operations require authentication using your Nue API key in the nue-api-key header:
const myHeaders = new Headers();
myHeaders.append("nue-api-key", "YOUR_API_KEY_HERE");
myHeaders.append("Content-Type", "application/json");Basic Customer Creation
Create Single Customer
Try it now: Create Customers ā
const myHeaders = new Headers();
myHeaders.append("nue-api-key", "YOUR_API_KEY_HERE");
myHeaders.append("Content-Type", "application/json");
// Create a single customer with required fields
const customerData = [{
name: "Acme Corporation",
recordType: "Consumer" // Required: "Consumer" or "Business"
}];
fetch('https://api.nue.io/customers', {
method: 'POST',
headers: myHeaders,
body: JSON.stringify(customerData)
})
.then(response => response.json())
.then(result => {
if (result.status === 'SUCCESS') {
console.log('ā
Customer created successfully');
const customer = result.data[0];
console.log(`Created: ${customer.name}`);
console.log(`Customer ID: ${customer.id}`);
console.log(`Account Number: ${customer.accountNumber}`);
console.log(`Created Date: ${customer.createdDate}`);
// Check for warnings
if (result.warnings && result.warnings.length > 0) {
console.log('ā ļø Warnings:', result.warnings);
}
} else {
console.error('ā Customer creation failed:', result);
}
})
.catch(error => console.log('Error:', error));Create Customer with Complete Information
Create a customer with comprehensive business and billing details:
const comprehensiveCustomer = [{
// Required fields
name: "TechStart Solutions Inc.",
recordType: "Business",
// Business information
legalEntityName: "TechStart Solutions Incorporated",
industry: "Technology",
annualRevenue: 5000000.00,
description: "Leading technology solutions provider",
funding: "500000",
type: "Customer", // Customer, Prospect, Partner
accountSource: "Web", // Web, Phone, Email, Referral
// Contact information
email: "[email protected]",
phone: "+1-555-0123",
fax: "+1-555-0124",
website: "https://techstart-solutions.com",
timezone: "America/New_York",
// Billing configuration
billCycleDay: "1st of Month", // "1st of Month", "7th of Month", "15th of Month", "Last Day of Month"
billCycleStartMonth: "01",
autoRenew: "Yes",
billingPeriod: "Monthly", // Monthly, Quarterly, Annual
billingProrationEnabled: "Yes",
// Billing address
billingStreet: "123 Tech Street",
billingCity: "San Francisco",
billingState: "CA",
billingPostalCode: "94105",
billingCountry: "United States",
// Shipping address (if different)
shippingStreet: "456 Innovation Ave",
shippingCity: "Palo Alto",
shippingState: "CA",
shippingPostalCode: "94301",
shippingCountry: "United States",
// Additional information
description: "Enterprise software company specializing in AI solutions",
accountSource: "Web"
}];
fetch('https://api.nue.io/customers', {
method: 'POST',
headers: myHeaders,
body: JSON.stringify(comprehensiveCustomer)
})
.then(response => response.json())
.then(result => {
console.log('Comprehensive customer created:', result);
const customer = result[0];
console.log(`\nā
Customer Created Successfully`);
console.log(`Name: ${customer.name}`);
console.log(`ID: ${customer.id}`);
console.log(`Account Number: ${customer.accountNumber}`);
console.log(`Industry: ${customer.industry}`);
console.log(`Bill Cycle: Day ${customer.billCycleDay} of each month`);
console.log(`Payment Method: ${customer.paymentMethod}`);
console.log(`Auto Renew: ${customer.autoRenew}`);
})
.catch(error => console.log('Error:', error));Bulk Customer Creation
Create Multiple Customers
Efficiently create multiple customers in a single API call:
const bulkCustomers = [
{
name: "Global Enterprises LLC",
recordType: "business",
industry: "Manufacturing",
email: "[email protected]",
billCycleDay: 15,
paymentMethod: "ACH",
billingStreet: "789 Industrial Blvd",
billingCity: "Detroit",
billingState: "MI",
billingPostalCode: "48201",
billingCountry: "United States"
},
{
name: "StartUp Innovations",
recordType: "business",
industry: "Technology",
email: "[email protected]",
billCycleDay: 1,
paymentMethod: "Credit Card",
billingStreet: "321 Startup Way",
billingCity: "Austin",
billingState: "TX",
billingPostalCode: "73301",
billingCountry: "United States"
},
{
name: "John Smith",
recordType: "consumer",
email: "[email protected]",
phone: "+1-555-0199",
billCycleDay: 1,
paymentMethod: "Credit Card",
billingStreet: "456 Main Street",
billingCity: "Denver",
billingState: "CO",
billingPostalCode: "80202",
billingCountry: "United States"
}
];
fetch('https://api.nue.io/customers', {
method: 'POST',
headers: myHeaders,
body: JSON.stringify(bulkCustomers)
})
.then(response => response.json())
.then(customers => {
console.log(`\nā
Successfully created ${customers.length} customers:`);
customers.forEach((customer, index) => {
console.log(`\n${index + 1}. ${customer.name}`);
console.log(` ID: ${customer.id}`);
console.log(` Account: ${customer.accountNumber}`);
console.log(` Type: ${customer.recordType}`);
console.log(` Email: ${customer.email}`);
console.log(` Billing: Day ${customer.billCycleDay} via ${customer.paymentMethod}`);
});
})
.catch(error => console.log('Error:', error));Advanced Customer Creation Patterns
Customer Onboarding Workflow
Implement a complete customer onboarding process:
class CustomerOnboardingService {
constructor(apiKey) {
this.apiKey = apiKey;
this.headers = new Headers();
this.headers.append("nue-api-key", apiKey);
this.headers.append("Content-Type", "application/json");
}
async onboardNewCustomer(customerInput) {
try {
// Step 1: Validate customer data
const validatedData = this.validateCustomerData(customerInput);
// Step 2: Enrich with defaults
const enrichedData = this.enrichCustomerData(validatedData);
// Step 3: Create customer
const createdCustomer = await this.createCustomer(enrichedData);
// Step 4: Set up additional configurations
await this.setupCustomerConfigurations(createdCustomer);
// Step 5: Send welcome communications
await this.sendWelcomeEmail(createdCustomer);
return {
success: true,
customer: createdCustomer,
message: `Customer ${createdCustomer.name} onboarded successfully`
};
} catch (error) {
console.error('Onboarding failed:', error);
return {
success: false,
error: error.message,
customerInput
};
}
}
validateCustomerData(input) {
const errors = [];
// Required field validation
if (!input.name || input.name.trim().length === 0) {
errors.push('Customer name is required');
}
if (!input.recordType || !['consumer', 'business'].includes(input.recordType)) {
errors.push('Record type must be "consumer" or "business"');
}
// Email validation
if (input.email && !this.isValidEmail(input.email)) {
errors.push('Invalid email format');
}
// Bill cycle day validation
if (input.billCycleDay && (input.billCycleDay < 1 || input.billCycleDay > 31)) {
errors.push('Bill cycle day must be between 1 and 31');
}
if (errors.length > 0) {
throw new Error(`Validation failed: ${errors.join(', ')}`);
}
return input;
}
enrichCustomerData(input) {
// Apply business defaults
const enriched = {
...input,
// Default billing configuration
billCycleDay: input.billCycleDay || 1,
paymentTerm: input.paymentTerm || "Net 30",
autoRenew: input.autoRenew || "DefaultToSubscriptionConfiguration",
billingProrationEnabled: input.billingProrationEnabled || "Yes",
taxExempt: input.taxExempt || "none",
accountSource: input.accountSource || "API",
// Set timezone if not provided
timezone: input.timezone || this.getDefaultTimezone(input.billingState),
// Set industry for business customers
industry: input.recordType === 'business' ?
(input.industry || 'Other') :
undefined
};
return enriched;
}
async createCustomer(customerData) {
const response = await fetch('https://api.nue.io/customers', {
method: 'POST',
headers: this.headers,
body: JSON.stringify([customerData])
});
if (!response.ok) {
throw new Error(`Customer creation failed: ${response.status} ${response.statusText}`);
}
const customers = await response.json();
return customers[0];
}
async setupCustomerConfigurations(customer) {
// Additional setup steps could include:
// - Setting up payment methods
// - Configuring billing preferences
// - Creating default contacts
// - Setting up integrations
console.log(`Setting up configurations for ${customer.name}...`);
// Example: Log setup completion
console.log(`ā
Configurations completed for account ${customer.accountNumber}`);
}
async sendWelcomeEmail(customer) {
// Integration with email service
console.log(`š§ Sending welcome email to ${customer.email}...`);
// Mock email service integration
const emailData = {
to: customer.email,
subject: `Welcome to Nue, ${customer.name}!`,
template: 'customer_welcome',
data: {
customerName: customer.name,
accountNumber: customer.accountNumber,
billCycleDay: customer.billCycleDay,
paymentMethod: customer.paymentMethod
}
};
// In real implementation, integrate with your email service
console.log(`ā
Welcome email queued for ${customer.email}`);
}
isValidEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
getDefaultTimezone(state) {
const timezoneMap = {
'CA': 'America/Los_Angeles',
'NY': 'America/New_York',
'TX': 'America/Chicago',
'FL': 'America/New_York',
'IL': 'America/Chicago'
};
return timezoneMap[state] || 'America/New_York';
}
}
// Usage example
const onboardingService = new CustomerOnboardingService("YOUR_API_KEY_HERE");
const newCustomerData = {
name: "Innovative Solutions Corp",
recordType: "business",
industry: "Consulting",
email: "[email protected]",
phone: "+1-555-0150",
annualRevenue: 2500000,
numberOfEmployees: 25,
billingStreet: "100 Business Plaza",
billingCity: "Seattle",
billingState: "WA",
billingPostalCode: "98101",
billingCountry: "United States",
billCycleDay: 15,
paymentMethod: "ACH"
};
onboardingService.onboardNewCustomer(newCustomerData)
.then(result => {
if (result.success) {
console.log('\nš Customer onboarding completed successfully!');
console.log(`Customer: ${result.customer.name}`);
console.log(`Account: ${result.customer.accountNumber}`);
console.log(`ID: ${result.customer.id}`);
} else {
console.error('ā Onboarding failed:', result.error);
}
});Customer Creation with Validation
Implement comprehensive validation and error handling:
class CustomerValidator {
static validate(customerData) {
const errors = [];
// Required fields
if (!customerData.name?.trim()) {
errors.push('name: Customer name is required');
}
if (!['consumer', 'business'].includes(customerData.recordType)) {
errors.push('recordType: Must be "consumer" or "business"');
}
// Email validation
if (customerData.email && !this.isValidEmail(customerData.email)) {
errors.push('email: Invalid email format');
}
// Phone validation
if (customerData.phone && !this.isValidPhone(customerData.phone)) {
errors.push('phone: Invalid phone format');
}
// Business-specific validations
if (customerData.recordType === 'business') {
if (customerData.annualRevenue && customerData.annualRevenue < 0) {
errors.push('annualRevenue: Must be a positive number');
}
if (customerData.numberOfEmployees && customerData.numberOfEmployees < 1) {
errors.push('numberOfEmployees: Must be at least 1');
}
}
// Billing validations
if (customerData.billCycleDay && (customerData.billCycleDay < 1 || customerData.billCycleDay > 31)) {
errors.push('billCycleDay: Must be between 1 and 31');
}
// Address validation
if (customerData.billingStreet && !customerData.billingCity) {
errors.push('billingCity: Required when billing street is provided');
}
return {
isValid: errors.length === 0,
errors
};
}
static isValidEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
static isValidPhone(phone) {
const phoneRegex = /^\+?[\d\s\-\(\)]{10,}$/;
return phoneRegex.test(phone);
}
}
async function createValidatedCustomer(customerData) {
const myHeaders = new Headers();
myHeaders.append("nue-api-key", "YOUR_API_KEY_HERE");
myHeaders.append("Content-Type", "application/json");
try {
// Validate input data
const validation = CustomerValidator.validate(customerData);
if (!validation.isValid) {
throw new Error(`Validation failed:\n${validation.errors.join('\n')}`);
}
// Create customer
const response = await fetch('https://api.nue.io/customers', {
method: 'POST',
headers: myHeaders,
body: JSON.stringify([customerData])
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`API Error ${response.status}: ${errorText}`);
}
const customers = await response.json();
const customer = customers[0];
console.log('ā
Customer created and validated successfully:');
console.log(` Name: ${customer.name}`);
console.log(` ID: ${customer.id}`);
console.log(` Account: ${customer.accountNumber}`);
return customer;
} catch (error) {
console.error('ā Customer creation failed:', error.message);
throw error;
}
}
// Usage with validation
const customerToCreate = {
name: "Valid Business Corp",
recordType: "business",
email: "[email protected]",
phone: "+1-555-0100",
industry: "Technology",
billCycleDay: 1,
billingStreet: "123 Valid Street",
billingCity: "Valid City",
billingState: "CA",
billingPostalCode: "90210",
billingCountry: "United States"
};
createValidatedCustomer(customerToCreate)
.then(customer => {
console.log('Customer ready for use:', customer.id);
})
.catch(error => {
console.log('Handle creation failure appropriately');
});Request Body Schema
Required Fields
Field | Type | Description | Options/Format |
|---|---|---|---|
name | String | Customer name (max 255 chars) | "Acme Corporation" |
recordType | String | Customer type | "Consumer" or "Business" |
Business Information Fields
Field | Type | Description | Options/Format |
|---|---|---|---|
legalEntityName | String | Legal entity name | Max 255 characters |
industry | String | Industry classification | See industry options below |
annualRevenue | Number | Annual revenue amount | Positive decimal number |
description | String | Customer description | Free text |
funding | String | Funding amount | Numeric string |
type | String | Customer classification | Customer, Prospect, Partner |
accountSource | String | Lead source | Web, Phone, Email, Referral |
site | String | Site information | Free text |
Contact Information Fields
Field | Type | Description | Format |
|---|---|---|---|
String | Primary email | Valid email format | |
phone | String | Primary phone | International format recommended |
fax | String | Fax number | International format |
website | String | Company website | Valid URL format |
timezone | String | Customer timezone | IANA timezone identifier |
imageSignedUrl | String | Profile image URL | Signed URL (read-only) |
Billing Configuration Fields
Field | Type | Description | Options |
|---|---|---|---|
billCycleDay | String | Day of month for billing | "1st of Month", "7th of Month", "15th of Month", "Last Day of Month" |
billCycleStartMonth | String | Starting month | "01" to "12" |
autoRenew | String | Auto-renewal setting | Yes, No, DefaultToSubscriptionConfiguration |
billingPeriod | String | Billing frequency | Monthly, Quarterly, Annual |
billingProrationEnabled | String | Enable proration | Yes, No |
Address Fields
Billing Address:
- billingStreet, billingCity, billingState, billingPostalCode, billingCountry
Shipping Address:
- shippingStreet, shippingCity, shippingState, shippingPostalCode, shippingCountry
Industry Options
Common industry values include:
- Technology
- Healthcare
- Financial Services
- Manufacturing
- Retail
- Education
- Government
- Non-profit
- Consulting
- Other
Response Structure
Success Response (201 Created)
{
"status": "SUCCESS",
"data": [
{
"accountNumber": "Z100293",
"accountSource": "Web",
"annualRevenue": 5000000.00,
"autoRenew": "Yes",
"billCycleDay": "7th of Month",
"billCycleStartMonth": "03",
"billingCity": "San Francisco",
"billingCountry": "US",
"billingPeriod": "Annual",
"billingPostalCode": "94005",
"billingProrationEnabled": "Yes",
"billingState": "CA",
"billingStreet": "123 Main Street",
"createdById": "3865c4c7-f233-4d7f-8426-2eb882856e5c",
"createdDate": "2025-06-27T23:23:53.002+00:00",
"description": "Some customer description",
"email": "[email protected]",
"fax": "+1-650-383-2838",
"funding": "500000",
"id": "c5786254-06a2-44fe-88d5-3dd5dad66e78",
"imageSignedUrl": "https://signedurl.io",
"industry": "Agriculture",
"lastModifiedById": "3865c4c7-f233-4d7f-8426-2eb882856e5c",
"lastModifiedDate": "2025-06-27T23:23:53.002+00:00",
"legalEntityName": "EntityName",
"name": "jadiceguyu",
"phone": "393-393-2939",
"recordType": "Consumer",
"shippingCity": "San Francisco",
"shippingCountry": "US",
"shippingPostalCode": "94005",
"shippingState": "CA",
"shippingStreet": "123 Main Street",
"site": "Website",
"timezone": "Pacific/Kiritimati",
"type": "Prospect",
"website": "https://url.com"
}
],
"warnings": []
}Error Handling
Complete Error Reference
The Customer API returns comprehensive error information to help you handle all scenarios:
Error Code | HTTP Status | Description | Resolution |
|---|---|---|---|
RESOURCE_NOT_FOUND | 404 | Customer not found | Verify customer ID exists |
DUPLICATE_RESOURCE | 409 | Customer already exists | Check for existing customer with same details |
REQUEST_SIZE_EXCEEDED | 400 | Batch limit exceeded | Reduce batch size (max 200 customers) |
MISSING_PARAMETER | 400 | Required field missing | Provide all required fields |
INVALID_FIELD_VALUE_FORMAT | 400 | Invalid field format | Check field format requirements |
RESERVED_FIELD | 400 | Attempting to modify reserved field | Remove reserved fields from request |
STRIPE_CUSTOMER_UPSERT_FAILED | 500 | Payment integration error | Check Stripe configuration |
CUSTOMER_NOT_MATCH | 400 | Customer mismatch | Verify customer relationships |
SALESFORCE_SYNC_FAILED | 500 | Salesforce integration error | Check Salesforce connection |
BATCH_PROCESSING_ERROR | 500 | Bulk operation failed | Retry with smaller batch |
VALIDATION_ERROR | 422 | Data validation failed | Review field constraints |
UNAUTHORIZED | 401 | Invalid API key | Verify API key and permissions |
RATE_LIMITED | 429 | Too many requests | Implement retry with exponential backoff |
Error Response Format
{
"status": "ERROR",
"error": {
"code": "MISSING_PARAMETER",
"message": "Required field 'name' is missing",
"details": {
"field": "name",
"requirement": "Customer name is required and cannot be empty"
}
}
}Validation Rules
Required Fields:
- name (String, max 255 characters)
- recordType ("Consumer" or "Business")
Field Constraints:
- email: Valid email format required
- billCycleDay: "1st of Month", "7th of Month", "15th of Month", or "Last Day of Month"
- billCycleStartMonth: "01" to "12"
- autoRenew: "Yes", "No", or "DefaultToSubscriptionConfiguration"
- billingPeriod: "Monthly", "Quarterly", or "Annual"
- timezone: Valid IANA timezone identifier
- annualRevenue: Positive number
- phone/fax: International format recommended
Batch Limits:
- Maximum 200 customers per request
- Requests exceeding limit return REQUEST_SIZE_EXCEEDED error
Advanced Features
Batch Processing
Create up to 200 customers in a single request for efficient bulk operations:
const batchCustomers = [
{
name: "Customer One",
recordType: "Business",
email: "[email protected]",
industry: "Technology"
},
{
name: "Customer Two",
recordType: "Consumer",
email: "[email protected]",
billingPeriod: "Monthly"
}
// ... up to 200 customers
];
fetch('https://api.nue.io/orders/customers', {
method: 'POST',
headers: myHeaders,
body: JSON.stringify(batchCustomers)
})
.then(response => response.json())
.then(result => {
if (result.status === 'SUCCESS') {
console.log(`ā
Created ${result.data.length} customers successfully`);
// Process each created customer
result.data.forEach((customer, index) => {
console.log(`${index + 1}. ${customer.name} (${customer.accountNumber})`);
});
}
});Enterprise Integrations
Salesforce Synchronization
Automatic bidirectional sync with Salesforce CRM:
// Create customer with Salesforce sync enabled
const salesforceCustomer = [{
name: "Enterprise Client Corp",
recordType: "Business",
email: "[email protected]",
// Salesforce integration fields
salesforceAccountId: "0013000000ABC123",
syncWithSalesforce: true,
salesforceOwner: "[email protected]"
}];Custom Fields Support
Store additional business-specific data using JSONB custom fields:
const customFieldsCustomer = [{
name: "Custom Data Corp",
recordType: "Business",
// Custom fields stored as JSONB
customFields: {
"crm_score": 85,
"lead_source": "trade_show",
"contract_type": "enterprise",
"renewal_probability": 0.92,
"custom_tags": ["high-value", "tech-sector"]
}
}];Revenue Analytics
Automatic calculation of key revenue metrics:
// Customer creation triggers automatic analytics
const analyticsCustomer = [{
name: "Analytics Customer",
recordType: "Business",
annualRevenue: 2500000.00,
// Analytics will automatically calculate:
// - Total Contract Value (TCV)
// - Annual Recurring Revenue (ARR)
// - Customer Monthly Recurring Revenue (CMRR)
// - Customer Lifetime Value (CLV)
}];Best Practices
Data Quality
- Validate input data before sending to API
- Use consistent formatting for phone numbers and addresses
- Set appropriate defaults for billing configuration
- Normalize business names for consistency
- Implement data deduplication to prevent duplicate customers
- Use custom fields for business-specific requirements
Performance
- Batch customer creation when possible (up to 200 per request)
- Implement retry logic with exponential backoff for transient failures
- Use distributed locking for concurrent operations
- Monitor rate limits and implement proper throttling
- Cache frequently accessed data to reduce API calls
- Use async processing for large batch operations
Security
- Validate all input data to prevent injection attacks
- Implement proper authentication and API key management
- Use tenant isolation to prevent cross-tenant data access
- Log all creation activities for comprehensive audit trails
- Implement proper error handling without exposing sensitive data
- Use HTTPS for all API communications
- Encrypt sensitive custom field data when necessary
Integration Best Practices
- Configure Salesforce sync for CRM integration
- Set up Stripe integration for payment processing
- Implement webhook handlers for real-time event processing
- Use GraphQL filtering for complex customer queries
- Monitor integration health and implement fallback mechanisms
- Handle integration failures gracefully with proper error recovery
This comprehensive guide enables you to efficiently create and onboard customers using the Nue Lifecycle Management API, supporting everything from simple customer creation to complex onboarding workflows.