Skip to main content

Code Examples

Practical code examples for common integration scenarios.

Customer Management

Create Customer with WeChat Integration

// Create customer and link WeChat account
async function createCustomerWithWeChat(wechatCode, customerData) {
const response = await fetch('https://api.sbmcrm.example.com/v1/customers', {
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
...customerData,
wechat: {
code: wechatCode
}
})
});

if (!response.ok) {
const error = await response.json();
throw new Error(error.error.message);
}

return await response.json();
}

Update Customer Tier

async function upgradeCustomerTier(customerId, newTier) {
const response = await fetch(
`https://api.sbmcrm.example.com/v1/customers/${customerId}/tier`,
{
method: 'PATCH',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
tier: newTier,
reason: 'Points threshold reached'
})
}
);

return await response.json();
}

Get Customer with Full Profile

async function getCustomerProfile(customerId) {
const response = await fetch(
`https://api.sbmcrm.example.com/v1/customers/${customerId}?include=points,tier,rewards,campaigns`,
{
headers: {
'Authorization': `Bearer ${accessToken}`
}
}
);

return await response.json();
}

Points Management

Award Points for Purchase

async function awardPointsForPurchase(customerId, transaction) {
const response = await fetch(
`https://api.sbmcrm.example.com/v1/customers/${customerId}/points/award`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
points: calculatePoints(transaction.amount, transaction.category),
reason: 'Purchase',
transaction_id: transaction.id,
metadata: {
store: transaction.store,
category: transaction.category
}
})
}
);

return await response.json();
}

function calculatePoints(amount, category) {
const rates = {
'fashion': 0.01, // 1 point per 100 CNY
'food': 0.005, // 0.5 points per 100 CNY
'default': 0.01
};

const rate = rates[category] || rates.default;
return Math.floor(amount * rate);
}

Redeem Points

async function redeemPoints(customerId, rewardId) {
const response = await fetch(
`https://api.sbmcrm.example.com/v1/customers/${customerId}/points/redeem`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
reward_id: rewardId
})
}
);

if (!response.ok) {
const error = await response.json();
throw new Error(error.error.message);
}

return await response.json();
}

Get Points History

async function getPointsHistory(customerId, filters = {}) {
const params = new URLSearchParams({
page: filters.page || 1,
limit: filters.limit || 20,
...(filters.type && { 'filter[type]': filters.type }),
...(filters.date_from && { date_from: filters.date_from }),
...(filters.date_to && { date_to: filters.date_to })
});

const response = await fetch(
`https://api.sbmcrm.example.com/v1/customers/${customerId}/points/history?${params}`,
{
headers: {
'Authorization': `Bearer ${accessToken}`
}
}
);

return await response.json();
}

Campaign Management

Create Campaign

async function createCampaign(campaignData) {
const response = await fetch('https://api.sbmcrm.example.com/v1/campaigns', {
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: campaignData.name,
description: campaignData.description,
start_date: campaignData.startDate,
end_date: campaignData.endDate,
target_segment: campaignData.segment,
reward_type: campaignData.rewardType,
reward_value: campaignData.rewardValue,
rules: campaignData.rules
})
});

return await response.json();
}

Get Campaign Participants

async function getCampaignParticipants(campaignId, page = 1) {
const response = await fetch(
`https://api.sbmcrm.example.com/v1/campaigns/${campaignId}/participants?page=${page}&limit=50`,
{
headers: {
'Authorization': `Bearer ${accessToken}`
}
}
);

return await response.json();
}

Join Campaign

async function joinCampaign(customerId, campaignId) {
const response = await fetch(
`https://api.sbmcrm.example.com/v1/campaigns/${campaignId}/join`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
customer_id: customerId
})
}
);

return await response.json();
}

Segmentation

Create Custom Segment

async function createSegment(segmentData) {
const response = await fetch('https://api.sbmcrm.example.com/v1/segments', {
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: segmentData.name,
description: segmentData.description,
filters: segmentData.filters,
auto_refresh: segmentData.autoRefresh || false
})
});

