Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

telnyx

team-telnyx90.6kMIT2.0.0TypeScript support: included

Telnyx API Node SDK

telnyx, sms, sip trunking, phone numbers, api, sdk

readme

Telnyx Node.js Library

Version Build Status Downloads Try on RunKit Code Style Join Slack

The Telnyx Node library provides convenient access to the Telnyx API from applications written in server-side JavaScript.

Documentation

See the Node API docs.

Versions

telnyx-node uses a slightly modified version of Semantic Versioning for all changes. See this document for details.

Installation

Install the package with:

npm install telnyx --save

Usage

The package needs to be configured with your account's API key which is available in your the Telnyx Mission Control Portal. Require it with the key's value:

import Telnyx from 'telnyx';

const telnyx = new Telnyx('KEY123456...');

const messagingProfile = await telnyx.messagingProfiles.create({
  name: 'Summer Campaign',
});

Using Promises

Every method returns a chainable promise which can be used instead of a regular callback:

// Create a new messaging profile and then send a message using that profile:
telnyx.messagingProfiles
  .create({
    name: 'Summer Campaign',
  })
  .then((messagingProfile) => {
    return telnyx.messagingPhoneNumbers.update('+18005554000', {
      messaging_profile_id: messagingProfile.data.id,
    });
  })
  .catch((err) => {
    // Deal with an error
  });

Configuring Timeout

