0
votes

I'm working with C# and WebAPI - my API is set up to accept JSON in POST requests.

What I'm trying to do is - whenever someone sends an SMS to a twilio phone number that I have provisioned, I want to forward this SMS message to my application via a POST request to my application's endpoint - something like example.com/smsfromtwilio - so that my application can analyze the body of the SMS message and record the sender's phone number.

I've tried to read through the docs but don't see any clearcut examples of how this can be done.

So far, when I provision my number, I have the following:

        var twilio = new TwilioRestClient(accountSid, authToken);
        var options = new PhoneNumberOptions {
            PhoneNumber = targetNumber,
            SmsUrl = "example.com/smsfromtwilio"
        };

        var number = twilio.AddIncomingPhoneNumber(options);

Even if this is the right direction to take, I don't know what format the incoming JSON data would be for my API endpoint. Is there any documentation explaining how to achieve this scenario?

Also - is there an example an 'sms forward' JSON payload so I can set up tests for my API?

Update

My controller:

    [HttpPost]
    [Route("api/sms")]
    public HttpResponseMessage Subscribe(string From, string Body) {
        try {
            var messages = _messageService.SendMessage("[email protected]", Body);
            return Request.CreateResponse(HttpStatusCode.OK, messages);
        } catch (Exception e) {
            return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
        }
    }

This is working with url parameters from POSTMAN, now to test twilio...

1

1 Answers

2
votes

Twilio evangelist here.

To forward an SMS message that is sent to your Twilio phone number your going to start by configuring your Twilio phone numbers Message Request Url to point at your Web API endpoint. Log into your Twilio account, then open up the Numbers page and click on the phone number you want to configure. Add the URL as shown below:

Now when someone sends a text message to your Twilio phone number, Twilio will turn around and make and HTTP POST request to that URL, sending along a set of form-urlencoded values. In Web API you should just be able to define a method signature to match the keys of those values and Model Binding will automatically populate the variables for you. For example if you wanted to grab the phone number the message came from and the message body you would just define a method like:

public IHttpResponseMessage Post(string From, string Body) {
   //do stuff here
   return OK();
}

There are a number of ways that you can test this. One would be to use a tool like Fiddler or POSTman to send HTTP requests with the property parameters to localhost. Another would be to expose localhost through a public URL using a tool like ngrok.

Hope that helps.