return await response.json();
}

// Example filters
const filters = {
and: [
{ field: 'tier', operator: 'equals', value: 'gold' },
{ field: 'points_balance', operator: 'greater_than', value: 1000 },
{ field: 'last_purchase_date', operator: 'within_days', value: 30 }
]
};

Get Segment Members

async function getSegmentMembers(segmentId, page = 1) {
const response = await fetch(
`https://api.sbmcrm.example.com/v1/segments/${segmentId}/members?page=${page}&limit=100`,
{
headers: {
'Authorization': `Bearer ${accessToken}`
}
}
);

return await response.json();
}

Notifications

Send Push Notification

async function sendNotification(customerIds, notificationData) {
const response = await fetch('https://api.sbmcrm.example.com/v1/notifications/send', {
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
customer_ids: customerIds,
title: notificationData.title,
body: notificationData.body,
image: notificationData.image,
action_url: notificationData.actionUrl,
channel: 'wechat_mini_program'
})
});

return await response.json();
}

Batch Operations

Batch Award Points

async function batchAwardPoints(awards) {
const response = await fetch('https://api.sbmcrm.example.com/v1/points/batch-award', {
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
awards: awards.map(award => ({
customer_id: award.customerId,
points: award.points,
reason: award.reason,
transaction_id: award.transactionId
}))
})
});

return await response.json();
}

Error Handling Wrapper

class SBMCRMClient {
constructor(apiKey, baseURL = 'https://api.sbmcrm.example.com/v1') {
this.apiKey = apiKey;
this.baseURL = baseURL;
}

async request(endpoint, options = {}) {
const url = `${this.baseURL}${endpoint}`;
const config = {
...options,
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
...options.headers
}
};

try {
const response = await fetch(url, config);

if (!response.ok) {
const error = await response.json();
throw new SBMCRMError(error.error, response.status);
}

return await response.json();
} catch (error) {
if (error instanceof SBMCRMError) {
throw error;
}
throw new Error(`Network error: ${error.message}`);
}
}

async get(endpoint) {
return this.request(endpoint, { method: 'GET' });
}

async post(endpoint, data) {
return this.request(endpoint, {
method: 'POST',
body: JSON.stringify(data)
});
}

async patch(endpoint, data) {
return this.request(endpoint, {
method: 'PATCH',
body: JSON.stringify(data)
});
}

async delete(endpoint) {
return this.request(endpoint, { method: 'DELETE' });
}
}

class SBMCRMError extends Error {
constructor(error, status) {
super(error.message);
this.name = 'SBMCRMError';
this.code = error.code;
this.status = status;
this.details = error.details;
}
}

// Usage
const client = new SBMCRMClient(process.env.API_KEY);

try {
const customer = await client.get('/customers/12345');
} catch (error) {
if (error instanceof SBMCRMError) {
console.error(`API Error [${error.code}]: ${error.message}`);
} else {
console.error('Unexpected error:', error);
}
}

Python Examples

Customer Management

import requests
from typing import Optional, Dict, Any

class SBMCRMClient:
def __init__(self, api_key: str, base_url: str = "https://api.sbmcrm.example.com/v1"):
self.api_key = api_key
self.base_url = base_url
self.headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}

def _request(self, method: str, endpoint: str, data: Optional[Dict] = None):
url = f"{self.base_url}{endpoint}"
response = requests.request(
method,
url,
headers=self.headers,
json=data
)
response.raise_for_status()
return response.json()

def get_customer(self, customer_id: str) -> Dict[str, Any]:
return self._request("GET", f"/customers/{customer_id}")

def create_customer(self, customer_data: Dict[str, Any]) -> Dict[str, Any]:
return self._request("POST", "/customers", customer_data)

def award_points(self, customer_id: str, points: int, reason: str) -> Dict[str, Any]:
return self._request("POST", f"/customers/{customer_id}/points/award", {
"points": points,
"reason": reason
})

# Usage
client = SBMCRMClient(api_key="your_api_key")
customer = client.get_customer("12345")