メニュー

Expand
ページを評価:

通話を発信する

All Functions execute with a pre-initialized instance of the Twilio Node.js SDK available for use. This means you can access and utilize any Twilio helper library method in your Function. For example, you can use a Function to make outbound phone calls via Programmable Voice as we'll show in the following example snippets.

These examples are not exhaustive, and we encourage you to peruse the Programmable Voice documentation for more inspiration on what you can build.

前提条件

Before you start, be sure to complete the following prerequisites. You can skip to "Create and host a Function" if you've already completed these steps and need to know more about Function deployment and invocation, or you can skip all the way to "Make an outbound call" if you're all ready to go and want to get straight to the code.

Create and host a Function

In order to run any of the following examples, you will first need to create a Function into which you can paste the example code. You can create a Function using the Twilio Console or the Serverless Toolkit as explained below:

If you prefer a UI-driven approach, creating and deploying a Function can be done entirely using the Twilio Console and the following steps:

  1. Log in to the Twilio Console and navigate to the Functions tab. If you need an account, you can sign up for a free Twilio account here!
  2. Functions are contained within Services. Create a Service by clicking the Create Service button and providing a name such as test-function.
  3. Once you've been redirected to the new Service, click the Add + button and select Add Function from the dropdown.
  4. This will create a new Protected Function for you with the option to rename it. The name of the file will be path it is accessed from.
  5. Copy any one of the example code snippets from this page that you want to experiment with, and paste the code into your newly created Function. You can quickly switch examples by using the dropdown menu of the code rail.
  6. Click Save to save your Function's contents.
  7. Click Deploy All to build and deploy the Function. After a short delay, your Function will be accesible from:
    https://<service-name>-<random-characters>-<optional-domain-suffix>.twil.io/<function-path>​
    For example: test-function-3548.twil.io/hello-world.

The Serverless Toolkit enables you with local development, project deployment, and other functionality via the Twilio CLI. To get up and running with these examples using Serverless Toolkit, follow this process:

  1. From the CLI, run twilio serverless:init <your-service-name> --empty to bootstrap your local environment.
  2. Navigate into your new project directory using cd <your-service-name>
  3. In the /functions directory, create a new JavaScript file that is named respective to the purpose of the Function. For example, sms-reply.protected.js for a Protected Function intended to handle incoming SMS.
  4. Populate the file using the code example of your choice and save.
    Note A Function can only export a single handler. You will want to create separate files if you want to run and/or deploy multiple examples at once.

Once your Function(s) code is written and saved, you can test it either by running it locally (and optionally tunneling requests to it via a tool like ngrok), or by deploying the Function and executing against the deployed url(s).

Run your Function in local development

Run twilio serverless:start from your CLI to start the project locally. The Function(s) in your project will be accesible from http://localhost:3000/sms-reply

  • If you want to test a Function as a Twilio webhook, run:
    twilio phone-numbers:update <your Twilio phone number> --sms-url "http://localhost:3000/sms-reply"​
    This will automatically generate an ngrok tunnel from Twilio to your locally running Function, so you can start sending texts to it. You can apply the same process but with the voice-url flag instead if you want to test with Twilio Voice.
  • If your code does not connect to Twilio Voice/Messages as a webhook, you can start your dev server and start an ngrok tunnel in the same command with the ngrok flag. For example: twilio serverless:start --ngrok=""

Deploy your Function

To deploy your Function and have access to live url(s), run twilio serverless:deploy from your CLI. This will deploy your Function(s) to Twilio under a development environment by default, where they can be accessed from:

https://<service-name>-<random-characters>-dev.twil.io/<function-path>

たとえば、次のようになります。 https://incoming-sms-examples-3421-dev.twil.io/sms-reply

Your Function is now ready to be invoked by HTTP requests, set as the webhook of a Twilio phone number, invoked by a Twilio Studio Run Function Widget, and more!

How to invoke your Function

Functions created in the UI are Protected by default, and we highly recommend you to set Functions deployed via the Serverless Toolkit to protected as well by prepending protected before the file extension, for example: send-sms.protected.js. This will help secure your Function and protect it from being accessed by bad actors. However, this also adds an extra layer of complexity if you want to manually invoke and test code, such as the examples on this page.

In order to successfully call your protected Function, you will need to provide a valid X-Twilio-Signature header in your request. You can learn more about the request validation process, but in the meantime lets get started with some code that will get you up and running fast.

Generate a valid X-Twilio-Signature header