Request timeout is configurable (the default is Node's default of 120 seconds):

telnyx.setTimeout(20000); // in ms (this is 20 seconds)

Configuring a Proxy

An https-proxy-agent can be configured with setHttpAgent.

To use telnyx behind a proxy you can pass to sdk:

import ProxyAgent from 'https-proxy-agent';

if (process.env.http_proxy) {
  telnyx.setHttpAgent(new ProxyAgent(process.env.http_proxy));
}

Network retries

Automatic network retries can be enabled with setMaxNetworkRetries. This will retry requests n times with exponential backoff if they fail due to an intermittent network problem.

// Retry a request once before giving up
telnyx.setMaxNetworkRetries(1);

Examining Responses

Some information about the response which generated a resource is available with the lastResponse property:

messagingProfile.lastResponse.requestId; // see: https://telnyx.com/docs/api/node#request_ids
messagingProfile.lastResponse.statusCode;

request and response events

The Telnyx object emits request and response events. You can use them like this:

import Telnyx from 'telnyx';

const telnyx = new Telnyx('KEY...');

const onRequest = (request) => {
  // Do something.
};

// Add the event handler function:
telnyx.on('request', onRequest);

// Remove the event handler function:
telnyx.off('request', onRequest);

request object

{
  method: 'POST',
  path: '/v2/messaging_profiles'
}

response object

{
  method: 'POST',
  path: '/v2/messaging_profiles',
  status: 200,
  request_id: 'Ghc9r26ts73DRf',
  elapsed: 445                // Elapsed time in milliseconds
}

Webhook signing

Telnyx signs the webhook events it sends to your endpoint, allowing you to validate that they were not sent by a third-party. You can read more about it here.

Please note that you must pass the raw request body, exactly as received from Telnyx, to the constructEvent() function; this will not work with a parsed (i.e., JSON) request body.

You can find an example of how to use this with Express in the examples/webhook-signing folder, but here's what it looks like:

const event = telnyx.webhooks.constructEvent(
  webhookRawBody,
  webhookTelnyxSignatureHeader,
  webhookTelnyxTimestampHeader,
  publicKey,
);

TeXML Signature

TeXML sends webhooks as form-encoded payloads instead of JSON. To validate the signature, use the telnyx.webhooks.signature.verifySignature method.

You can find an example of how to use this with Express in the examples/webhook-signing folder.

const timeToleranceInSeconds = 300; // Will validate signatures of webhooks up to 5 minutes after Telnyx sent the request
try {
  telnyx.webhooks.signature.verifySignature(
    webhookRawBody,
    webhookTelnyxSignatureHeader,
    webhookTelnyxTimestampHeader,
    publicKey,
    timeToleranceInSeconds,
  );
} catch (e) {
  console.log('Failed to validate the signature');
  console.log(e);
}

Writing a Plugin

If you're writing a plugin that uses the library, we'd appreciate it if you identified using telnyx.setAppInfo():

telnyx.setAppInfo({
  name: 'MyAwesomePlugin',
  version: '1.2.34', // Optional
  url: 'https://myawesomeplugin.info', // Optional
});

This information is passed along when the library makes calls to the Telnyx API.

Auto-pagination

You can auto-paginate list methods. We provide a few different APIs for this to aid with a variety of node versions and styles.

Async iterators (for-await-of)

If you are in a Node environment that has support for async iteration, such as Node 10+ or babel, the following will auto-paginate:

for await (const messagingProfile of telnyx.messagingProfiles.list()) {
  doSomething(messagingProfile);
  if (shouldStop()) {
    break;
  }
}

autoPagingEach

If you are in a Node environment that has support for await, such as Node 7.9 and greater, you may pass an async function to .autoPagingEach:

await telnyx.messagingProfiles
  .list()
  .autoPagingEach(async (messagingProfile) => {
    await doSomething(messagingProfile);
    if (shouldBreak()) {
      return false;
    }
  });
console.log('Done iterating.');

Equivalently, without await, you may return a Promise, which can resolve to false to break:

telnyx.messagingProfiles
  .list()
  .autoPagingEach((messagingProfile) => {
    return doSomething(messagingProfile).then(() => {
      if (shouldBreak()) {
        return false;
      }
    });
  })
  .then(() => {
    console.log('Done iterating.');
  })
  .catch(handleError);

If you prefer callbacks to promises, you may also use a next callback and a second onDone callback:

telnyx.messagingProfiles.list().autoPagingEach(
  function onItem(messagingProfile, next) {
    doSomething(messagingProfile, function (err, result) {
      if (shouldStop(result)) {
        next(false); // Passing `false` breaks out of the loop.
      } else {
        next();
      }
    });
  },
  function onDone(err) {
    if (err) {
      console.error(err);
    } else {
      console.log('Done iterating.');
    }
  },
);

If your onItem function does not accept a next callback parameter or return a Promise, the return value is used to decide whether to continue (false breaks, anything else continues).

autoPagingToArray

This is a convenience for cases where you expect the number of items to be relatively small; accordingly, you must pass a limit option to prevent runaway list growth from consuming too much memory.

Returns a promise of an array of all items across pages for a list request.

const allMessagingProfiles = await telnyx.messagingProfiles
  .list()
  .autoPagingToArray({limit: 10000});

Getting help

If you need help installing or using the library, please check the Telnyx Documentation first, and contact Telnyx support if you don't find an answer to your question.

If you've instead found a bug in the library or would like new features added, go ahead and open issues or pull requests against this repo!

Contributing

Bug fixes, docs, and library improvements are always welcome. Please refer to our Contributing Guide for detailed information on how you can contribute.

Note: Please be aware that a good share of the files are auto-generated. You are welcome to suggest changes and submit PRs illustrating the changes. However, we'll have to make the changes in the underlying tool. You can find more info about this in the Contributing Guide.

If you're not familiar with the GitHub pull request/contribution process, this is a nice tutorial.

Development

Setup

Run the following to create your env file

cp .env.local .env

Don't forget to update your .env values accordingly.

Now inject envs into terminal:

. ./setup_env.sh

Feel free to use Node --env-file parameter to setup envs if you prefer

The test suite depends on the Prism Mock Server.

Start the prism mock service with the following command:

npx prism mock https://raw.githubusercontent.com/team-telnyx/openapi/master/openapi/spec3.json

One final step -- because the Node SDK originally expected to reach the legacy telnyx-mock service at port 12111 (in addition to providing a /v2/ base path), we need to setup the Telnyx mock proxy server to modify the request path and forward along to the prism mock server.

# In new terminal window

git clone git@github.com:team-telnyx/telnyx-prism-mock.git
cd telnyx-prism-mock/proxy

npm install
node index.js

Running Tests

$ npm install
$ npm test

Run all tests with a custom telnyx-mock port:

$ TELNYX_MOCK_PORT=12111 npm test

Run a single test suite:

$ npm test -- test/Error.test.ts

Run a single test (case sensitive):

$ npm test -- test/Error.test.ts -t 'Populates with type'

If you wish, you may run tests using your Telnyx Test API key by setting the environment variable TELNYX_TEST_API_KEY before running the tests:

$ export TELNYX_TEST_API_KEY='KEY....'
$ export TELNYX_MOCK_PORT='12...'
$ npm test

Debugging

To inspect values in tests first import debug:

import Debug from 'debug';

const debug = Debug('foo');
//...
debug(result);

Then run the tests with:

$ DEBUG=foo npm test

To view verbose debugging for nock run the tests with:

$ DEBUG=nock.* npm test

Typescript

Run:

npm run build

Then check output in dist folder

Linter (Prettier)

Add an editor integration or:

$ npm run fix

Acknowledgements

The contributors and maintainers of Telnyx Node would like to extend their deep gratitude to the authors of Stripe Node, upon which this project is based. Thank you for developing such elegant, usable, extensible code and for sharing it with the community.

changelog

CHANGELOG

v2

v2.0.0

  • Typescript Support! :tada:

v2.0.0-beta.6

  • Add connections example
  • Add numbers example
  • Fix WebhookHeader type mismatch

v2.0.0-beta.5

  • Update TelnyxAPI.d.ts types
  • Add missing Events and remove unused ones
  • Remove /tags endpoint from TelephonyCredentials resource
  • Update ManagedAccounts resource tests
  • Remove network preferences endpoints from SimCards resource
  • Remove unused NumberOrderDocuments resource
  • Update tsconfig.json to use Node16 module
  • Update relative lib files to include js extension according to moduleResolution config

v2.0.0-beta.4

  • Add CONTRIBUTING.md guidelines
  • Update README.md
  • Fix tranformResponseData misusage on list resource methods
  • Update stale types on Portability, Porting and Portout resources methods

v2.0.0-beta.3

  • Add Errors type declaration
  • Add VERSIONS.md information
  • Update package dependencies for runtime usage

v2.0.0-beta.2

  • Add missing Texml resource methods
  • Add missing PhoneNumbers, NumberOrders and RegulatoryRequirements resource methods
  • Update types on stale resources methods

v2.0.0-beta.1

  • Fix Queues resource nested methods
  • Fix PortingOrders and Ips resource nested methods param names
  • Update legacy skipped tests
  • Fix Verifications, VerifyProfiles and VerifiedNumbers resources method naming and params
  • Remove dupe Verify resource
  • Update nested methods types to match param values usage

v2.0.0-beta.0

  • Move AutorespConfigs resource to be nested in MessagingProfiles
  • Fix nested resources in Calls, MessagingProfiles and Conferences ID usage instead of using constructors data
  • Fix nested resources Calls, MessagingProfiles and Conferences method names
  • Fix Brand resources method name
  • Fix bug on DELETE operations empty responseBody JSON Parsing
  • Update types on resources methods with multiple urlParams
  • FIX: README Typo by @mpareja-godaddy in https://github.com/team-telnyx/telnyx-node/pull/186

v2.0.0-alpha.7

  • Export API callback events type definitions

v2.0.0-alpha.6

  • Update optional types on Webhooks
  • Make optional types on Fqdns, Ips, Messages and StorageBuckets resources more strict

v2.0.0-alpha.5

  • Remove ClientStateUpdate resource
  • Remove MessagesAlphanumericSenderId resource
  • Remove MessagingHostedNumber resource
  • Remove MessagingPhoneNumbers resource
  • Remove MessagingSenderIds resource
  • Remove PublicKey resource
  • Remove UpdateClientState resource
  • Remove Debugging dupe resource
  • Update syntax on Events resources
  • Update ExternalConnections stale resource
  • Update Messages stale resource
  • Update Ips stale resources
  • Update AutorespConfigs stale resource
  • Update DetailRecords stale resource
  • Update InventoryCoverage stale resource

v2.0.0-alpha.4

  • Add Addresses example
  • Remove BusinessIdentity resource
  • Remove CallInformation resource
  • Remove duplicated Credentials resource
  • Fixed Conferences, Documents and TelephonyCredentials method names
  • Add missing resource types defs

v2.0.0-alpha.3

  • Update typing on Nested Resources

v2.0.0-alpha.2

  • Fix AI resource methods and created nested structure

v2.0.0-alpha.1

  • Update actions workflow versions to v4 and .npmignore to v2
  • Update examples dependencies

v2.0.0-alpha.0

  • Add Typescript default config, linter and dependencies
  • Bump default Node version to 20
  • Update README on Development instructions
  • Remove yarn in favor of npm 10
  • Convert SDK files to Typescript
  • Convert Resources to Typescript
  • Use ES Modules syntax
  • Update package main entrypoint to be compiled version of src telnyx.ts
  • Added Jest and create tests in Typescript
  • Update tests expect matchers according to limitations with prism mock
  • Add nock cleanup setup
  • Make setApiKey TelnyxObject prototype method private
  • Moved to moduleResolution Bundler to support better imports and tests with Jest
  • Enabled esModuleInterop for Jest
  • Update files included when publishing
  • Remove custom resource get generateAccessTokenFromCredential from TelephonyCredentials
  • Update AutoRechargePreferences resource
  • Remove RegisterCall resource
  • Remove ProgrammableFaxCommants specs
  • Remove BulkCreation resource
  • Update TexmlApplications resource
  • Remove Conferences dial_participant action
  • Remove SimCards deletePublicIp and setPublicIp
  • Update Queues method names to camelCase
  • Remove VerifiedCallsDisplayProfile resource
  • Update examples to Typescript
  • Remove duplicated AccessTokens resource
  • Move custom AdvancedOptinoptout resource to be AutoRespConfigs resource
  • Remove Billing resource
  • Remove inexistent Bucket resource
  • Move BucketUsage resource to StorageBuckets
  • Remove duplicated BulkPhoneNumberCampaigns resource
  • Remove duplicated BulkPhoneNumberOperations resource

v1

v1.26.2

  • Fix Brand and Campaign redirects
  • Update security

v1.26.1

  • Fix porting comments

v1.26.0

  • Endpoint additions
  • Package upgrades
  • Preparation for typescript migration/support

v1.25.5

  • Security Updates + API Additions

v1.23.0 (2021-10-19)

  • Addresses added validate
  • AuthenticationProvider added list, create, retrieve, update, del
  • DynamicEmergency (for endpoints and addresses) added list, retrieve, create, del
  • InventoryCoverage added request
  • NumberBackgroundJobs added list, retrieve, updateEmergencySettings, updateNumbers, deleteNumbers
  • PhoneNumbers added setEmergencySettings
  • PortabilityChecks added run
  • PortingOrders added listExceptionTypes, listActivationJobs, cancelOrder, listAllowedFocWindows
  • PortingPhoneNumber added list
  • PortoutRequests added list, retrieve, updateStatus, listComments, createComment
  • SimCards added setStandby, retrievePublicIP, setPublicIP, deletePublicIP
  • WirelessDetailRecordReports added list, create, retrieve, del

v1.22.0 (2021-09-23)

  • resources Additional support for Verification endpoint

v1.21.0 (2021-09-15)

  • Conference added retrieve, participants, speak, play, stop, record_start, record_stop, update, leave

v1.20.0 (2021-09-14)

  • PortingOrders added porting orders endpoint

v1.19.0 (2021-08-26)

  • DetailRecords added detail records endpoint

v1.18.0 (2021-07-28)

  • resources Additional support for Telephony Credentials (WebRTC)

v1.17.0 (2021-07-19)

  • SMS Verification add support for BySMS Verification Codes

v1.16.0 (2021-07-15)

  • call control added enqueuing
  • SIM added more coverage

v1.15.0 (2021-04-26)

  • call control added gather_stop, record_pause, refer, record_resume, transcription_start, transcription_stop

v1.13.0 (2021-03-29)

  • resources Hosted Messaging Support

v1.12.0 (2021-03-15)

  • bug fix PhoneNumberRegulatoryRequirements now hits phone_numbers_regulatory_requirements
  • resources Fax support

v1.11.1 (2021-01-19)

  • resources: Fax Applications

v1.11.0 (2020-12-18)

  • resources: Verify Profiles

  • resources: Verifications

  • build: Github Actions

v1.10.3 (2020-12-15)

Bug Fixes
  • resources: Add function tryParseJSON to avoid parse invalid objects.
New Features
  • resources: Telephony Credentials

v1.10.2 (2020-10-16)

Bug Fixes
  • resources: Add Phone Numbers Retrieve Method

v1.10.1 (2020-09-24)

Bug Fixes
  • resources: Recreate resources on constructor call

v1.10.0 (2020-08-07)

  • resources: Messaging Profile Metrics

  • resources: Short Codes

v1.9.0 (2020-07-22)

  • resources: SIM Card Enable/Disable Methods

v1.8.0 (2020-07-14)

  • resources: OTA Updates

  • resources: SIM Card Groups

  • resources: Mobile Operator Networks

  • resources: SIM Card Network Preferences Methods

  • resources: Number Lookup

  • resources: Balance

  • resources: Addresses

  • resources: Faxes

v1.7.2 (2020-04-20)

New Features
  • resources: Inbound Channels

  • resources: Call Control Application

  • resources: Outbound Voice Profiles

v1.7.1 (2020-01-30)

Bug Fixes
  • resources: Clear leftover state in nested methods

  • webhook: Update examples

v1.7.0 (2020-01-30)

New Features
  • resources: Connections

  • resources: Ips

  • resources: FQDNs

v1.6.0 (2019-12-18)

New Features
  • resources: Number Order Regulatory Requirements

  • resources: Number Order Documents

v1.5.0 (2019-12-16)

New Features
  • resources: Credential Connections

  • resources: FQDN Connections

  • resources: IP Connections

v1.4.0 (2019-12-12)

New Features
  • resources: Billing Groups

  • webhooks: Inbound Call Control example

v1.3.0 (2019-11-14)

New Features
  • resources: SIM Cards

  • resources: Phone Numbers

v1.2.4 (2019-10-22)

Bug Fixes
  • resources: fix content-length header calculation on requestData
    • account for multi-byte chars on getting request data length (e.g.: en dash)
    • improve specs

v1.2.3 (2019-9-25)

Bug Fixes
  • query-string: fix query parameter array format. Use 'brackets'

v1.2.2 (2019-9-9)

Bug Fixes
  • webhooks: fix signature verification with tweetnacl

v1.2.1 (2019-9-5)

Bug Fixes
  • webhooks: replace c compiled ed25519 package with node tweetnacl

  • package: fix install for node v12

v1.2.0 (2019-8-19)

New Features
  • resources: empty constructors on resources names, for Calls and Conferences

  • resources: nested resources

  • resources: new Aplhanumeric Sender ID endpoints

v1.1.0 (2019-8-9)

New Features
  • webhooks: validation algorithm update to ed25519
Bug Fixes
  • resources: nested resources custom attributes assign

  • error-handling: prevent undefined message on error handling

v1.0.0 (2019-8-2)

New Features
  • Call Control: Call commands, Call Events and Call Status

  • Number Reservations: extend to have number reservations resources

  • Initial structure:

    • Remove references to charges and customers

    • Use safe example phone number

    • Load api base url from environment

    • Initial commit

Documentation Changes
  • README:

    • developer docs liks

    • fix integrations links

    • Improve wording in README regarding API key

Other Changes
  • testing: telnyx-mock testing support

  • node: Node version support