Vonage Developer Center

Communications API

Integrate sms, voice, video and two-factor authentication into your apps with Vonage communication APIs.

Send an SMS

Write the code

Add the following to send-sms.sh:

curl -X "POST" "https://rest.nexmo.com/sms/json" \
  -d "from=$VONAGE_BRAND_NAME" \
  -d "text=A text message sent using the Vonage SMS API" \
  -d "to=$TO_NUMBER" \
  -d "api_key=$VONAGE_API_KEY" \
  -d "api_secret=$VONAGE_API_SECRET"

View full source

Run your code

Save this file to your machine and run it:

sh send-sms.sh

Prerequisites

npm install @vonage/server-sdk

Create a file named send.js and add the following code:

const { Vonage } = require('@vonage/server-sdk')

const vonage = new Vonage({
  apiKey: VONAGE_API_KEY,
  apiSecret: VONAGE_API_SECRET
})

View full source

Write the code

Add the following to send.js:

const from = VONAGE_BRAND_NAME
const to = TO_NUMBER
const text = 'A text message sent using the Vonage SMS API'

async function sendSMS() {
    await vonage.sms.send({to, from, text})
        .then(resp => { console.log('Message sent successfully'); console.log(resp); })
        .catch(err => { console.log('There was an error sending the messages.'); console.error(err); });
}

sendSMS();

View full source

Run your code

Save this file to your machine and run it:

node send.js

Prerequisites

Add the following to `build.gradle`:

compile 'com.vonage:client:6.2.0'

Create a class named SendMessage and add the following code to the main method:

VonageClient client = VonageClient.builder().apiKey(VONAGE_API_KEY).apiSecret(VONAGE_API_SECRET).build();

View full source

Write the code

Add the following to the main method of the SendMessage class:

TextMessage message = new TextMessage(VONAGE_BRAND_NAME,
        TO_NUMBER,
        "A text message sent using the Vonage SMS API"
);

SmsSubmissionResponse response = client.getSmsClient().submitMessage(message);

if (response.getMessages().get(0).getStatus() == MessageStatus.OK) {
    System.out.println("Message sent successfully.");
} else {
    System.out.println("Message failed with error: " + response.getMessages().get(0).getErrorText());
}

View full source

Run your code

We can use the application plugin for Gradle to simplify the running of our application. Update your build.gradle with the following:

  apply plugin: 'application'
  mainClassName = project.hasProperty('main') ? project.getProperty('main') : ''

Run the following gradle command to execute your application, replacing com.vonage.quickstart.sms with the package containing SendMessage:

gradle run -Pmain=com.vonage.quickstart.sms.SendMessage

Prerequisites

Install-Package Vonage

Create a file named SendSms.cs and add the following code:

using Vonage;
using Vonage.Request;

View full source

Add the following to SendSms.cs:

    vonageApiKey,
    vonageApiSecret
    );

var vonageClient = new VonageClient(credentials);

View full source

Write the code

Add the following to SendSms.cs:

{
    To = toNumber,
    From = vonageBrandName,
    Text = "A text message sent using the Vonage SMS API"
});
Console.WriteLine(response.Messages[0].To);

View full source

Prerequisites

composer require vonage/client

Create a file named send-sms.php and add the following code:

$basic  = new \Vonage\Client\Credentials\Basic(VONAGE_API_KEY, VONAGE_API_SECRET);
$client = new \Vonage\Client($basic);

View full source

Write the code

Add the following to send-sms.php:

$response = $client->sms()->send(
    new \Vonage\SMS\Message\SMS(TO_NUMBER, BRAND_NAME, 'A text message sent using the Nexmo SMS API')
);

$message = $response->current();

if ($message->getStatus() == 0) {
    echo "The message was sent successfully\n";
} else {
    echo "The message failed with status: " . $message->getStatus() . "\n";
}

View full source

Run your code

Save this file to your machine and run it:

php send-sms.php

Prerequisites

pip install vonage

Create a file named send-an-sms.py and add the following code:

client = vonage.Client(key=VONAGE_API_KEY, secret=VONAGE_API_SECRET)

View full source

Write the code

Add the following to send-an-sms.py:

