ตัวแปรข้อความ
ใช้ตัวแปรเพื่อปรับแต่งข้อความ cascade ให้เป็นส่วนตัวด้วยเนื้อหาแบบไดนามิก เช่น ชื่อ, URL, และค่าที่กำหนดเอง.
ภาพรวม
ตัวแปรทำให้:
- Personalization: แทรกชื่อผู้รับ, หมายเลขบัญชี
- Dynamic URLs: รวมลิงก์ที่เป็นเอกลักษณ์สำหรับแต่ละผู้รับ
- URL Shortening: ย่อ URL ยาวโดยอัตโนมัติ
- Template Reusability: แม่แบบเดียว, ข้อความส่วนบุคคลหลายข้อความ
ประเภทตัวแปร
| Type | Syntax | Purpose | Example |
|---|---|---|---|
name | %name=id% | ตัวแปรข้อความ | ชื่อ, รหัส, จำนวน |
url | %url=id% | URL เต็ม | ลิงก์, URL ติดตาม |
short_url | %short_url=id% | URL ย่อ | ลิงก์แบบกะทัดรัด |
ไวยากรณ์ตัวแปร
ตัวแปรใช้รูปแบบ: %type=id%
- type: ประเภทตัวแปร (
name,url,short_url) - id: ตัวระบุที่ไม่ซ้ำ (จำนวนเต็ม)
ตัวอย่าง
Hello %name=1%, your code is %name=2%
Visit our website: %url=1%
Quick link: %short_url=1%
การใช้ตัวแปร
ขั้นตอนที่ 1: อัปโหลดค่าตัวแปร
ก่อนส่งข้อความ ให้อัปโหลดค่าตัวแปรไปยัง API:
จุดเชื่อมต่อ:
POST https://restapi.smsbat.com/api/items
คำขอ:
{
"variables": [
{
"id": 1,
"type": "name",
"value": "John"
},
{
"id": 2,
"type": "name",
"value": "12345"
},
{
"id": 3,
"type": "url",
"value": "https://example.com/products"
},
{
"id": 4,
"type": "short_url",
"value": "https://example.com/very-long-url-that-needs-shortening"
}
]
}
ขั้นตอนที่ 2: ส่งข้อความพร้อมตัวแปร
ใช้ ID ตัวแปรที่อัปโหลดในข้อความของคุณ:
{
"id": "msg-001",
"fromName": "YourStore",
"toPhone": "+380XXXXXXXXX",
"messageType": "transaction",
"text": "Hello %name=1%! Your verification code is %name=2%. Visit: %short_url=4%"
}
ผลลัพธ์:
Hello John! Your verification code is 12345. Visit: https://sho.rt/abc123
ตัวอย่างสมบูรณ์
อัปโหลดตัวแปร
curl -X POST https://restapi.smsbat.com/api/items \
-H "Content-Type: application/json" \
-H "X-Authorization-Key: your-api-key" \
-d '{
"variables": [
{
"id": 1,
"type": "name",
"value": "Sarah"
},
{
"id": 2,
"type": "name",
"value": "ORD-789"
},
{
"id": 3,
"type": "url",
"value": "https://example.com/track/ORD-789"
}
]
}'
ส่งข้อความ
curl -X POST https://restapi.smsbat.com/api/CascadeMessage/send_message/async \
-H "Content-Type: application/json" \
-H "X-Authorization-Key: your-api-key" \
-d '[
{
"id": "order-notification",
"fromName": "YourStore",
"toPhone": "+380XXXXXXXXX",
"messageType": "transaction",
"text": "Hi %name=1%! Order %name=2% shipped. Track: %url=3%"
}
]'
ข้อความที่ส่งแล้ว:
Hi Sarah! Order ORD-789 shipped. Track: https://example.com/track/ORD-789
กรณีการใช้งาน
การยืนยันคำสั่งซื้อ
// Variables
{
"variables": [
{"id": 1, "type": "name", "value": "John"},
{"id": 2, "type": "name", "value": "12345"},
{"id": 3, "type": "name", "value": "$99.99"},
{"id": 4, "type": "url", "value": "https://store.com/order/12345"}
]
}
// Message
{
"text": "Hi %name=1%! Order #%name=2% for %name=3% confirmed. Details: %url=4%"
}
// Result
"Hi John! Order #12345 for $99.99 confirmed. Details: https://store.com/order/12345"
การรีเซ็ตรหัสผ่าน
// Variables
{
"variables": [
{"id": 1, "type": "name", "value": "Mike"},
{"id": 2, "type": "short_url", "value": "https://app.example.com/reset?token=abc123def456"}
]
}
// Message
{
"text": "Hi %name=1%, reset your password: %short_url=2% (valid 30 min)"
}
// Result
"Hi Mike, reset your password: https://sho.rt/xyz789 (valid 30 min)"
แคมเปญส่งเสริมการขาย
// Variables
{
"variables": [
{"id": 1, "type": "name", "value": "VIP20"},
{"id": 2, "type": "short_url", "value": "https://store.com/sale?utm_source=sms&utm_campaign=summer"}
]
}
// Message
{
"text": "Summer Sale! Use code %name=1% for 20% off: %short_url=2%"
}
// Result
"Summer Sale! Use code VIP20 for 20% off: https://sho.rt/abc"
การยืนยันบัญชี
// Variables
{
"variables": [
{"id": 1, "type": "name", "value": "789456"},
{"id": 2, "type": "name", "value": "10"}
]
}
// Message
{
"text": "Your verification code: %name=1%. Valid for %name=2% minutes."
}
// Result
"Your verification code: 789456. Valid for 10 minutes."
ตัวอย่างการนำไปใช้
Python
import requests
class CascadeVariables:
def __init__(self, api_key):
self.base_url = 'https://restapi.smsbat.com'
self.headers = {
'Content-Type': 'application/json',
'X-Authorization-Key': api_key
}
def upload_variables(self, variables):
"""Upload variable values"""
response = requests.post(
f'{self.base_url}/api/items',
headers=self.headers,
json={'variables': variables}
)
response.raise_for_status()
return response.json()
def send_with_variables(self, tracking_id, from_name, to_phone,
message_type, text, variables):
"""Upload variables and send message"""
# Upload variables first
self.upload_variables(variables)
# Send message
message = {
'id': tracking_id,
'fromName': from_name,
'toPhone': to_phone,
'messageType': message_type,
'text': text
}
response = requests.post(
f'{self.base_url}/api/CascadeMessage/send_message/async',
headers=self.headers,
json=[message]
)
response.raise_for_status()
return response.json()[0]
# Usage
cascade = CascadeVariables('your-api-key')
# Define variables
variables = [
{'id': 1, 'type': 'name', 'value': 'John'},
{'id': 2, 'type': 'name', 'value': 'ORD-12345'},
{'id': 3, 'type': 'url', 'value': 'https://example.com/track/ORD-12345'}
]
# Send message with variables
result = cascade.send_with_variables(
tracking_id='order-notification',
from_name='YourStore',
to_phone='+380XXXXXXXXX',
message_type='transaction',
text='Hi %name=1%! Order %name=2% shipped. Track: %url=3%',
variables=variables
)
print(f"Message sent: {result['messageId']}")
JavaScript (Node.js)
const axios = require('axios');
class CascadeVariables {
constructor(apiKey) {
this.baseUrl = 'https://restapi.smsbat.com';
this.headers = {
'Content-Type': 'application/json',
'X-Authorization-Key': apiKey
};
}
async uploadVariables(variables) {
const response = await axios.post(
`${this.baseUrl}/api/items`,
{ variables },
{ headers: this.headers }
);
return response.data;
}
async sendWithVariables({ id, fromName, toPhone, messageType, text, variables }) {
// Upload variables first
await this.uploadVariables(variables);
// Send message
const response = await axios.post(
`${this.baseUrl}/api/CascadeMessage/send_message/async`,
[{
id,
fromName,
toPhone,
messageType,
text
}],
{ headers: this.headers }
);
return response.data[0];
}
}
// Usage
const cascade = new CascadeVariables('your-api-key');
const result = await cascade.sendWithVariables({
id: 'order-notification',
fromName: 'YourStore',
toPhone: '+380XXXXXXXXX',
messageType: 'transaction',
text: 'Hi %name=1%! Order %name=2% shipped. Track: %url=3%',
variables: [
{ id: 1, type: 'name', value: 'John' },
{ id: 2, type: 'name', value: 'ORD-12345' },
{ id: 3, type: 'url', value: 'https://example.com/track/ORD-12345' }
]
});
console.log('Message sent:', result.messageId);
PHP
<?php
class CascadeVariables {
private $baseUrl = 'https://restapi.smsbat.com';
private $apiKey;
public function __construct($apiKey) {
$this->apiKey = $apiKey;
}
public function uploadVariables($variables) {
$ch = curl_init($this->baseUrl . '/api/items');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'X-Authorization-Key: ' . $this->apiKey
]);
curl_setopt($ch, CURLOPT_POSTFIELDS,
json_encode(['variables' => $variables]));
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
public function sendWithVariables($id, $fromName, $toPhone,
$messageType, $text, $variables) {
// Upload variables
$this->uploadVariables($variables);
// Send message
$message = [
'id' => $id,
'fromName' => $fromName,
'toPhone' => $toPhone,
'messageType' => $messageType,
'text' => $text
];
$ch = curl_init(
$this->baseUrl . '/api/CascadeMessage/send_message/async'
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'X-Authorization-Key: ' . $this->apiKey
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([$message]));
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true);
return $result[0];
}
}
// Usage
$cascade = new CascadeVariables('your-api-key');
$variables = [
['id' => 1, 'type' => 'name', 'value' => 'John'],
['id' => 2, 'type' => 'name', 'value' => 'ORD-12345'],
['id' => 3, 'type' => 'url', 'value' => 'https://example.com/track/ORD-12345']
];
$result = $cascade->sendWithVariables(
'order-notification',
'YourStore',
'+380XXXXXXXXX',
'transaction',
'Hi %name=1%! Order %name=2% shipped. Track: %url=3%',
$variables
);
echo "Message sent: " . $result['messageId'] . "\n";
แนวทางปฏิบัติที่ดีที่สุด
ตัวแปร ID
- ✅ ใช้ ID ตามลำดับ (1, 2, 3, …)
- ✅ ใช้ ID ซ้ำสำหรับข้อความจำนวนมากที่มีตัวแปรเดียวกัน
- ✅ บันทึกการแมป ID ของตัวแปร
- ❌ อย่าใช้ ID แบบสุ่ม
- ❌ อย่าข้ามหมายเลข ID
ค่าตัวแปร
- ✅ ตรวจสอบค่าก่อนอัปโหลด
- ✅ จัดการอักขระพิเศษอย่างเหมาะสม
- ✅ ทดสอบกับกรณีขอบ
- ❌ อย่าใส่ HTML ในตัวแปรชื่อ
- ❌ อย่าเกินขีดจำกัดความยาวที่สมเหตุสมผล
ตัวแปร URL
- ✅ ใช้
short_urlสำหรับ URL ยาว - ✅ รวมพารามิเตอร์การติดตาม
- ✅ ใช้ HTTPS
- ❌ อย่าใช้ URL ที่ดูน่าสงสัย
- ❌ อย่าใส่ข้อมูลสำคัญใน URL
ประสิทธิภาพ
- อัปโหลดตัวแปรครั้งเดียว ส่งหลายข้อความ
- การอัปโหลดตัวแปรเป็นชุด
- แคชตัวแปรที่ใช้บ่อย
- ทำความสะอาดตัวแปรเก่าเป็นระยะ
แพทเทิร์นขั้นสูง
การปรับส่วนบุคคลแบบกลุ่ม
async function sendBulkPersonalized(recipients) {
const messages = [];
const variables = [];
let varId = 1;
recipients.forEach((recipient, index) => {
// Variables for this recipient
const nameVarId = varId++;
const orderVarId = varId++;
const urlVarId = varId++;
variables.push(
{ id: nameVarId, type: 'name', value: recipient.name },
{ id: orderVarId, type: 'name', value: recipient.orderId },
{ id: urlVarId, type: 'url', value: recipient.trackingUrl }
);
messages.push({
id: `order-${recipient.orderId}`,
fromName: 'YourStore',
toPhone: recipient.phone,
messageType: 'transaction',
text: `Hi %name=${nameVarId}%! Order %name=${orderVarId}% shipped. Track: %url=${urlVarId}%`
});
});
// Upload all variables
await uploadVariables(variables);
// Send all messages
return await sendBulk(messages);
}
ระบบเทมเพลต
class MessageTemplate {
constructor(template) {
this.template = template;
this.varIdCounter = 1;
}
create(data) {
const variables = [];
let text = this.template;
// Replace placeholders with variable syntax
Object.entries(data).forEach(([key, value]) => {
const varId = this.varIdCounter++;
variables.push({
id: varId,
type: this.getVarType(value),
value: value
});
text = text.replace(`{{${key}}}`, `%${this.getVarType(value)}=${varId}%`);
});
return { text, variables };
}
getVarType(value) {
if (value.startsWith('http')) return 'url';
return 'name';
}
}
// Usage
const template = new MessageTemplate(
'Hi {{name}}! Order {{orderId}} shipped. Track: {{trackUrl}}'
);
const { text, variables } = template.create({
name: 'John',
orderId: 'ORD-123',
trackUrl: 'https://example.com/track/ORD-123'
});
await sendWithVariables({ text, variables });
การแก้ไขปัญหา
ตัวแปรไม่ถูกแทนที่
- ตรวจสอบว่าตัวแปรถูกอัปโหลดก่อนส่ง
- ตรวจสอบว่า ID ตัวแปรตรงกันในข้อความและการอัปโหลด
- ตรวจสอบไวยากรณ์ที่ถูกต้อง:
%type=id% - ตรวจสอบว่าประเภทตัวแปรตรงกับค่า
การย่อ URL ล้มเหลว
- ตรวจสอบว่า URL ถูกต้องและเข้าถึงได้
- ตรวจสอบว่า URL เริ่มต้นด้วย http:// หรือ https://
- ตรวจสอบว่า URL ยังไม่ได้ถูกย่อแล้ว
- ลองใช้
urlแทนshort_url
เกินขีดจำกัดตัวแปร
- ติดต่อฝ่ายสนับสนุนเกี่ยวกับขีดจำกัดตัวแปร
- ใช้ ID ตัวแปรซ้ำเมื่อเป็นไปได้
- ทำความสะอาดตัวแปรเก่า
- ปรับปรุงการใช้ตัวแปร
ขั้นตอนต่อไป
- Send Messages - ส่งข้อความ cascade
- Message Types - สำรวจประเภทข้อความ
- SMSBAT API - เรียนรู้เกี่ยวกับ SMSBAT API