20steps / amazon-alexa-php
PHP 的 Amazon Alexa 接口
Requires
- php: >=5.3.0
Requires (Dev)
- phpunit/phpunit: ~4.6
This package is not auto-updated.
Last update: 2024-09-26 06:25:24 UTC
README
这个库提供了一个方便的接口,用于在您的 PHP 应用中开发 Amazon Alexa 技能。
信息
工作进度中
使用
通过 composer 安装: composer require 20steps/amazon-alexa-php
。
请求
当 Amazon Alexa 触发您的技能时,一个 HTTP 请求将被发送到您为应用指定的 URL。
您可以像这样获取请求的 JSON
主体
$applicationId = "your-application-id-from-alexa"; // See developer.amazon.com and your Application. Will start with "amzn1.echo-sdk-ams.app." $rawRequest = $request->getContent; // This is how you would retrieve this with Laravel or Symfony 2. $alexa = new \Alexa\Request\Request($rawRequest, $applicationId); $alexaRequest = $alexa->fromData();
库期望原始请求数据,而不是解析后的 JSON,因为它需要验证请求签名。
您可以使用 instanceof
确定请求类型,例如
if ($alexaRequest instanceof IntentRequest) { // Handle intent here }
证书验证
默认情况下,系统通过获取亚马逊的签名证书并解密签名来验证请求签名。您需要 CURL 才能获取证书。没有进行缓存,但您可以根据您的应用提供的功能轻松覆盖证书类以实现证书缓存。
这里有一个基本示例
class MyAppCertificate extends \Alexa\Request\Certificate { public function getCertificate() { $cached_certificate = retrieve_cert_from_myapp_cache(); if (empty($cached_certificate)) { // Certificate is not cached, download it $cached_ertificate = $this->fetchCertificate(); // Cache it now } return $cached_certificate; } }
然后在您的应用中,使用 setCertificateDependency 函数
$certificate = new MyAppCertificate($_SERVER['HTTP_SIGNATURECERTCHAINURL'], $_SERVER['HTTP_SIGNATURE']); $alexa = new \Alexa\Request\Request($rawRequest); $alexa->setCertificateDependency($certificate); $alexaRequest = $alexa->fromData();
应用程序 ID 验证
库将自动验证您的应用程序 ID 与传入请求的应用程序 ID 匹配 - 您不需要为此做任何事情。如果您希望更改验证方式,可以使用与证书验证类似的场景 - 提供一个扩展 \Alexa\Request\Application 的应用程序类,并在此类中提供 validateApplicationId() 函数。以与证书相同的方式将应用程序传递给 Request 库。
$application = new MyAppApplication($myappId); $alexa = new \Alexa\Request\Request($rawRequest, $myappId); $alexa->setApplicationDependency($application); $alexaRequest = $alexa->fromData();
响应
您可以使用 Response
类构建 Alexa 响应。您还可以选择设置一个卡片或一个 reprompt。
这里有一些示例。
$response = new \Alexa\Response\Response; $response->respond('Cooool. I\'ll lower the temperature a bit for you!') ->withCard('Temperature decreased by 2 degrees');
$response = new \Alexa\Response\Response; $response->respond('What is your favorite color?') ->reprompt('Please tell me your favorite color');
要输出响应,只需使用 ->render()
函数即可,例如在 Laravel 中,您将创建响应如下
return response()->json($response->render());
在纯 PHP 中
header('Content-Type: application/json'); echo json_encode($response->render()); exit;