vasily-kartashov / amazon-alexa-php
PHP的Amazon Alexa接口
0.2.6
2018-07-02 15:31 UTC
Requires
- php: >=7.0
Requires (Dev)
README
此库为开发PHP应用程序的Amazon Alexa技能提供了一些接口。
请将此库视为正在开发中,未来可能进行重大的API更改。当前实现是垃圾,但几乎没有其他替代方案。
使用方法
通过Composer安装: vasily-kartashov/amazon-alexa-php
。
路线图
- 移除公共访问
- 添加更多单元测试
- 弃用旧的令人困惑的API
- 添加对标准HTTP请求对象的依赖
- 添加与php-league的Oauth-Server的集成
停止抛出异常- 添加LoggerAwareInterface
- 提取证书验证机构并添加缓存
- 添加验证器和对https://github.com/alexa/alexa-smarthome/tree/master/validation_schemas的依赖
请求
通过使用工厂方法Request::fromHttpRequest
创建请求,该方法接受PSR-7定义的RequestInterface
类型的对象。例如,当使用Guzzle时,可以通过运行以下代码初始化一个Alexa请求对象:
$request = Request::fromHttpRequest(ServerRequest::fromGlobals(), $applicationId);
证书验证
默认情况下,系统通过获取亚马逊的签名证书并解密签名来验证请求签名。你需要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()函数作为其中的一部分。以与证书相同的方式将应用程序传递给请求库。
$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;