UNPKG

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