froodley/amazon-alexa-php

PHP的Amazon Alexa接口 - XSS过滤,增强测试性

0.5.2.5 2017-10-18 23:43 UTC

README

此库为在PHP应用程序中开发Amazon Alexa技能提供了一个便捷的接口。

它从jakobsuchy/amazon-alexa-php中进行了重大更改(并且已分支)

最重要的更改是添加了XSS净化和一些基本的Doctrine验证,并使一切无状态,SRP和更具可测试性

用法

通过composer安装:composer require froodley/amazon-alexa-php

请求

当Amazon Alexa触发您的技能时,将向您为应用程序指定的URL发送HTTP请求。

您可以通过以下方式获取请求的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.
$alexaRequestFactory = new \Alexa\Request\RequestFactory();
$alexaRequest = $alexaRequestFactory->fromRawData($rawRequest, [$applicationId]);

该库期望原始请求数据,而不是解析的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()函数作为其中的一部分。以与证书相同的方式将应用程序传递给请求库

$application = new MyAppApplication($myappId);
$alexa = new \Alexa\Request\Request($rawRequest, $myappId);
$alexa->setApplicationDependency($application);

$alexaRequest = $alexa->fromData();

响应

您可以使用Response类构建Alexa响应。您还可以选择设置卡片或重试提示。

以下是一些示例。

$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;