Send HTTP post request from Amazon Alexa skills kit

Casper picture Casper · Dec 14, 2015 · Viewed 7.1k times · Source

I'm a beginner in web server and trying to execute some PHP script from Amazon Echo.

Basically I have an apache web server running (accessible from the internet over port 443). I also have a PHP script inside my web server https://web-server.mine/script.php

I've successfully run the PHP script from a web browser with a basic web authentication.

Now I'm trying to make a POST request from Amazon Alexa skills kit but I don't know how to pass the credentials so it could make a call to the URL.

Answer

dale3h picture dale3h · Dec 16, 2015

I am not entirely clear on what you are asking, so I will try to answer all of my interpretations.

  1. If you're trying to make sure that it is the Alexa Skill that is trying to access your URL, the easiest way that I've found to authenticate by checking the applicationId from the POST data:

    // Get raw POST data
    $post = file_get_contents( 'php://input' );
    
    // Decode the JSON into a stdClass object
    $post = json_decode( $post );
    
    // Check the applicationId to make sure it's your Alexa Skill
    if ( 'amzn1.echo-sdk-ams.app.[your-unique-value-here]' == $post->session->application->applicationId ) {
        // Insert code to run if the applicationId matches
        echo 'The applicationId matches!';
    } else {
        // Insert code to run if the applicationId does NOT match
        echo 'The applicationId does NOT match!';
    }
    

    If going this route, you'll need to make sure that you create a valid SSL certificate as outlined here: Create a Private Key and Self-Signed Certificate for Testing

  2. If you're trying to make a POST request to another URL from within your script, try using file_get_contents() as described here: How to post data in PHP using file_get_contents?

On a side note, it may be worth looking into using a set of PHP classes that have been developed for making the creation of Alexa Skills much easier, like this one: https://github.com/develpr/alexa-app

I personally run Node.js on a Raspberry Pi, and I use the Node packages alexa-app-server and alexa-app to make creation and hosting of multiple skills much easier. If this is something that interests you, just Google "nodejs alexa-app-server" for the latest links to these packages.