UNPKG

16.2 kBMarkdownView Raw
1# Nexmo Client Library for Node.js [![build status](https://secure.travis-ci.org/Nexmo/nexmo-node.png)](http://travis-ci.org/Nexmo/nexmo-node)
2
3A Node.JS REST API Wrapper library for [Nexmo](http://nexmo.com/).
4
5For full API documentation refer to [docs.nexmo.com](https://docs.nexmo.com/).
6
7[![NPM](https://nodei.co/npm/nexmo.png)](https://nodei.co/npm/nexmo/)
8
9[Installation](#installation) | [Constructor](#constructor) | [Messaging](#messaging) | [Voice](#voice) | [Verify](#verify) | [Number Insight](#number-insight) | [Applications](#applications) | [Management](#management) | [Redact](#redact) | [JWT (JSON Web Token)](#jwt)
10
11## Installation
12
13```bash
14npm install nexmo
15```
16
17## Constructor
18
19```js
20var Nexmo = require('nexmo');
21
22var nexmo = new Nexmo({
23 apiKey: API_KEY,
24 apiSecret: API_SECRET,
25 applicationId: APP_ID,
26 privateKey: PRIVATE_KEY_PATH,
27 }, options);
28```
29
30* `apiKey` - API Key from Nexmo
31* `apiSecret` - API SECRET from Nexmo
32* `applicationId` - The Nexmo Application ID to be used when creating JWTs. Required for voice related functionality.
33* `privateKey` - The Private Key to be used when creating JWTs. You can specify the key as any of the following:
34 * The private key as a string (It must start with `-----BEGIN PRIVATE KEY-----`)
35 * A [Buffer](https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_string_encoding) containing the file contents. Required for voice related functionality.
36 * A path to the key file on disk
37* `options` - Additional options for the constructor
38
39Options are:
40
41```js
42{
43 // If true, log information to the console
44 debug: true|false,
45 // append info the the User-Agent sent to Nexmo
46 // e.g. pass 'my-app' for /nexmo-node/1.0.0/4.2.7/my-app
47 appendToUserAgent: string,
48 // Set a custom logger
49 logger: {
50 log: function() {level, args...}
51 info: function() {args...},
52 warn: function() {args...}
53 },
54 // Set a custom timeout for requests to Nexmo in milliseconds. Defaults to the standard for Node http requests, which is 120,000 ms.
55 timeout: integer
56}
57```
58
59## Messaging
60
61### Send a text message
62
63```js
64nexmo.message.sendSms(sender, recipient, message, options, callback);
65```
66
67* `opts` - parameter is optional. See [SMS API Reference](https://docs.nexmo.com/messaging/sms-api/api-reference#request)
68
69### Send a Binary Message
70
71```js
72nexmo.message.sendBinaryMessage(fromnumber, tonumber, body, udh, callback);
73```
74
75* `body` - Hex encoded binary data
76* `udh` - Hex encoded udh
77
78### Send a WAP Push Message
79
80```js
81nexmo.message.sendWapPushMessage(fromnumber, tonumber, title, url, validity, callback);
82```
83
84* `validity` - is optional (if given should be in milliseconds)
85
86### Send a Short Code alert
87
88```js
89nexmo.message.shortcodeAlert(recipient, messageParams, opts, callback);
90```
91
92## Voice
93
94For detailed information please see the documentation at https://docs.nexmo.com/voice/voice-api
95
96### Make a call
97
98Requires `applicationId` and `privateKey` to be set on the constructor.
99
100```js
101nexmo.calls.create({
102 to: [{
103 type: 'phone',
104 number: TO_NUMBER
105 }],
106 from: {
107 type: 'phone',
108 number: FROM_NUMBER
109 },
110 answer_url: [ANSWER_URL]
111}, callback);
112```
113
114For more information see https://docs.nexmo.com/voice/voice-api/api-reference#call_create
115
116### Get a Call
117
118```js
119nexmo.calls.get(callId, callback);
120```
121
122For more information see https://docs.nexmo.com/voice/voice-api/api-reference#call_create
123
124### Query Calls
125
126```
127nexmo.calls.get({status: 'completed'}, callback);
128```
129
130The first parameter can contain many properties to filter the returned call or to page results. For more information see the [Calls API Reference](https://docs.nexmo.com/voice/voice-api/api-reference#calls).
131
132### Update a Call
133
134```js
135nexmo.calls.update(callId, { action: 'hangup' }, callback);
136```
137
138For more information see https://developer.nexmo.com/api/voice#modify-an-existing-call
139
140### Stream an Audio File to a Call
141
142```js
143nexmo.calls.stream.start(
144 callId,
145 {
146 stream_url: [
147 'https://nexmo-community.github.io/ncco-examples/assets/voice_api_audio_streaming.mp3'
148 ],
149 loop: 1
150 });
151```
152
153For more information see https://docs.nexmo.com/voice/voice-api/api-reference#stream_put
154
155### Stop an audio stream in a call
156
157```js
158nexmo.calls.stream.stop(callId);
159```
160
161For more information see https://docs.nexmo.com/voice/voice-api/api-reference#stream_delete
162
163### Play synthesized text in a call
164
165```js
166nexmo.calls.talk.start(
167 callId,
168 {
169 text: 'No songs detected',
170 voiceName: 'Emma',
171 loop: 1
172 }
173);
174```
175
176For more information see https://docs.nexmo.com/voice/voice-api/api-reference#talk_put
177
178### Stop synthesized text in a call
179
180```js
181nexmo.calls.talk.stop(callId);
182```
183
184### Send DTMF to a Call
185
186```js
187nexmo.calls.dtmf.send(callId, params, callback);
188```
189
190For more information see https://docs.nexmo.com/voice/voice-api/api-reference#dtmf_put
191
192
193## Files
194
195For detailed information please see the documentation at https://docs.nexmo.com/voice/voice-api/recordings
196
197### Get a file (recording)
198
199```js
200nexmo.files.get(fileIdOrUrl, callback);
201```
202
203### Save a file (recording)
204
205```js
206nexmo.files.save(fileIdOrUrl, file, callback);
207```
208
209## Verify
210
211### Submit a Verification Request
212
213```js
214nexmo.verify.request({number:<NUMBER_TO_BE_VERIFIED>,brand:<NAME_OF_THE_APP>},callback);
215```
216
217For more information check the documentation at https://docs.nexmo.com/verify/api-reference/api-reference#vrequest
218
219### Validate the response of a Verification Request
220
221```js
222nexmo.verify.check({request_id:<UNIQUE_ID_FROM_VERIFICATION_REQUEST>,code:<CODE_TO_CHECK>},callback);
223```
224
225For more information check the documentation at https://docs.nexmo.com/verify/api-reference/api-reference#check
226
227### Search one or more Verification Request
228
229```js
230nexmo.verify.search(<ONE_REQUEST_ID or ARRAY_OF_REQUEST_ID>,callback);
231```
232
233For more information check the documentation at https://docs.nexmo.com/verify/api-reference/api-reference#search
234
235### Cancel verification
236
237```js
238nexmo.verify.control({request_id:<UNIQUE_ID_FROM_VERIFICATION_REQUEST>,cmd:'cancel'},callback);
239```
240
241For more information check the documentation at https://docs.nexmo.com/verify/api-reference/api-reference#control
242
243### Trigger next verification event
244
245```js
246nexmo.verify.control({request_id:<UNIQUE_ID_FROM_VERIFICATION_REQUEST>,cmd:'trigger_next_event'},callback);
247```
248
249For more information check the documentation at https://docs.nexmo.com/verify/api-reference/api-reference#control
250
251## Number Insight
252
253### Basic
254
255```js
256nexmo.numberInsight.get({level: 'basic', number: NUMBER}, callback);
257```
258
259For more information check the documentation at https://docs.nexmo.com/number-insight/basic
260
261Example:
262
263```js
264nexmo.numberInsight.get({level: 'basic', number: '1-234-567-8900'}, callback);
265```
266
267### Standard
268
269```js
270nexmo.numberInsight.get({level: 'standard', number: NUMBER}, callback);
271```
272
273For more information check the documentation at https://docs.nexmo.com/number-insight/standard
274
275Example:
276
277```js
278nexmo.numberInsight.get({level: 'standard', number: '1-234-567-8900'}, callback);
279```
280
281### Advanced
282
283```js
284nexmo.numberInsight.get({level: 'advanced', number: NUMBER}, callback);
285```
286
287For more information check the documentation at https://docs.nexmo.com/number-insight/advanced
288
289### Advanced Async
290
291Number Insight Advanced might take a few seconds to return a result, therefore the option exist to process the result asynchronously through a webhook.
292
293```js
294nexmo.numberInsight.get({level: 'advancedAsync', number: NUMBER, callback: "http://example.com"}, callback);
295```
296
297In 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](https://docs.nexmo.com/number-insight/advanced-async) documentation.
298
299## Applications
300
301For an overview of applications see https://docs.nexmo.com/tools/application-api
302
303### Create an App
304
305```js
306nexmo.applications.create(name, type, answerUrl, eventUrl, options, callback);
307```
308
309For more information see https://docs.nexmo.com/tools/application-api/api-reference#create
310
311### Get a single App
312
313```js
314nexmo.applications.get(appId, callback);
315```
316
317For more information see https://docs.nexmo.com/tools/application-api/api-reference#retrieve
318
319### Get Apps by filter
320
321```js
322nexmo.application.get(options, callback);
323```
324
325For more information see https://docs.nexmo.com/tools/application-api/api-reference#list
326
327### Update an App
328
329```js
330nexmo.applications.update(appId, name, type, answerUrl, eventUrl, options, callback);
331```
332
333For more information see https://docs.nexmo.com/tools/application-api/api-reference#update
334
335### Delete an App
336
337```js
338nexmo.application.delete(appId, callback);
339```
340
341For more information see https://docs.nexmo.com/tools/application-api/api-reference#delete
342
343## Management
344
345### Check Account Balance
346
347```js
348nexmo.account.checkBalance(callback);
349```
350
351### Get Pricing for sending message to a country.
352
353```js
354nexmo.number.getPricing(countryCode, callback);
355```
356
357* `countryCode` - 2 letter ISO Country Code
358
359### Get Pricing for sending message or making a call to a number.
360
361```js
362nexmo.number.getPhonePricing(product, countryCode, callback);
363```
364
365* `product` - either `voice` or `sms`
366* `countryCode` - 2 letter ISO Country Code
367
368### Get all numbers associated to the account.
369
370```js
371nexmo.number.get(options, callback);
372```
373
374* `options` parameter is an optional Dictionary Object containing any of the following parameters
375 * `pattern`
376 * `search_pattern`
377 * `index`
378 * `size`
379
380For more details on what the above options mean refer to the Nexmo API [documentation](https://docs.nexmo.com/tools/developer-api/account-numbers)
381
382Example:
383
384```js
385nexmo.number.get({pattern:714,index:1,size:50,search_pattern:2}, callback);
386```
387
388### Search for MSISDN's available to purchase
389
390```js
391nexmo.number.search(countryCode,options,callback);
392```
393
394`options` parameter is optional. They can be one of the following :
395
3961. number pattern to match the search (eg. 1408)
3972. Dictionary Object optionally containing the following parameters :
398 * `pattern`
399 * `search_pattern`
400 * `features`
401 * `index`
402 * `size`
403
404For more details on what the above options mean refer to the Nexmo API [documentation](https://docs.nexmo.com/tools/developer-api/number-search)
405
406Example:
407
408```js
409nexmo.number.search('US',{pattern:3049,index:1,size:50,features:'VOICE',search_pattern:2}, callback);
410```
411
412### Purchase number
413
414```js
415nexmo.number.buy(countryCode, msisdn, callback);
416```
417
418### Cancel Number
419
420```js
421nexmo.number.cancel(countryCode, msisdn, callback);
422```
423
424### Update Number
425
426```js
427nexmo.number.update(countryCode, msisdn, params, callback);
428```
429
430params is a dictionary of parameters per [documentation](https://docs.nexmo.com/index.php/developer-api/number-update)
431
432### Update Password (API Secret)
433
434```js
435nexmo.account.updatePassword(<NEW_PASSWORD>,callback);
436```
437
438### Update Callback URL associated to the account
439
440```js
441nexmo.updateSMSCallback(<NEW_CALLBACK_URL>,callback);
442```
443
444### Change Delivery Receipt URL associated to the account
445
446```js
447nexmo.account.updateDeliveryReceiptCallback(<NEW_DR_CALLBACK_URL>,callback);
448```
449
450## Redact
451
452### Redact a specific ID
453
454```js
455nexmo.redact.transaction(id, type, callback);
456```
457
458## Media
459
460### Upload a file
461
462```js
463nexmo.media.upload({"file": "/path/to/file"}, callback);
464```
465
466### Upload from a URL
467
468```js
469nexmo.media.upload({"url": "https://example.com/ncco.json"}, callback);
470```
471
472### Search existing media
473
474```js
475// See https://ea.developer.nexmo.com/api/media#search-media-files
476// for possible search parameters
477nexmo.media.search({ page_size: 1, page_index: 1 }, callback);
478```
479
480### Download media
481
482```js
483nexmo.media.download(id, callback);
484```
485
486### Delete media
487
488```js
489nexmo.media.delete(id, callback);
490```
491
492### Update media
493
494```js
495nexmo.media.update(id, body, callback);
496```
497
498### Get media details
499
500```js
501nexmo.media.get(id, callback);
502```
503
504## JWT
505
506There are two ways of generating a JWT. You can use the function that exists on the Nexmo definition:
507
508```js
509var Nexmo = require('nexmo');
510
511var jwt = Nexmo.generateJwt('path/to/private.key', {application_id: APP_ID});
512```
513
514Or via a `Nexmo` instance where your supplied `applicationId` and `privateKey` credentials will be used:
515
516```js
517var Nexmo = require('nexmo');
518
519var nexmo = new Nexmo({
520 apiKey: API_KEY,
521 apiSecret: API_SECRET,
522 applicationId: APP_ID,
523 privateKey: PRIVATE_KEY_PATH,
524 });
525
526var jwt = nexmo.generateJwt();
527```
528
529## Voice (Deprecated)
530
531### Send TTS Message
532
533```js
534nexmo.voice.sendTTSMessage(<TO_NUMBER>,message,options,callback);
535```
536
537### Send TTS Prompt With Capture
538
539```js
540nexmo.sendTTSPromptWithCapture(<TO_NUMBER>,message,<MAX_DIGITS>, <BYE_TEXT>,options,callback);
541```
542
543### Send TTS Prompt With Confirm
544
545```js
546nexmo.voice.sendTTSPromptWithConfirm(<TO_NUMBER>, message ,<MAX_DIGITS>,'<PIN_CODE>',<BYE_TEXT>,<FAILED_TEXT>,options,callback);
547```
548
549## Testing
550
551Run:
552
553```bash
554npm test
555```
556
557Or to continually watch and run tests as you change the code:
558
559```bash
560npm run-script test-watch
561```
562
563## Examples
564
565See [examples/README.md](examples/README.md).
566
567Also see the [Nexmo Node Quickstarts repo](https://github.com/nexmo-community/nexmo-node-quickstart).
568
569## Creating your own requests
570
571> !!!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
572
573For endpoints that are not yet implemented, you can use the Nexmo HTTP Client to
574make requests with the correct authentication method.
575
576In these examples, we assume that you've created a `nexmo` instance as follows:
577
578```javascript
579var nexmo = new Nexmo({
580 apiKey: 'API_KEY',
581 apiSecret: 'API_SECRET',
582 applicationId: 'APPLICATION_ID',
583 privateKey: './private.key',
584});
585```
586
587* If your API endpoint is on `api.nexmo.com`, use the `nexmo.options.api` object.
588* If your API endpoint is on `rest.nexmo.com`, use the `nexmo.options.rest` object.
589
590Both of these objects expose the following methods:
591
592* `get(path, params, callback, useJwt)` (`params` is the query string to use)
593* `post(path, params, callback, useJwt)` (`params` is the POST body to send)
594* `postUseQueryString(path, params, callback, useJwt)` (`params` is the query string to use)
595* `delete(path, callback, useJwt)`
596
597To make a request to `api.nexmo.com/v1/calls?status=rejected`:
598
599```javascript
600nexmo.options.api.get(
601 "/v1/calls",
602 {"status": "rejected"},
603 function(err, data){
604 console.log(err);
605 console.log(data);
606 },
607 true // Use JWT for authentication
608);
609```
610
611To make a request to `rest.nexmo.com/sms/json?from=Demo&to=447700900000&text=Testing`:
612
613```javascript
614nexmo.options.rest.postUseQueryString(
615 "/sms/json",
616 {"from": "Demo", "to": "447700900000", "text": "Testing"},
617 function(err, data){
618 console.log(err);
619 console.log(data);
620 },
621 false // Don't use JWT, fall back to API key/secret
622);
623```
624
625## API Coverage
626
627* Voice
628 * [x] Outbound Calls
629 * [ ] Inbound Call Webhook
630 * [x] Update calls
631 * [x] Stream to Call
632 * [x] Talk to Call
633 * [x] DTMF to Call
634* Messaging
635 * [x] Send
636 * [ ] Delivery Receipt Webhook
637 * [ ] Inbound Message Webhook
638 * [x] Search
639 * [x] Message
640 * [x] Messages
641 * [x] Rejections
642 * [ ] US Short Codes
643 * [ ] Two-Factor Authentication
644 * [ ] Event Based Alerts
645 * [ ] Sending Alerts
646 * [ ] Campaign Subscription Management
647* Number Insight
648 * [X] Basic
649 * [X] Standard
650 * [X] Advanced
651 * [X] Advanced Async
652 * [ ] Advanced Async Webhook
653* Verify
654 * [x] Verify
655 * [x] Check
656 * [x] Search
657 * [x] Control
658* Applications
659 * [x] Create an Application
660 * [x] Get Applications
661 * [x] Update an Application
662 * [x] Delete an Application
663* Account
664 * [X] Balance
665 * [x] Pricing
666 * [x] Settings
667 * [x] Top Up
668 * [x] Numbers
669 * [x] Search
670 * [x] Buy
671 * [x] Cancel
672 * [x] Update
673* Media
674 * [x] Upload
675 * [x] Download
676 * [x] Search
677 * [x] Get
678 * [x] Update
679 * [x] Delete
680* Voice (Deprecated)
681 * [x] Outbound Calls
682 * [ ] Inbound Call Webhook
683 * [x] Text-To-Speech Call
684 * [x] Text-To-Speech Prompt
685* Redact
686 * [x] Transaction
687
688
689## License
690
691MIT - see [LICENSE](LICENSE.txt)