Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

nexmo

Package Overview
Dependencies
Maintainers
5
Versions
55
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

nexmo

Nexmo REST API client for Node.js. API support for SMS, Voice Calls, Text-to-Speech, Numbers, Verify (2FA) and more.

  • 2.5.2-beta-1
  • Source
  • npm
  • Socket score

Version published
Maintainers
5
Created
Source

Nexmo Client Library for Node.js

build status Known Vulnerabilities codecov

A Node.JS REST API Wrapper library for Nexmo.

For full API documentation refer to developer.nexmo.com.

NPM

Installation | Constructor | Messaging | Message Signing | Voice | Verify | Number Insight | Applications | Conversations | Users | Management | Redact | JWT (JSON Web Token)

Installation

npm install nexmo

Constructor

  • apiKey and apiSecret are required for SMS, Verify, Number Insights, Account management APIs
  • applicationId and privateKey are required for Voice / Stitch applications
const Nexmo = require('nexmo');

const nexmo = new Nexmo({
    apiKey: API_KEY,
    apiSecret: API_SECRET,
    applicationId: APP_ID,
    privateKey: PRIVATE_KEY_PATH,
    signatureSecret: SIGNATURE_SECRET,
    signatureMethod: SIGNATURE_METHOD
  }, options);
  • apiKey - API Key from Nexmo.
  • apiSecret - API SECRET from Nexmo.
  • applicationId - (optional) The Nexmo Application ID to be used when creating JWTs.
  • privateKey - (optional) The Private Key to be used when creating JWTs. You can specify the key as any of the following:
    • A Buffer containing the file contents.
    • A String containing the path to the key file on disk.
  • signatureSecret - (optional) API singature secret from Nexmo, used for signing SMS message requests
  • signatureMethod - (optional) singature method matching the one you gave Nexmo, used for signing SMS message requests. Must be one of "md5hash", "md5", "sha1", "sha256", or "sha512"
  • options - (optional) Additional options for the constructor.

Options are:

{
  // If true, log information to the console
  debug: true|false,
  // append info the the User-Agent sent to Nexmo
  // e.g. pass 'my-app' for /nexmo-node/1.0.0/4.2.7/my-app
  appendToUserAgent: string,
  // Set a custom logger
  logger: {
    log: function() {level, args...}
    info: function() {args...},
    warn: function() {args...}
  },
  // Set a custom timeout for requests to Nexmo in milliseconds. Defaults to the standard for Node http requests, which is 120,000 ms.
  timeout: integer
}

Messaging

Send a text message

nexmo.message.sendSms(sender, recipient, message, options, callback);

Send a Binary Message

nexmo.message.sendBinaryMessage(fromnumber, tonumber, body, udh, callback);
  • body - Hex encoded binary data
  • udh - Hex encoded udh

Send a WAP Push Message

nexmo.message.sendWapPushMessage(fromnumber, tonumber, title, url, validity, callback);
  • validity - is optional (if given should be in milliseconds)

Send a Short Code alert

nexmo.message.shortcodeAlert(recipient, messageParams, opts, callback);

Voice

For detailed information please see the documentation at https://developer.nexmo.com/api/voice

Make a call

Requires applicationId and privateKey to be set on the constructor.

nexmo.calls.create({
  to: [{
    type: 'phone',
    number: TO_NUMBER
  }],
  from: {
    type: 'phone',
    number: FROM_NUMBER
  },
  answer_url: [ANSWER_URL]
}, callback);

For more information see https://developer.nexmo.com/api/voice#createCall

Get a Call

nexmo.calls.get(callId, callback);

For more information see https://developer.nexmo.com/api/voice#getCall

Query Calls

nexmo.calls.get({status: 'completed'}, callback);

The first parameter can contain many properties to filter the returned call or to page results. For more information see the Calls API Reference.

Update a Call

nexmo.calls.update(callId, { action: 'hangup' }, callback);

For more information see https://developer.nexmo.com/api/voice#updateCall

Stream an Audio File to a Call

nexmo.calls.stream.start(
  callId,
  {
    stream_url: [
      'https://nexmo-community.github.io/ncco-examples/assets/voice_api_audio_streaming.mp3'
    ],
    loop: 1
  });

