skip to Main Content

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 Overview

My Skills from Alexa
My Skills from Alexa

Create 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.

Creating an Alexa Skill
Creating an Alexa Skill
Model for your Skill
Model for your Skill

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.

Dashboard
Dashboard

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.

Invocation Name
Invocation Name

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.

Create an Intent
Create an Intent

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.

Create Utterances
Create Utterances
Slots creating
Slots creating
Assign Slots to Utterances
Assign Slots to Utterances
Utterances Overview
Utterances Overview

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.db-dzine.com. 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”.

Translated with www.DeepL.com/Translator

Set an Endpoint
Set an Endpoint
Skill Building
Skill Building

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": [
        {
            "name": "Daniel Barenkamp",
            "email": "[email protected]"
        }
    ],
    "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['request']['intent']['name']) ? $data['request']['intent']['name'] : 'default';
$intentData = !empty($data['request']['intent']['slots']) ? $data['request']['intent']['slots'] : 'default';
$sessionId =  !empty($data['session']['sessionId']) ? $data['session']['sessionId'] : '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['name']['value']) ? $intentData['name']['value'] : '';

		// 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 = [ 'version' => '1.0',
		    'response' => [
		          'outputSpeech' => [
		                'type' => 'PlainText',
		                'text' => 'Hallo ' . $name,
		                'ssml' => null
		          ],
		          'shouldEndSession' => false
		    ]
		];
		break;

	// Default
	default:
		$responseArray = [ 'version' => '1.0',
		    'response' => [
		          'outputSpeech' => [
		                'type' => 'PlainText',
		                'text' => 'Ich bin die Default Rückgabe! Intent: ' . $intent,
		                'ssml' => null
		          ],
		          '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.

Alexa Skill Testing
Alexa Skill Testing

Daniel Barenkamp

Founder and Creator of DB-Dzine.

Leave a Reply

Your email address will not be published. Required fields are marked *

Close search
Search