While it's possible to generate the header yourself using HMAC-SHA1, we highly recommend you use the convenience utilites exported by Twilio's Helper Libraries to perform this operation. Head over to the libraries page to download the library for your language of choice.

Once you have the library of your choice installed, you'll need to:

  1. Set your Auth Token as an environment variable.
  2. Modify the URL and payload of the example below if using Node.js. Refer to the examples here for how to generate a signature with other SDKs.
  3. Execute the modified script and save the resulting X-Twilio-Signature for use in the next step.

const { getExpectedTwilioSignature } = require('twilio/lib/webhooks/webhooks');

// Retrieve your auth token from the environment instead of hardcoding it
const authToken = process.env.TWILIO_AUTH_TOKEN;

// Declare any paramaeters being sent to your Function
const payload = {
  Body: 'Hello, there!',
};

// Use the Twilio helper to generate your valid signature!
// The first argument is your Twilio auth token.
// The second is the full URL of your Function.
// The third is any payload you are sending (or {} if none).
const xTwilioSignature = getExpectedTwilioSignature(
  authToken,
  'https://example-4321.twil.io/sms/send',
  payload
);

// Print the signature to the console for use with your HTTP client of choice
console.log('xTwilioSignature: ', xTwilioSignature);

// For example, output will look like this:
// xTwilioSignature: coGTEaFEMv8ejgNGtgtUsbL8r7c=

Create a valid request

Once you've generated a valid X-Twilio-Signature value, it's time to use this as a header in a request to your Function. You can do so using a variety of tools, such as curl, Postman, and more. Be sure to:

  • Set the URL of the Function, including the root and full path to the deployed Function.
  • Set the X-Twilio-Signature header and content type header (application/x-www-form-urlencoded) for your request.
  • URL encode any data beng sent.

Using curl, the example request above would look like this:

curl -L -X POST 'http://test-4321.twil.io/sms/send' \
-H 'X-Twilio-Signature: coGTEaFEMv8ejgNGtgtUsbL8r7c=' \
-H 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'Body=Hello, there!'

通話の発信

For any Function using the built-in Twilio Client, the "Add my Twilio Credentials (ACCOUNT_SID) and (AUTH_TOKEN) to ENV" option on the Settings > Environment Variables tab must be enabled.

You can use a Function to make a call from your Twilio phone number via Programmable Voice. The to and from parameters of your call must be specified to successfully send, and valid TwiML must be provided either via the url or twiml parameters.

You'll tell Twilio which phone number to use to make this call by either providing a From value in your request, or by omitting it and replacing the placeholder default value in the example code with your own Twilio phone number.

Next, specify yourself as the call recipient by either providing a To value in your request, or by omitting it and replacing the default value in the example code with your personal number. The resulting from and to values both must use E.164 formatting ("+" and a country code, e.g., +16175551212).

Finally, the url or twiml value determines the contents of the call that is being sent. As with the other values, either pass in the respective value in your request to this Function or override the default in the example to your own custom value.

Once you've made any modifications to the sample and have deployed your Function for testing, go ahead and make some test HTTP requests against it to get a call to your phone! Example code for invoking your Function is described earlier in this document.

        
        
        
        Twilio will retrieve the TwiML from the provided URL and use it to handle the call

        通話の発信

        Twilio will retrieve the TwiML from the provided URL and use it to handle the call
              
              
              
              Directly provide TwiML instructions for how to handle the call

              通話の発信

              Directly provide TwiML instructions for how to handle the call

              発信通話の録音

              When making an outgoing call, you can tell Twilio to record the entire call from beginning to end. Add the record argument to your call to calls.create(), set it to true, and Twilio will record the full call on your behalf.

              Once the call is complete, you can listen to your recordings either in the Twilio Console, or access them directly via the REST API for Recordings.

                    
                    
                    
                    ページを評価:

                    ヘルプが必要ですか?

                    We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd by visiting Twilio's Community Forums or browsing the Twilio tag on Stack Overflow.

                          
                          
                          

                          フィードバックくださりありがとうございます!

                          We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?

                          Sending your feedback...
                          🎉 Thank you for your feedback!
                          Something went wrong. Please try again.

                          Thanks for your feedback!

                          Refer us and get $10 in 3 simple steps!

                          ステップ1

                          Get link

                          Get a free personal referral link here

                          ステップ2:

                          Give $10

                          Your user signs up and upgrade using link

                          ステップ3

                          Get $10

                          1,250 free SMSes
                          OR 1,000 free voice mins
                          OR 12,000 chats
                          OR more