For more information see https://developer.nexmo.com/api/voice#startStream

Stop an audio stream in a call

nexmo.calls.stream.stop(callId);

For more information see https://developer.nexmo.com/api/voice#stopStream

Play synthesized text in a call

nexmo.calls.talk.start(
  callId,
  {
    text: 'No songs detected',
    voiceName: 'Emma',
    loop: 1
  }
);

For more information see https://developer.nexmo.com/api/voice#startTalk

Stop synthesized text in a call

nexmo.calls.talk.stop(callId);

For more information see https://developer.nexmo.com/api/voice#stopTalk

Send DTMF to a Call

nexmo.calls.dtmf.send(callId, params, callback);

For more information see https://developer.nexmo.com/api/voice#startDTMF

Files

For detailed information please see the documentation at https://developer.nexmo.com/voice/voice-api/guides/recording

Get a file (recording)

nexmo.files.get(fileIdOrUrl, callback);

Save a file (recording)

nexmo.files.save(fileIdOrUrl, file, callback);

Verify

Submit a Verification Request

nexmo.verify.request({number:<NUMBER_TO_BE_VERIFIED>,brand:<NAME_OF_THE_APP>},callback);

For more information check the documentation at https://developer.nexmo.com/api/verify#verify-request

Validate the response of a Verification Request

nexmo.verify.check({request_id:<UNIQUE_ID_FROM_VERIFICATION_REQUEST>,code:<CODE_TO_CHECK>},callback);

For more information check the documentation at https://developer.nexmo.com/api/verify#verify-check

Search one or more Verification Request

nexmo.verify.search(<ONE_REQUEST_ID or ARRAY_OF_REQUEST_ID>,callback);

For more information check the documentation at https://developer.nexmo.com/api/verify#verify-search

Cancel verification

nexmo.verify.control({request_id:<UNIQUE_ID_FROM_VERIFICATION_REQUEST>,cmd:'cancel'},callback);

For more information check the documentation at https://developer.nexmo.com/api/verify#verify-control

Trigger next verification event

nexmo.verify.control({request_id:<UNIQUE_ID_FROM_VERIFICATION_REQUEST>,cmd:'trigger_next_event'},callback);

For more information check the documentation at https://developer.nexmo.com/api/verify#verify-control

Number Insight

Basic

nexmo.numberInsight.get({level: 'basic', number: NUMBER}, callback);

For more information check the documentation at https://developer.nexmo.com/number-insight/building-blocks/number-insight-basic/node

Example:

nexmo.numberInsight.get({level: 'basic', number: '1-234-567-8900'},  callback);

Standard

nexmo.numberInsight.get({level: 'standard', number: NUMBER}, callback);

For more information check the documentation at https://developer.nexmo.com/number-insight/building-blocks/number-insight-standard/node

Example:

nexmo.numberInsight.get({level: 'standard', number: '1-234-567-8900'}, callback);

Advanced

nexmo.numberInsight.get({level: 'advancedSync', number: NUMBER}, callback);

For more information check the documentation at https://developer.nexmo.com/number-insight/building-blocks/number-insight-advanced/node

Advanced Async

Number Insight Advanced might take a few seconds to return a result, therefore the option exists to process the result asynchronously through a webhook.

nexmo.numberInsight.get({level: 'advancedAsync', number: NUMBER, callback: "http://example.com"}, callback);

In this case, the result of your insight request is posted to the callback URL as a webhook. For more details on webhooks see the Number Insight Advanced documentation.

Applications

For an overview of applications see https://developer.nexmo.com/concepts/guides/applications

Create an App

nexmo.applications.create(params, callback);

For more information see https://developer.nexmo.com/api/application.v2#createApplication

params can be

{
"name": "My Application",
  "capabilities": {
    "voice": {
      "webhooks": {
        "answer_url": {
          "address": "https://example.com/webhooks/answer",
          "http_method": "POST"
        },
        "event_url": {
          "address": "https://example.com/webhooks/event",
          "http_method": "POST"
        }
      }
    },
    "messages": {
      "webhooks": {
        "inbound_url": {
          "address": "https://example.com/webhooks/inbound",
          "http_method": "POST"
        },
        "status_url": {
          "address": "https://example.com/webhooks/status",
          "http_method": "POST"
        }
      }
    },
    "rtc": {
      "webhooks": {
        "event_url": {
          "address": "https://example.com/webhooks/event",
          "http_method": "POST"
        }
      }
    },
    "vbc": {}
  }
}

