jakubsuchy / 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-18 19:01:57 UTC
README
这个库为PHP应用程序开发Amazon Alexa技能提供了一个方便的接口。
用法
通过composer安装: composer require minicodemonkey/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 }
证书验证
默认情况下,系统通过获取Amazon的签名证书并解密签名来验证请求签名。您需要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匹配 - 您不需要为此做任何事情。如果您希望更改验证方式,您可以使用与证书验证类似的场景 - 提供一个自己的Application类,该类扩展了\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;