Neurological Phenomenon Multiplexer
    Share your code. npm Orgs help your team discover, share, and reuse code. Create a free org »

    nexmopublic

    Nexmo Client Library for Node.js build status

    A Node.JS REST API Wrapper library for Nexmo.

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

    NPM

    Installation | Constructor | Messaging | Voice | Verify | Number Insight | Applications | Management | JWT (JSON Web Token)

    Installation

    npm install nexmo

    Constructor

    var Nexmo = require('nexmo');
     
    var nexmo = new Nexmo({
        apiKey: API_KEY,
        apiSecret: API_SECRET,
        applicationId: APP_ID,
        privateKey: PRIVATE_KEY_PATH,
      }, options);
    • apiKey - API Key from Nexmo
    • apiSecret - API SECRET from Nexmo
    • applicationId - The Nexmo Application ID to be used when creating JWTs. Required for voice related functionality.
    • privateKey - The Private Key to be used when creating JWTs. You can specify the key as any of the following:
      • The private key as a string (It must start with -----BEGIN PRIVATE KEY-----)
      • A Buffer containing the file contents. Required for voice related functionality.
      • A path to the key file on disk
    • options - 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://docs.nexmo.com/voice/voice-api

    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://docs.nexmo.com/voice/voice-api/api-reference#call_create

    Get a Call

    nexmo.calls.get(callId, callback);

    For more information see https://docs.nexmo.com/voice/voice-api/api-reference#call_create

    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#modify-an-existing-call

    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://docs.nexmo.com/voice/voice-api/api-reference#stream_put

    Stop an audio stream in a call

    nexmo.calls.stream.stop(callId);

    For more information see https://docs.nexmo.com/voice/voice-api/api-reference#stream_delete

    Play synthesized text in a call

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

    For more information see https://docs.nexmo.com/voice/voice-api/api-reference#talk_put

    Stop synthesized text in a call

    nexmo.calls.talk.stop(callId);

    Send DTMF to a Call

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

    For more information see https://docs.nexmo.com/voice/voice-api/api-reference#dtmf_put

    Files

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

    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://docs.nexmo.com/verify/api-reference/api-reference#vrequest

    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://docs.nexmo.com/verify/api-reference/api-reference#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://docs.nexmo.com/verify/api-reference/api-reference#search

    Cancel verification

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

    For more information check the documentation at https://docs.nexmo.com/verify/api-reference/api-reference#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://docs.nexmo.com/verify/api-reference/api-reference#control

    Number Insight

    Basic

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

    For more information check the documentation at https://docs.nexmo.com/number-insight/basic

    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://docs.nexmo.com/number-insight/standard

    Example:

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

    Advanced

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

    For more information check the documentation at https://docs.nexmo.com/number-insight/advanced

    Advanced Async

    Number Insight Advanced might take a few seconds to return a result, therefore the option exist 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://docs.nexmo.com/tools/application-api

    Create an App

    nexmo.applications.create(name, type, answerUrl, eventUrl, options, callback);

    For more information see https://docs.nexmo.com/tools/application-api/api-reference#create

    Get a single App

    nexmo.applications.get(appId, callback);

    For more information see https://docs.nexmo.com/tools/application-api/api-reference#retrieve

    Get Apps by filter

    nexmo.application.get(options, callback);

    For more information see https://docs.nexmo.com/tools/application-api/api-reference#list

    Update an App

    nexmo.applications.update(appId, name, type, answerUrl, eventUrl, options, callback);

    For more information see https://docs.nexmo.com/tools/application-api/api-reference#update

    Delete an App

    nexmo.application.delete(appId, callback);

    For more information see https://docs.nexmo.com/tools/application-api/api-reference#delete

    Management

    Check Account Balance

    nexmo.account.checkBalance(callback);

    Get Pricing for sending message to a country.

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

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

    nexmo.number.getPhonePricing(product, countryCode, callback);
    • product - either voice or sms
    • countryCode - 2 letter ISO Country Code

    Get all numbers associated to 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 on what the above options mean refer to the Nexmo API documentation

    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
    • features
    • index
    • size

    For more details on what the above options mean refer to the Nexmo API documentation

    Example:

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

    Purchase number

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

    Cancel Number

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

    Update Number

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

    params is a dictionary of parameters per documentation

    Update Password (API Secret)

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

    Update Callback URL associated to the account

    nexmo.updateSMSCallback(<NEW_CALLBACK_URL>,callback);

    Change Delivery Receipt URL associated to the account

    nexmo.account.updateDeliveryReceiptCallback(<NEW_DR_CALLBACK_URL>,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);

    JWT

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

    var Nexmo = require('nexmo');
     
    var 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:

    var Nexmo = require('nexmo');
     
    var nexmo = new Nexmo({
        apiKey: API_KEY,
        apiSecret: API_SECRET,
        applicationId: APP_ID,
        privateKey: PRIVATE_KEY_PATH,
      });
     
    var jwt = nexmo.generateJwt();

    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:

    var 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
    • Account
      • Balance
      • Pricing
      • Settings
      • Top Up
      • Numbers
        • Search
        • Buy
        • Cancel
        • Update
    • Media
      • Upload
      • Download
      • Search
      • Get
      • Update
      • Delete
    • Voice (Deprecated)
      • Outbound Calls
      • Inbound Call Webhook
      • Text-To-Speech Call
      • Text-To-Speech Prompt

    License

    MIT - see LICENSE

    install

    npm i nexmo

    Downloadsweekly downloads

    9,846

    version

    2.2.1

    license

    MIT

    repository

    githubgithub

    last publish

    collaborators

    • avatar
    • avatar
    • avatar
    • avatar
    • avatar