Get a single App

nexmo.applications.get(appId, callback, v2flag);

For more information see https://developer.nexmo.com/api/application.v2#getApplication

  • v2flag - if true, you'll receive the V2 API response, else you'll receive a V1 style response from the V2 API

Get Apps by a filter

nexmo.applications.get(options, callback, v2flag);

For more information see https://developer.nexmo.com/api/application.v2#listApplication

  • options - filter options, use {} to get all your applications
  • v2flag - if true, you'll receive the V2 API response, else you'll receive a V1 style response from the V2 API

Update an App

nexmo.applications.update(params, callback);

For more information see https://developer.nexmo.com/api/application.v2#updateApplication

Delete an App

nexmo.application.delete(appId, callback);

For more information see https://developer.nexmo.com/api/application.v2#deleteApplication

Conversations

For an overview of conversations see https://developer.nexmo.com/stitch/overview

Create a Conversation

nexmo.conversations.create(params, callback);

params is a dictionary of parameters per documentation

Get a single Conversation

nexmo.conversations.get(conversationId, callback);

For more information see https://developer.nexmo.com/api/stitch#retrieveConversation

Get Conversations by filter

nexmo.conversations.get(options, callback);

For more information see https://developer.nexmo.com/api/stitch

Update a Conversation

nexmo.conversations.update(conversationId, params, callback);

params is a dictionary of parameters per documentation

Delete a Conversation

nexmo.conversations.delete(conversationId, callback);

For more information see https://developer.nexmo.com/api/stitch#deleteConversation

Add a Member to a Conversation

nexmo.conversations.members.add(conversationId, params, callback);

params is a dictionary of parameters per documentation

Get a single Member

nexmo.conversations.members.get(conversationId, memberId, callback);

For more information see https://developer.nexmo.com/api/stitch#getUser

Get Members by filter

nexmo.conversations.members.get(conversationId, params, callback);

For more information see https://developer.nexmo.com/api/stitch

Users

Create a User

nexmo.users.create(params, callback);

params is a dictionary of parameters per documentation

Get a single User

nexmo.users.get(userId, callback);

For more information see https://developer.nexmo.com/api/stitch#getUser

Get Users by filter

nexmo.users.get(options, callback);

For more information see https://developer.nexmo.com/api/stitch#getUsers

Get all Conversations for a Users

nexmo.users.getConversations(userId, callback);

For more information see https://developer.nexmo.com/api/stitch#getuserConversations

Update a User

nexmo.users.update(userId, params, callback);

params is a dictionary of parameters per documentation

Delete a User

nexmo.users.delete(userId, callback);

For more information see https://developer.nexmo.com/api/stitch#deleteUser

Management

Check Account Balance

nexmo.account.checkBalance(callback);

List Account Secrets

nexmo.account.listSecrets(apiKey, callback);

Get Account Secret

nexmo.account.getSecret(apiKey, secretId, callback);

Create Account Secret

nexmo.account.createSecret(apiKey, secret, callback);

Delete Account Secret

nexmo.account.deleteSecret(apiKey, secretId, callback);

Get Pricing for sending a message to a country.

nexmo.number.getPricing(countryCode, callback);
  • countryCode - 2 letter ISO Country Code

Get Pricing for sending a message or making a call to a number.

nexmo.number.getPhonePricing(product, msisdn, callback);
  • product - either voice or sms
  • msisdn - Mobile Station International Subscriber Directory Number (MSISDN) is a number used to identify a mobile phone number internationally. i.e. 447700900000

Get all numbers associated with the account.

nexmo.number.get(options, callback);
  • options parameter is an optional Dictionary Object containing any of the following parameters
    • pattern
    • search_pattern
    • index
    • size

For more details about these options, refer to the Numbers API reference

Example:

