telnyx-account-javascript
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinese<!-- Auto-generated from Telnyx OpenAPI specs. Do not edit. -->
<!-- Auto-generated from Telnyx OpenAPI specs. Do not edit. -->
Telnyx Account - JavaScript
Telnyx Account - JavaScript
Installation
安装
bash
npm install telnyxbash
npm install telnyxSetup
设置
javascript
import Telnyx from 'telnyx';
const client = new Telnyx({
apiKey: process.env['TELNYX_API_KEY'], // This is the default and can be omitted
});All examples below assume is already initialized as shown above.
clientjavascript
import Telnyx from 'telnyx';
const client = new Telnyx({
apiKey: process.env['TELNYX_API_KEY'], // This is the default and can be omitted
});以下所有示例均假设已按照上述方式完成初始化。
clientError Handling
错误处理
All API calls can fail with network errors, rate limits (429), validation errors (422),
or authentication errors (401). Always handle errors in production code:
javascript
try {
const result = await client.messages.send({ to: '+13125550001', from: '+13125550002', text: 'Hello' });
} catch (err) {
if (err instanceof Telnyx.APIConnectionError) {
console.error('Network error — check connectivity and retry');
} else if (err instanceof Telnyx.RateLimitError) {
// 429: rate limited — wait and retry with exponential backoff
const retryAfter = err.headers?.['retry-after'] || 1;
await new Promise(r => setTimeout(r, retryAfter * 1000));
} else if (err instanceof Telnyx.APIError) {
console.error(`API error ${err.status}: ${err.message}`);
if (err.status === 422) {
console.error('Validation error — check required fields and formats');
}
}
}Common error codes: invalid API key, insufficient permissions,
resource not found, validation error (check field formats),
rate limited (retry with exponential backoff).
401403404422429所有API调用都可能因网络错误、速率限制(429)、验证错误(422)或认证错误(401)而失败。在生产代码中务必处理错误:
javascript
try {
const result = await client.messages.send({ to: '+13125550001', from: '+13125550002', text: 'Hello' });
} catch (err) {
if (err instanceof Telnyx.APIConnectionError) {
console.error('Network error — check connectivity and retry');
} else if (err instanceof Telnyx.RateLimitError) {
// 429: rate limited — wait and retry with exponential backoff
const retryAfter = err.headers?.['retry-after'] || 1;
await new Promise(r => setTimeout(r, retryAfter * 1000));
} else if (err instanceof Telnyx.APIError) {
console.error(`API error ${err.status}: ${err.message}`);
if (err.status === 422) {
console.error('Validation error — check required fields and formats');
}
}
}常见错误码:无效API密钥,权限不足,资源未找到,验证错误(检查字段格式),速率限制(使用指数退避策略重试)。
401403404422429Important Notes
重要说明
- Pagination: List methods return an auto-paginating iterator. Use to iterate through all pages automatically.
for await (const item of result) { ... }
- 分页: 列表方法会返回一个自动分页的迭代器。使用可自动遍历所有页面。
for await (const item of result) { ... }
List Audit Logs
列出审计日志
Retrieve a list of audit log entries. Audit logs are a best-effort, eventually consistent record of significant account-related changes.
GET /audit_eventsjavascript
// Automatically fetches more pages as needed.
for await (const auditEventListResponse of client.auditEvents.list()) {
console.log(auditEventListResponse.id);
}Returns: (string | null), (enum: telnyx, account_manager, account_owner, organization_member), (string), (array | null), (date-time), (uuid), (uuid), (string), (string), (uuid)
alternate_resource_idchange_made_bychange_typechangescreated_atidorganization_idrecord_typeresource_iduser_id检索审计日志条目列表。审计日志是对账户相关重大变更的尽力而为、最终一致的记录。
GET /audit_eventsjavascript
// Automatically fetches more pages as needed.
for await (const auditEventListResponse of client.auditEvents.list()) {
console.log(auditEventListResponse.id);
}返回字段:(字符串 | 空值)、(枚举值:telnyx、account_manager、account_owner、organization_member)、(字符串)、(数组 | 空值)、(日期时间)、(uuid)、(uuid)、(字符串)、(字符串)、(uuid)
alternate_resource_idchange_made_bychange_typechangescreated_atidorganization_idrecord_typeresource_iduser_idGet user balance details
获取用户余额详情
GET /balancejavascript
const balance = await client.balance.retrieve();
console.log(balance.data);Returns: (string), (string), (string), (string), (string), (enum: balance)
available_creditbalancecredit_limitcurrencypendingrecord_typeGET /balancejavascript
const balance = await client.balance.retrieve();
console.log(balance.data);返回字段:(字符串)、(字符串)、(字符串)、(字符串)、(字符串)、(枚举值:balance)
available_creditbalancecredit_limitcurrencypendingrecord_typeGet monthly charges breakdown
获取月度费用明细
Retrieve a detailed breakdown of monthly charges for phone numbers in a specified date range. The date range cannot exceed 31 days.
GET /charges_breakdownjavascript
const chargesBreakdown = await client.chargesBreakdown.retrieve({ start_date: '2025-05-01' });
console.log(chargesBreakdown.data);Returns: (string), (date), (array[object]), (date), (email), (string)
currencyend_dateresultsstart_dateuser_emailuser_id检索指定日期范围内电话号码的月度费用详细明细。日期范围不能超过31天。
GET /charges_breakdownjavascript
const chargesBreakdown = await client.chargesBreakdown.retrieve({ start_date: '2025-05-01' });
console.log(chargesBreakdown.data);返回字段:(字符串)、(日期)、(对象数组)、(日期)、(邮箱)、(字符串)
currencyend_dateresultsstart_dateuser_emailuser_idGet monthly charges summary
获取月度费用汇总
Retrieve a summary of monthly charges for a specified date range. The date range cannot exceed 31 days.
GET /charges_summaryjavascript
const chargesSummary = await client.chargesSummary.retrieve({
end_date: '2025-06-01',
start_date: '2025-05-01',
});
console.log(chargesSummary.data);Returns: (string), (date), (date), (object), (object), (email), (string)
currencyend_datestart_datesummarytotaluser_emailuser_id检索指定日期范围内的月度费用汇总。日期范围不能超过31天。
GET /charges_summaryjavascript
const chargesSummary = await client.chargesSummary.retrieve({
end_date: '2025-06-01',
start_date: '2025-05-01',
});
console.log(chargesSummary.data);返回字段:(字符串)、(日期)、(日期)、(对象)、(对象)、(邮箱)、(字符串)
currencyend_datestart_datesummarytotaluser_emailuser_idSearch detail records
搜索明细记录
Search for any detail record across the Telnyx Platform
GET /detail_recordsjavascript
// Automatically fetches more pages as needed.
for await (const detailRecordListResponse of client.detailRecords.list()) {
console.log(detailRecordListResponse);
}Returns: (string), (string), (string), (string), (date-time), (string), (string), (date-time), (string), (string), (string), (string), (enum: inbound, outbound), (array[string]), (boolean), (string), (enum: SMS, MMS, RCS), (string), (boolean), (integer), (string), (string), (string), (string), (date-time), (string), (enum: gw_timeout, delivered, dlr_unconfirmed, dlr_timeout, received, gw_reject, failed), (string), (date-time), (string), (string)
carriercarrier_feecldclicompleted_atcostcountry_codecreated_atcurrencydelivery_statusdelivery_status_failover_urldelivery_status_webhook_urldirectionerrorsfteumccmessage_typemncon_netpartsprofile_idprofile_nameraterecord_typesent_atsource_country_codestatustagsupdated_atuser_iduuid在Telnyx平台上搜索任意明细记录
GET /detail_recordsjavascript
// Automatically fetches more pages as needed.
for await (const detailRecordListResponse of client.detailRecords.list()) {
console.log(detailRecordListResponse);
}返回字段:(字符串)、(字符串)、(字符串)、(字符串)、(日期时间)、(字符串)、(字符串)、(日期时间)、(字符串)、(字符串)、(字符串)、(字符串)、(枚举值:inbound、outbound)、(字符串数组)、(布尔值)、(字符串)、(枚举值:SMS、MMS、RCS)、(字符串)、(布尔值)、(整数)、(字符串)、(字符串)、(字符串)、(字符串)、(日期时间)、(字符串)、(枚举值:gw_timeout、delivered、dlr_unconfirmed、dlr_timeout、received、gw_reject、failed)、(字符串)、(日期时间)、(字符串)、(字符串)
carriercarrier_feecldclicompleted_atcostcountry_codecreated_atcurrencydelivery_statusdelivery_status_failover_urldelivery_status_webhook_urldirectionerrorsfteumccmessage_typemncon_netpartsprofile_idprofile_nameraterecord_typesent_atsource_country_codestatustagsupdated_atuser_iduuidList invoices
列出发票
Retrieve a paginated list of invoices.
GET /invoicesjavascript
// Automatically fetches more pages as needed.
for await (const invoiceListResponse of client.invoices.list()) {
console.log(invoiceListResponse.file_id);
}Returns: (uuid), (uuid), (boolean), (date), (date), (uri)
file_idinvoice_idpaidperiod_endperiod_starturl检索分页的发票列表。
GET /invoicesjavascript
// Automatically fetches more pages as needed.
for await (const invoiceListResponse of client.invoices.list()) {
console.log(invoiceListResponse.file_id);
}返回字段:(uuid)、(uuid)、(布尔值)、(日期)、(日期)、(uri)
file_idinvoice_idpaidperiod_endperiod_starturlGet invoice by ID
根据ID获取发票
Retrieve a single invoice by its unique identifier.
GET /invoices/{id}javascript
const invoice = await client.invoices.retrieve('182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e');
console.log(invoice.data);Returns: (uri), (uuid), (uuid), (boolean), (date), (date), (uri)
download_urlfile_idinvoice_idpaidperiod_endperiod_starturl通过唯一标识符检索单个发票。
GET /invoices/{id}javascript
const invoice = await client.invoices.retrieve('182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e');
console.log(invoice.data);返回字段:(uri)、(uuid)、(uuid)、(布尔值)、(日期)、(日期)、(uri)
download_urlfile_idinvoice_idpaidperiod_endperiod_starturlList auto recharge preferences
列出自动充值偏好设置
Returns the payment auto recharge preferences.
GET /payment/auto_recharge_prefsjavascript
const autoRechargePrefs = await client.payment.autoRechargePrefs.list();
console.log(autoRechargePrefs.data);Returns: (boolean), (string), (boolean), (enum: credit_paypal, ach), (string), (string), (string)
enabledidinvoice_enabledpreferencerecharge_amountrecord_typethreshold_amount返回支付自动充值偏好设置。
GET /payment/auto_recharge_prefsjavascript
const autoRechargePrefs = await client.payment.autoRechargePrefs.list();
console.log(autoRechargePrefs.data);返回字段:(布尔值)、(字符串)、(布尔值)、(枚举值:credit_paypal、ach)、(字符串)、(字符串)、(字符串)
enabledidinvoice_enabledpreferencerecharge_amountrecord_typethreshold_amountUpdate auto recharge preferences
更新自动充值偏好设置
Update payment auto recharge preferences.
PATCH /payment/auto_recharge_prefsOptional: (boolean), (boolean), (enum: credit_paypal, ach), (string), (string)
enabledinvoice_enabledpreferencerecharge_amountthreshold_amountjavascript
const autoRechargePref = await client.payment.autoRechargePrefs.update();
console.log(autoRechargePref.data);Returns: (boolean), (string), (boolean), (enum: credit_paypal, ach), (string), (string), (string)
enabledidinvoice_enabledpreferencerecharge_amountrecord_typethreshold_amount更新支付自动充值偏好设置。
PATCH /payment/auto_recharge_prefs可选字段:(布尔值)、(布尔值)、(枚举值:credit_paypal、ach)、(字符串)、(字符串)
enabledinvoice_enabledpreferencerecharge_amountthreshold_amountjavascript
const autoRechargePref = await client.payment.autoRechargePrefs.update();
console.log(autoRechargePref.data);返回字段:(布尔值)、(字符串)、(布尔值)、(枚举值:credit_paypal、ach)、(字符串)、(字符串)、(字符串)
enabledidinvoice_enabledpreferencerecharge_amountrecord_typethreshold_amountList User Tags
列出用户标签
List all user tags.
GET /user_tagsjavascript
const userTags = await client.userTags.list();
console.log(userTags.data);Returns: (array[string]), (array[string])
number_tagsoutbound_profile_tags列出所有用户标签。
GET /user_tagsjavascript
const userTags = await client.userTags.list();
console.log(userTags.data);返回字段:(字符串数组)、(字符串数组)
number_tagsoutbound_profile_tagsCreate a stored payment transaction
创建存储支付交易
POST /v2/payment/stored_payment_transactionsamountjavascript
const response = await client.payment.createStoredPaymentTransaction({ amount: '120.00' });
console.log(response.data);Returns: (integer), (string), (boolean), (date-time), (string), (string), (enum: transaction), (enum: stored_payment)
amount_centsamount_currencyauto_rechargecreated_atidprocessor_statusrecord_typetransaction_processing_typePOST /v2/payment/stored_payment_transactionsamountjavascript
const response = await client.payment.createStoredPaymentTransaction({ amount: '120.00' });
console.log(response.data);返回字段:(整数)、(字符串)、(布尔值)、(日期时间)、(字符串)、(字符串)、(枚举值:transaction)、(枚举值:stored_payment)
amount_centsamount_currencyauto_rechargecreated_atidprocessor_statusrecord_typetransaction_processing_typeList webhook deliveries
列出Webhook投递记录
Lists webhook_deliveries for the authenticated user
GET /webhook_deliveriesjavascript
// Automatically fetches more pages as needed.
for await (const webhookDeliveryListResponse of client.webhookDeliveries.list()) {
console.log(webhookDeliveryListResponse.id);
}Returns: (array[object]), (date-time), (uuid), (string), (date-time), (enum: delivered, failed), (uuid), (object)
attemptsfinished_atidrecord_typestarted_atstatususer_idwebhook列出已认证用户的webhook投递记录
GET /webhook_deliveriesjavascript
// Automatically fetches more pages as needed.
for await (const webhookDeliveryListResponse of client.webhookDeliveries.list()) {
console.log(webhookDeliveryListResponse.id);
}返回字段:(对象数组)、(日期时间)、(uuid)、(字符串)、(日期时间)、(枚举值:delivered、failed)、(uuid)、(对象)
attemptsfinished_atidrecord_typestarted_atstatususer_idwebhookFind webhook_delivery details by ID
根据ID查找Webhook投递详情
Provides webhook_delivery debug data, such as timestamps, delivery status and attempts.
GET /webhook_deliveries/{id}javascript
const webhookDelivery = await client.webhookDeliveries.retrieve(
'C9C0797E-901D-4349-A33C-C2C8F31A92C2',
);
console.log(webhookDelivery.data);Returns: (array[object]), (date-time), (uuid), (string), (date-time), (enum: delivered, failed), (uuid), (object)
attemptsfinished_atidrecord_typestarted_atstatususer_idwebhook提供Webhook投递调试数据,例如时间戳、投递状态和尝试记录。
GET /webhook_deliveries/{id}javascript
const webhookDelivery = await client.webhookDeliveries.retrieve(
'C9C0797E-901D-4349-A33C-C2C8F31A92C2',
);
console.log(webhookDelivery.data);返回字段:(对象数组)、(日期时间)、(uuid)、(字符串)、(日期时间)、(枚举值:delivered、failed)、(uuid)、(对象)
attemptsfinished_atidrecord_typestarted_atstatususer_idwebhook