Search code examples
javavonage

Nexmo Receiving SMS Java


I was wondering what approach I should use to be able to receive messages through Nexmo. Has anybody had any experience on this issue because Nexmo doesn't seem to have clear documentation on how to receive messages through there libraries. Any help would be wonderful.


Solution

  • For each Nexmo number you own, you can configure a URL which will be called by Nexmo when an SMS is received at that number. The GET request will contain information about the received SMS as request params.

    A little complexity is added (while you're developing) because Nexmo needs to be able to reach a URL that is hosted on your development machine, which is probably not publicly available on the Internet! For this, you'll want to run something like Ngrok which will provide a tunnel to a port on your local machine with a public URL.

    I'd recommend starting with a simple servlet that prints out its params:

    public class InboundSMSServlet extends HttpServlet {
        @Override
        protected void service(HttpServletRequest req,
                             HttpServletResponse resp)
                throws ServletException,
                       java.io.IOException {
            System.out.println("Received: " + req.getMethod());
            for (String param : Collections.list(req.getParameterNames())) {
                String value = req.getParameter(param);
                System.out.println(param + ": " + value);
            }
        }
    }
    

    ... configure it to a convenient URL ...

    <servlet>
        <servlet-name>inbound-sms</servlet-name>
        <servlet-class>getstarted.InboundSMSServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>inbound-sms</servlet-name>
        <url-pattern>/inbound</url-pattern>
    </servlet-mapping>
    

    Run both your servlet container and ngrok at the same time and check that the ngrok URL with /YOUR_PROJECT_NAME/inbound at the end works as expected. Then go into the Nexmo dashboard, Your Numbers, and hit Edit on the number you want to receive SMS messages to. Enter the Ngrok URL you tested above.

    Now send an SMS to the number you configured, and you should see the contents of your message printed to the console; something like:

    Received: GET
    messageId: 0B0000004A2D09D9
    to: 447520666777
    text: Hello Nexmo!
    msisdn: 447720123123
    type: text
    keyword: HELLO
    message-timestamp: 2017-04-27 14:41:32
    

    The details of how this works are documented on the Nexmo site