nexmo.number.get({pattern:714,index:1,size:50,search_pattern:2}, callback);

Search for MSISDN's available to purchase

nexmo.number.search(countryCode,options,callback);

options parameter is optional. They can be one of the following :

  1. number pattern to match the search (eg. 1408)
  2. Dictionary Object optionally containing the following parameters :
  • pattern
  • search_pattern
  • type
  • features
  • index
  • size

For more details about these options, refer to the Numbers API reference

Example:

nexmo.number.search('US',{pattern:3049,index:1,size:50,type:'mobile-lvn',features:'VOICE',search_pattern:2}, callback);

Purchase Number

nexmo.number.buy(countryCode, msisdn, callback);

For more details on these parameters, see the Numbers API reference.

Cancel Number

nexmo.number.cancel(countryCode, msisdn, callback);

For more details on these parameters, see the Numbers API reference.

Update Number

nexmo.number.update(countryCode, msisdn, params, callback);

params is a dictionary of parameters as described in the Numbers API reference.

Update Password (API Secret)

nexmo.account.updatePassword(<NEW_PASSWORD>,callback);

Update Callback URL associated to the account

nexmo.account.updateSMSCallback(<NEW_CALLBACK_URL>,callback);

Change Delivery Receipt URL associated to the account

nexmo.account.updateDeliveryReceiptCallback(<NEW_DR_CALLBACK_URL>,callback);

Redact

Redact a specific ID

nexmo.redact.transaction(id, type, callback);

Media

Upload a file

nexmo.media.upload({"file": "/path/to/file"}, callback);

Upload from a URL

nexmo.media.upload({"url": "https://example.com/ncco.json"}, callback);

Search existing media

// See https://ea.developer.nexmo.com/api/media#search-media-files
// for possible search parameters
nexmo.media.search({ page_size: 1, page_index: 1 }, callback);

Download media

nexmo.media.download(id, callback);

Delete media

nexmo.media.delete(id, callback);

Update media

nexmo.media.update(id, body, callback);

Get media details

nexmo.media.get(id, callback);

Channel

Send a message

nexmo.channel.send(
  { type: "<TYPE>", number: "<TO>"},
  { type: "<TYPE>", number: "<FROM>"},
  { content: { type: "text", text: "testing" } },
  callback
);

Dispatch

Create a dispatch

nexmo.dispatch.create(
  "failover",
  [
    {
      to: { type: "viber_service_msg", id: "<TO>"},
      from: { type: "viber_service_msg", id: "<FROM>" },
      message: {
        content: {
          type: "text",
          text: "<CONTENT>"
        },
        viber_service_msg: {
          ttl: 30
        }
      },
      failover: {
        expiry_time: 600,
        condition_status: "delivered"
      }
    },
    {
      to: { type: "sms", number: "<TO>" },
      from: { type: "sms", number: "<FROM>" },
      message: {
        content: {
          type: "text",
          text: "<CONTENT>"
        }
      }
    }
  ],
  callback
);

JWT

There are two ways of generating a JWT. You can use the function that exists on the Nexmo definition:

const Nexmo = require('nexmo');

const jwt = Nexmo.generateJwt('path/to/private.key', {application_id: APP_ID});

Or via a Nexmo instance where your supplied applicationId and privateKey credentials will be used:

const Nexmo = require('nexmo');

const nexmo = new Nexmo({
    applicationId: APP_ID,
    privateKey: PRIVATE_KEY_PATH,
  });

const jwt = nexmo.generateJwt();

Signature

There are two ways of generating a signature hash. Both strip the sig parameter if supplied. You can use the function that exists on the Nexmo definition:

const Nexmo = require('nexmo');

const hash = Nexmo.generateSignature(SIGNATURE_METHOD, SIGNATURE_SECRET, params);

Or via a Nexmo instance where your supplied signatureSecret and signatureMethod:

const Nexmo = require('nexmo');

const nexmo = new Nexmo({
    apiKey: API_KEY,
    apiSecret: API_SECRET,
    signatureSecret: SIGNATURE_SECRET,
    signatureMethod: SIGNATURE_METHOD,
  });

const hash = nexmo.generateSignature();

