nomisoft / php-alexa-helper
一个简化与亚马逊Alexa API协同开发的库
Requires
- php: >=5.3.0
This package is not auto-updated.
Last update: 2024-09-14 19:58:49 UTC
README
一个简化与亚马逊Alexa API协同开发的库
安装
composer require nomisoft/php-alexa-helper
使用
请求
这将捕获POST请求中的JSON
use \Alexa\Request\AlexaRequest; $alexaRequest = AlexaRequest::fromRequest();
如果您已经捕获了发布的JSON并将其保存在变量中,可以将它传递给AlexaRequest类的构造函数
$alexaRequest = new AlexaRequest($json);
$alexaRequest对象现在表现得像一个代表由Alexa API发布的JSON的对象。您可以直接访问属性,例如,与JSON匹配
$alexaRequest->version; $alexaRequest->session->application->applicationId; $alexaRequest->request->intent->slots->ZodiacSign->value;
有几个快捷函数可用
$alexaRequest->getType()是一个快捷方式,返回JSON中request->type的值
$alexaRequest->getIntent()是一个快捷方式,返回JSON中request->intent->name的值
$alexaRequest->getSlots()返回一个键/值数组,表示意图槽位。例如,"slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "virgo" } }将返回array('ZodiacSign'=>'virgo')
验证请求
提交给Alexa审核的技能还需要额外步骤来验证请求是否来自亚马逊。RequestValidator类将执行所有必要的时戳和证书检查。
use \Alexa\Request\AlexaRequest; use \Alexa\Request\RequestValidator; $alexaRequest = AlexaRequest::fromRequest(); $validator = new RequestValidator($request); if (!$validator->validate('YOUR_APP_ID')) { print_r($validator->getErrors()); }
响应
要响应Alexa请求,您可以构造一个OutputSpeech对象
use \Alexa\Request\AlexaRequest; use \Alexa\Request\OutputSpeech; $response = new AlexaResponse(); $speech = new OutputSpeech(); $speech->setText('Hello World'); $response->setOutputSpeech($speech);
当您调用您的Alexa技能时,您的亚马逊Echo(或其他Alexa启用设备)将通过说“Hello World”来响应
默认情况下将使用“PlainText”类型的语音响应。您也可以使用SSML进行响应
$speech = new OutputSpeech(); $speech->setType('SSML'); $speech->setText('<speak>Hello <say-as interpret-as="spell-out">world</say-as>.</speak>');
如果您还想发送一个显示在Alexa应用屏幕上的“卡片”响应,可以创建一个Card对象。以下示例是带有一些文本的“简单”卡片
use \Alexa\Request\Card; $card = new Card(); $card->setContent('Hello World'); $response->setCard($card); $response->render();
除了设置卡片文本内容外,您还可以设置标题并返回要显示的图片
$card = new Card(); $card->setType('Standard'); $card->setTitle('Hello World Title'); $card->setText('Hello World Content'); $card->setSmallImage('http://example.com/small.jpg'); $card->setLargeImage('http://example.com/large.jpg'); $response->setCard($card);
AlexaResponse类是可序列化的JSON,因此要向亚马逊返回您的响应,只需echo json_encode($response);或调用$response->render()。如果您使用Symfony,您可以从控制器返回json,如下所示
$jsonResponse = new \Symfony\Component\HttpFoundation\JsonResponse($response); return $jsonResponse;