responseData = client.sms.send_message(
    {
        "from": VONAGE_BRAND_NAME,
        "to": TO_NUMBER,
        "text": "A text message sent using the Vonage SMS API",
    }
)

if responseData["messages"][0]["status"] == "0":
    print("Message sent successfully.")
else:
    print(f"Message failed with error: {responseData['messages'][0]['error-text']}")

View full source

Run your code

Save this file to your machine and run it:

python send-an-sms.py

Prerequisites

gem install vonage

Create a file named send.rb and add the following code:

client = Vonage::Client.new(
  api_key: VONAGE_API_KEY,
  api_secret: VONAGE_API_SECRET
)

View full source

Write the code

Add the following to send.rb:

client.sms.send(
  from: VONAGE_BRAND_NAME,
  to: TO_NUMBER,
  text: 'A text message sent using the Vonage SMS API'
)

View full source

Run your code

Save this file to your machine and run it:

ruby send.rb

Make a voice call

Prerequisites

Execute the following command at your terminal prompt to create the JWT for authentication:

export JWT=$(nexmo jwt:generate $PATH_TO_PRIVATE_KEY application_id=$NEXMO_APPLICATION_ID)

Write the code

Add the following to make-an-outbound-call.sh:

curl -X POST https://api.nexmo.com/v1/calls\
  -H "Authorization: Bearer "$JWT\
  -H "Content-Type: application/json"\
  -d '{"to":[{"type": "phone","number": "$TO_NUMBER"}],
      "from": {"type": "phone","number": "$VONAGE_NUMBER"},
      "answer_url":["https://raw.githubusercontent.com/nexmo-community/ncco-examples/gh-pages/text-to-speech.json"]}'

View full source

Run your code

Save this file to your machine and run it:

bash make-an-outbound-call.sh

Prerequisites

npm install @vonage/server-sdk

Create a file named make-call.js and add the following code:

const { Vonage } = require('@vonage/server-sdk')

const vonage = new Vonage({
  apiKey: VONAGE_API_KEY,
  apiSecret: VONAGE_API_SECRET,
  applicationId: VONAGE_APPLICATION_ID,
  privateKey: VONAGE_APPLICATION_PRIVATE_KEY_PATH
})

View full source

Write the code

Add the following to make-call.js:

const ANSWER_URL = 'https://raw.githubusercontent.com/nexmo-community/ncco-examples/gh-pages/text-to-speech.json'

vonage.voice.createOutboundCall({
  to: [{
    type: 'phone',
    number: TO_NUMBER
  }],
  from: {
    type: 'phone',
    number: VONAGE_NUMBER
  },
  answer_url: [ANSWER_URL]
})
  .then(resp => console.log(resp))
  .catch(err => console.error(err));

View full source

Run your code

Save this file to your machine and run it:

node make-call.js

Prerequisites

Add the following to `build.gradle`:

compile 'com.vonage:client:6.2.0'

Create a class named OutboundTextToSpeech and add the following code to the main method:

VonageClient client = VonageClient.builder()
        .applicationId(VONAGE_APPLICATION_ID)
        .privateKeyPath(VONAGE_PRIVATE_KEY_PATH)
        .build();

View full source

Write the code

Add the following to the main method of the OutboundTextToSpeech class:

final String ANSWER_URL = "https://nexmo-community.github.io/ncco-examples/talk.json";

client.getVoiceClient().createCall(new Call(TO_NUMBER, VONAGE_NUMBER, ANSWER_URL));

View full source

Run your code

We can use the application plugin for Gradle to simplify the running of our application. Update your build.gradle with the following:

  apply plugin: 'application'
  mainClassName = project.hasProperty('main') ? project.getProperty('main') : ''

Run the following gradle command to execute your application, replacing com.vonage.quickstart.voice with the package containing OutboundTextToSpeech:

gradle run -Pmain=com.vonage.quickstart.voice.OutboundTextToSpeech

Prerequisites

Install-Package Vonage

Create a file named MakeOutboundCall.cs and add the following code:

using Vonage;
using Vonage.Request;
using Vonage.Voice;
using Vonage.Voice.Nccos.Endpoints;

View full source

Add the following to MakeOutboundCall.cs:


var creds = Credentials.FromAppIdAndPrivateKeyPath(vonageApplicationId, vonagePrivateKeyPath);

View full source

Write the code

Add the following to MakeOutboundCall.cs:


var answerUrl = "https://nexmo-community.github.io/ncco-examples/text-to-speech.json";
var toEndpoint = new PhoneEndpoint() { Number = toNumber };
var fromEndpoint = new PhoneEndpoint() { Number = vonageNumber };

var command = new CallCommand() { To = new Endpoint[] { toEndpoint }, From = fromEndpoint, AnswerUrl = new[] { answerUrl } };

View full source

Prerequisites

composer require vonage/client

Create a file named text-to-speech-outbound.php and add the following code:

$keypair = new \Vonage\Client\Credentials\Keypair(
    file_get_contents(VONAGE_APPLICATION_PRIVATE_KEY_PATH),
    VONAGE_APPLICATION_ID
);

$client = new \Vonage\Client($keypair);

View full source

Write the code

Add the following to text-to-speech-outbound.php:

$outboundCall = new \Vonage\Voice\OutboundCall(
    new \Vonage\Voice\Endpoint\Phone(TO_NUMBER),
    new \Vonage\Voice\Endpoint\Phone(VONAGE_NUMBER)
);
$outboundCall->setAnswerWebhook(
    new \Vonage\Voice\Webhook(
        'https://raw.githubusercontent.com/nexmo-community/ncco-examples/gh-pages/text-to-speech.json',
        \Vonage\Voice\Webhook::METHOD_GET
    )
);
$response = $client->voice()->createOutboundCall($outboundCall);

var_dump($response);

View full source

Run your code

Save this file to your machine and run it:

php text-to-speech-outbound.php

Prerequisites

pip install vonage

Create a file named make-an-outbound-call.py and add the following code:

client = vonage.Client(
    application_id=VONAGE_APPLICATION_ID,
    private_key=VONAGE_APPLICATION_PRIVATE_KEY_PATH,
)

View full source

Write the code

Add the following to make-an-outbound-call.py:

response = client.voice.create_call({
  'to': [{'type': 'phone', 'number': TO_NUMBER}],
  'from': {'type': 'phone', 'number': FROM_NUMBER},
  'answer_url': ['https://raw.githubusercontent.com/nexmo-community/ncco-examples/gh-pages/text-to-speech.json']
})

pprint(response)

View full source

Run your code

Save this file to your machine and run it:

python3 make-an-outbound-call.py

Prerequisites

gem install vonage

Create a file named outbound_tts_call.rb and add the following code:

client = Vonage::Client.new(
  api_key: VONAGE_API_KEY,
  api_secret: VONAGE_API_SECRET,
  application_id: VONAGE_APPLICATION_ID,
  private_key: File.read(VONAGE_APPLICATION_PRIVATE_KEY_PATH)
)

View full source

Write the code

Add the following to outbound_tts_call.rb:

response = client.voice.create(
  to: [{
    type: 'phone',
    number: TO_NUMBER
  }],
  from: {
    type: 'phone',
    number: VONAGE_NUMBER
  },
  answer_url: [
    'https://raw.githubusercontent.com/nexmo-community/ncco-examples/gh-pages/text-to-speech.json'
  ]
)

puts response.inspect

View full source

Run your code

Save this file to your machine and run it:

ruby outbound_tts_call.rb

Send a WhatsApp message

Write the code

Add the following to send-text.sh:

curl -X POST $MESSAGES_API_URL \
     -H 'Authorization: Bearer '$JWT\
     -H 'Content-Type: application/json' \
     -H 'Accept: application/json' \
     -d $'{
      "message_type": "text",
      "text": "Nexmo Verification code: 12345. Valid for 10 minutes.",
      "to": "$TO_NUMBER",
      "from": "$WHATSAPP_NUMBER",
      "channel":  "whatsapp"
  }'

View full source

Run your code

Save this file to your machine and run it:

bash send-text.sh

Prerequisites

npm install @vonage/server-sdk

Create a file named send-text.js and add the following code:

const { Vonage } = require('@vonage/server-sdk')
const { Text } = require('@vonage/messages/dist/classes/WhatsApp/Text');

const vonage = new Vonage({
  apiKey: VONAGE_API_KEY,
  apiSecret: VONAGE_API_SECRET,
  applicationId: VONAGE_APPLICATION_ID,
  privateKey: VONAGE_APPLICATION_PRIVATE_KEY_PATH
}, {
  apiHost: BASE_URL
})

View full source

Write the code

Add the following to send-text.js:

vonage.messages.send(
  new Text(
    "This is a WhatsApp Message text message sent using the Messages API",
    TO_NUMBER,
    WHATSAPP_NUMBER
  )
)
  .then(resp => console.log(resp.message_uuid))
  .catch(err => console.error(err));

View full source

Run your code

Save this file to your machine and run it:

node send-text.js

Prerequisites

Add the following to `build.gradle`:

compile 'com.vonage:client:6.2.0'

Create a class named SendWhatsappText and add the following code to the main method:

VonageClient client = VonageClient.builder()
        .applicationId(VONAGE_APPLICATION_ID)
        .privateKeyPath(VONAGE_PRIVATE_KEY_PATH)
        .build();

MessagesClient messagesClient = client.getMessagesClient();

View full source

Write the code

Add the following to the main method of the SendWhatsappText class:

var message = WhatsappTextRequest.builder()
        .from(VONAGE_WHATSAPP_NUMBER).to(TO_NUMBER)
        .text("Hello from Vonage!")
        .build();

try {
    MessageResponse response = messagesClient.sendMessage(message);
    System.out.println("Message sent successfully. ID: "+response.getMessageUuid());
}
catch (MessageResponseException mrx) {
    switch (mrx.getStatusCode()) {
        default: throw mrx;
        case 401: // Bad credentials
            throw new IllegalStateException(mrx.getTitle(), mrx);
        case 422: // Invalid
            throw new IllegalStateException(mrx.getDetail(), mrx);
        case 402: // Low balance
            client.getAccountClient().topUp("transactionID");
            break;
        case 429: // Rate limit
            Thread.sleep(12_000);
            break;
    }
}

View full source

Run your code

We can use the application plugin for Gradle to simplify the running of our application. Update your build.gradle with the following:

  apply plugin: 'application'
  mainClassName = project.hasProperty('main') ? project.getProperty('main') : ''

Run the following gradle command to execute your application, replacing com.vonage.quickstart.messages.whatsapp with the package containing SendWhatsappText:

gradle run -Pmain=com.vonage.quickstart.messages.whatsapp.SendWhatsappText

Prerequisites

Install-Package Vonage

Write the code

Add the following to SendWhatsAppText.cs:

var credentials = Credentials.FromAppIdAndPrivateKeyPath(appId, privateKeyPath);

var vonageClient = new VonageClient(credentials);

var request = new WhatsAppTextRequest
{
    To = to,
    From = brandName,
    Text = "An SMS sent using the Vonage Messages API"
};

var response = await vonageClient.MessagesClient.SendAsync(request);

View full source

Prerequisites

pip install vonage

Write the code

Add the following to send_text.py:

client = vonage.Client(
    application_id=VONAGE_APPLICATION_ID,
    private_key=VONAGE_APPLICATION_PRIVATE_KEY_PATH,
)

client.messages.send_message(
    {
        "channel": "whatsapp",
        "message_type": "text",
        "to": TO_NUMBER,
        "from": FROM_NUMBER,
        "text": "This is a WhatsApp text message sent using the Vonage Messages API",
    }
)

View full source

Run your code

Save this file to your machine and run it:

python3 send_text.py

Prerequisites

gem install vonage

Write the code

Add the following to send-text.rb:

client = Vonage::Client.new(
  application_id: VONAGE_APPLICATION_ID,
  private_key: File.read(VONAGE_APPLICATION_PRIVATE_KEY_PATH)
)

message = Vonage::Messaging::Message.whatsapp(
  type: 'text',
  message: "This is a WhatsApp Message text message sent using the Messages API"
)

client.messaging.send(
  from: VONAGE_WHATSAPP_NUMBER,
  to: TO_NUMBER,
  **message
)

View full source

Run your code

Save this file to your machine and run it:

ruby send-text.rb

See more use cases

See all use cases
Zipcar
Glassdoor
Help Lightning
HeyHi
Medxm
Teladoc
AllState
Chegg
Coca Cola
DHL
Domino's
Kickstarter