SIGNATURE_METHOD is the signature method matching the one you gave Nexmo. Must be one of "md5hash", "md5", "sha1", "sha256", or "sha512".

Voice (Deprecated)

Send TTS Message

nexmo.voice.sendTTSMessage(<TO_NUMBER>,message,options,callback);

Send TTS Prompt With Capture

nexmo.sendTTSPromptWithCapture(<TO_NUMBER>,message,<MAX_DIGITS>, <BYE_TEXT>,options,callback);

Send TTS Prompt With Confirm

nexmo.voice.sendTTSPromptWithConfirm(<TO_NUMBER>, message ,<MAX_DIGITS>,'<PIN_CODE>',<BYE_TEXT>,<FAILED_TEXT>,options,callback);

Testing

Run:

npm test

Or to continually watch and run tests as you change the code:

npm run-script test-watch

Examples

See examples/README.md.

Also, see the Nexmo Node Quickstarts repo.

Creating your own requests

IMPORTANT

This section uses internal APIs and should not be relied on. We make no guarantees that the interface is stable. Relying on these methods is not recommended for production applications

For endpoints that are not yet implemented, you can use the Nexmo HTTP Client to make requests with the correct authentication method.

In these examples, we assume that you've created a nexmo instance as follows:

const nexmo = new Nexmo({
    apiKey: 'API_KEY',
    apiSecret: 'API_SECRET',
    applicationId: 'APPLICATION_ID',
    privateKey: './private.key',
});
  • If your API endpoint is on api.nexmo.com, use the nexmo.options.api object.
  • If your API endpoint is on rest.nexmo.com, use the nexmo.options.rest object.

Both of these objects expose the following methods:

  • get(path, params, callback, useJwt) (params is the query string to use)
  • post(path, params, callback, useJwt) (params is the POST body to send)
  • postUseQueryString(path, params, callback, useJwt) (params is the query string to use)
  • delete(path, callback, useJwt)

To make a request to api.nexmo.com/v1/calls?status=rejected:

nexmo.options.api.get(
    "/v1/calls",
    {"status": "rejected"},
    function(err, data){
        console.log(err);
        console.log(data);
    },
    true // Use JWT for authentication
);

To make a request to rest.nexmo.com/sms/json?from=Demo&to=447700900000&text=Testing:

nexmo.options.rest.postUseQueryString(
    "/sms/json",
    {"from": "Demo", "to": "447700900000", "text": "Testing"},
    function(err, data){
        console.log(err);
        console.log(data);
    },
    false // Don't use JWT, fall back to API key/secret
);

API Coverage

  • Voice
    • Outbound Calls
    • Inbound Call Webhook
    • Update Calls
    • Stream to Call
    • Talk to Call
    • DTMF to Call
  • Messaging
    • Send
    • Delivery Receipt Webhook
    • Inbound Message Webhook
    • Search
      • Message
      • Messages
      • Rejections
    • US Short Codes
      • Two-Factor Authentication
      • Event-Based Alerts
        • Sending Alerts
        • Campaign Subscription Management
  • Number Insight
    • Basic
    • Standard
    • Advanced
    • Advanced Async
    • Advanced Async Webhook
  • Verify
    • Verify
    • Check
    • Search
    • Control
  • Applications
    • Create an Application
    • Get Applications
    • Update an Application
    • Delete an Application
  • Conversations
    • Create a Conversation
    • Get Conversations
    • Update a Conversation
    • Delete a Conversation
    • Add a Member to a Conversation
    • Get Members
  • Users
    • Create a User
    • Get Users
    • Get Conversations for a User
    • Update a User
    • Delete a User
  • Account
    • Balance
    • Pricing
    • Settings
    • Top Up
    • Numbers
      • Search
      • Buy
      • Cancel
      • Update
  • Media
    • Upload
    • Download
    • Search
    • Get
    • Update
    • Delete
  • Channel
    • Send
  • Workflow
    • Create
  • Voice (Deprecated)
    • Outbound Calls
    • Inbound Call Webhook
    • Text-To-Speech Call
    • Text-To-Speech Prompt
  • Redact
    • Transaction

License

MIT - see LICENSE

Keywords

FAQs

Package last updated on 12 Sep 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc