UNPKG

15.4 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) | [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## JWT
451
452There are two ways of generating a JWT. You can use the function that exists on the Nexmo definition:
453
454```js
455var Nexmo = require('nexmo');
456
457var jwt = Nexmo.generateJwt('path/to/private.key', {application_id: APP_ID});
458```
459
460Or via a `Nexmo` instance where your supplied `applicationId` and `privateKey` credentials will be used:
461
462```js
463var Nexmo = require('nexmo');
464
465var nexmo = new Nexmo({
466 apiKey: API_KEY,
467 apiSecret: API_SECRET,
468 applicationId: APP_ID,
469 privateKey: PRIVATE_KEY_PATH,
470 });
471
472var jwt = nexmo.generateJwt();
473```
474
475## Voice (Deprecated)
476
477### Send TTS Message
478
479```js
480nexmo.voice.sendTTSMessage(<TO_NUMBER>,message,options,callback);
481```
482
483### Send TTS Prompt With Capture
484
485```js
486nexmo.sendTTSPromptWithCapture(<TO_NUMBER>,message,<MAX_DIGITS>, <BYE_TEXT>,options,callback);
487```
488
489### Send TTS Prompt With Confirm
490
491```js
492nexmo.voice.sendTTSPromptWithConfirm(<TO_NUMBER>, message ,<MAX_DIGITS>,'<PIN_CODE>',<BYE_TEXT>,<FAILED_TEXT>,options,callback);
493```
494
495## Testing
496
497Run:
498
499```bash
500npm test
501```
502
503Or to continually watch and run tests as you change the code:
504
505```bash
506npm run-script test-watch
507```
508
509## Examples
510
511See [examples/README.md](examples/README.md).
512
513Also see the [Nexmo Node Quickstarts repo](https://github.com/nexmo-community/nexmo-node-quickstart).
514
515## Creating your own requests
516
517> !!!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
518
519For endpoints that are not yet implemented, you can use the Nexmo HTTP Client to
520make requests with the correct authentication method.
521
522In these examples, we assume that you've created a `nexmo` instance as follows:
523
524```javascript
525var nexmo = new Nexmo({
526 apiKey: 'API_KEY',
527 apiSecret: 'API_SECRET',
528 applicationId: 'APPLICATION_ID',
529 privateKey: './private.key',
530});
531```
532
533* If your API endpoint is on `api.nexmo.com`, use the `nexmo.options.api` object.
534* If your API endpoint is on `rest.nexmo.com`, use the `nexmo.options.rest` object.
535
536Both of these objects expose the following methods:
537
538* `get(path, params, callback, useJwt)` (`params` is the query string to use)
539* `post(path, params, callback, useJwt)` (`params` is the POST body to send)
540* `postUseQueryString(path, params, callback, useJwt)` (`params` is the query string to use)
541* `delete(path, callback, useJwt)`
542
543To make a request to `api.nexmo.com/v1/calls?status=rejected`:
544
545```javascript
546nexmo.options.api.get(
547 "/v1/calls",
548 {"status": "rejected"},
549 function(err, data){
550 console.log(err);
551 console.log(data);
552 },
553 true // Use JWT for authentication
554);
555```
556
557To make a request to `rest.nexmo.com/sms/json?from=Demo&to=447700900000&text=Testing`:
558
559```javascript
560nexmo.options.rest.postUseQueryString(
561 "/sms/json",
562 {"from": "Demo", "to": "447700900000", "text": "Testing"},
563 function(err, data){
564 console.log(err);
565 console.log(data);
566 },
567 false // Don't use JWT, fall back to API key/secret
568);
569```
570
571## API Coverage
572
573* Voice
574 * [x] Outbound Calls
575 * [ ] Inbound Call Webhook
576 * [x] Update calls
577 * [x] Stream to Call
578 * [x] Talk to Call
579 * [x] DTMF to Call
580* Messaging
581 * [x] Send
582 * [ ] Delivery Receipt Webhook
583 * [ ] Inbound Message Webhook
584 * [x] Search
585 * [x] Message
586 * [x] Messages
587 * [x] Rejections
588 * [ ] US Short Codes
589 * [ ] Two-Factor Authentication
590 * [ ] Event Based Alerts
591 * [ ] Sending Alerts
592 * [ ] Campaign Subscription Management
593* Number Insight
594 * [X] Basic
595 * [X] Standard
596 * [X] Advanced
597 * [X] Advanced Async
598 * [ ] Advanced Async Webhook
599* Verify
600 * [x] Verify
601 * [x] Check
602 * [x] Search
603 * [x] Control
604* Applications
605 * [x] Create an Application
606 * [x] Get Applications
607 * [x] Update an Application
608 * [x] Delete an Application
609* Account
610 * [X] Balance
611 * [x] Pricing
612 * [x] Settings
613 * [x] Top Up
614 * [x] Numbers
615 * [x] Search
616 * [x] Buy
617 * [x] Cancel
618 * [x] Update
619* Media
620 * [x] Upload
621 * [x] Download
622 * [x] Search
623 * [x] Get
624 * [x] Update
625 * [x] Delete
626* Voice (Deprecated)
627 * [x] Outbound Calls
628 * [ ] Inbound Call Webhook
629 * [x] Text-To-Speech Call
630 * [x] Text-To-Speech Prompt
631
632
633## License
634
635MIT - see [LICENSE](LICENSE.txt)