Create an Alexa Skill with PHP – Tutorial

Since my last tutorial some things have changed at Amazon’s Alexa Developer Platform. The interface has been reworked and instead of the old system, where intents had to be created manually, there is now a skill builder.

Therefore I would like to give you here a small update of my old Alexa PHP Tutorials.The Skill Overview

We’ll be leaving soon, too. I simply assume that you have an Alexa Developer account and therefore jump straight into the new dashboard. Via the menu item “Your Alexa Consoles” (top right) > Skills you get to your Skill Overview.

To your Alexa Skill OverviewCreate a Skill

Under “Create Skill” we can create our first own Amazon Alexa skill. After you have clicked the button you have to assign a skill name in the first step. In my example, Daniel.

Then we have to select the model for the skill. We want to start small and not directly build a Smart Home or Video Skill. That’s why we choose Custom here.

Skill Settings

Skill Dashboard

That’s it: Now you get into the dashboard of your skill. In the upper bar you will find the following points:

  • Daniel => name of your skill
  • Build => Here we create the commands
  • Test => So we can check the functions later
  • Launch => If you want to publish your skill in the Amazon Store
  • Measure => usage behavior etc.

Under Build in the left sidebar is the most important one – the Skill calls and settings.

Invocation Name

In the right bar you will find a good checklist with things to do. Here we also start and click on “1st Invocation Name”. The invocation name is the “start expression” for Alexa to address your skill e.g. via “Alexa, ask INVOCATION NAME”. I use daniel as an example – important: no capitalization is allowed here.

Creating an Intent

After setting the Invocation name we can create our first skill intent. An intent is a command that runs on your server when one of the associated uterances is detected. It doesn’t sound complicated.Here is an example:

  • Intent = hello
  • Utterances
    • hi
    • hello
    • moin

If you now ask your skill “hi”, the intent “hello” will be executed on your server. What then comes back from this intent depends on your programming.

Skill Utterances & Slots

Ok so we have now created an intent with “hello”. Now we create 3 utterances as described above: hello, hi and moin.

I would also like a slot (or variable) to be transferred to my server. I add a slot “name” with the slot type “AMAZON.DE_FIRST_NAME”. Of course I have to add these to the Utterances with the help of a brace.

Now our first intent is ready.

Set an Endpoint

Now we can set an endpoint. The endpoint is the destination where your skill requests should be sent. In my case this is https://alexa.welaunch.io. It is important that the endpoint has an encrypted connection (https).

Select HTTPs, enter the address and select “My development endpoint has a certificate from a trusted certificate authority”. Then back to the interaction model and click on “Build Click”.

The PHP-Part

Now we can finally get to the PHP topic. Actually, not much changes here in comparison to my old tutorial, but I will explain it again briefly. As a logger I use monologue to check why some questions were not answered. You can also see which intents or utterances are asked, but not supported by your skill. For example, when I say “hiderido” – this uterance is missing.

Composer File for Monolog:

{
    "name": "db-dzine/alexaphp",
    "description": "PHP Class for Alexa",
    "type": "library",
    "authors": ,
    "minimum-stability": "dev",
    "require": {
        "monolog/monolog": "1.x-dev",
    }
}

After that run composer install in your folder. Then you can create an index.php and load autload & monolog:

<?php // Load Monolog Vendor require_once __DIR__ . '/vendor/autoload.php'; // Autoload files using Composer autoload use Monolog\Logger; use Monolog\Handler\StreamHandler; // Save Requests on debug log define('DEBUG', true); define('DEBUG_FILE', __DIR__ . '/logs/log.log'); $logger = new Logger('Alexa'); $logger->pushHandler( new StreamHandler( DEBUG_FILE, Logger::INFO ) );

Um requests von eurem Skill zu catchen:

// Get Alexa Request
$jsonRequest = file_get_contents('php://input');

// Decode the Request
$data        = json_decode($jsonRequest, true);

// Abort when Empty
if( empty($data) || (!isset($data) ) ) {
	die('Bad Request');
}

The following variables can be read from the data array. There’s more in here, of course, but these are the most important:

$intent = !empty($data) ? $data : 'default';
$intentData = !empty($data) ? $data : 'default';
$sessionId =  !empty($data) ? $data : 'default'; 

$logger->info( var_export($data, true));
$logger->info( $intentData );
$logger->info( $sessionId);

Now we can use the $intent variable to find out which intent was addressed. I return a nice hello via a switch statement in case of the “hello”-intent. And if a name was passed with it, I will also return it. Return the whole as JSON encoded string to Alexa.

switch ($intent) {

	// Hallo Intent für Utterances hi, hallo, moin
	case 'hallo':
		// Hallo Intentdata abfragen
		$name = !empty($intentData) ? $intentData : '';

		// save $name in data file - here also mysql can be used
		// later you can use session id to get data like name
		if(!empty($name)) {
			$dataToSave = array($sessionId => array(
				'name' => $name
			));
			$fp = fopen('data.json', 'w');
			fwrite($fp, json_encode($dataToSave));
			fclose($fp);
		}

		$responseArray = ,
		          'shouldEndSession' => false
		    ]
		];
		break;

	// Default
	default:
		$responseArray = ,
		          'shouldEndSession' => true
		    ]
		];
		break;
}

header ( 'Content-Type: application/json' );
echo json_encode ( $responseArray );
die();

Skill testing

We can test our skill with a “Question daniel hello klaus”. Sounds stupid, but ask daniel to start the skill (invocation name) and hello (intent) is executed.

You can also use your Alexa app on your smartphone to test the skill.

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Close Popup

We use cookies to give you the best online experience. By agreeing you accept the use of cookies in accordance with our cookie policy.

Close Popup
Privacy Settings saved!
Privacy Settings

When you visit any web site, it may store or retrieve information on your browser, mostly in the form of cookies. Control your personal Cookie Services here.

These cookies are necessary for the website to function and cannot be switched off in our systems.

Technical Cookies
In order to use this website we use the following technically required cookies
  • wordpress_test_cookie
  • wordpress_logged_in_
  • wordpress_sec

Decline all Services
Save
Accept all Services