fm5z / sitra-api-php
Requires
Requires (Dev)
- phpunit/phpunit: ~8.5
This package is auto-updated.
Last update: 2023-03-27 17:29:17 UTC
README
Rhône Alpes Tourisme的PHP客户端 Apidae API
- 所有API方法都带有输入验证;
- 自动设置身份验证(对于凭证和OAuth端点);
- Apidae SSO辅助工具;
- 错误处理;
- 处理导出(Zip下载和读取);
- 基于Guzzle 6。
本文档仅处理PHP实现,如需进一步问题,请参阅Apidae API文档。
安装
通过Composer
composer require fm5z/apidae-api-php
独立安装(当无法使用Composer时)
如果您无法使用Composer,您可以从此处下载完整的存档
- 解压缩ZIP文件,并将整个"vendor"目录添加到您的项目中;
- 如果您还没有自动加载器,请包含文件
vendor/autoload.php
。
然而我们强烈建议您在所有项目中使用Composer。
使用
创建客户端
您需要创建一个Client
实例
$client = new \Apidae\ApiClient\Client([ 'apiKey' => 'XXX', 'projectId' => 672, 'baseUrl' => 'https://api.apidae-tourisme.com/', 'OAuthClientId' => 'XXX', 'OAuthSecret' => 'XXX', 'exportDir' => '/tmp/apidaeExports', // Http client configuration 'timeout' => 0, 'connectTimeout' => 0, 'proxy' => null, 'verify' => true, // Global settings for touristic objects queries 'responseFields' => [], 'locales' => ['fr', 'en'], 'count' => 20, // For SSO 'ssoBaseUrl' => 'http://base.fm5z.com', 'ssoRedirectUrl' => 'https:///', 'ssoClientId' => 'XXX', 'ssoSecret' => 'XXX', ]); // You can also only use the mandatory parameters (all options have sensible defaults). $client = new \Apidae\ApiClient\Client([ 'apiKey' => 'XXX', 'projectId' => 672, ]);
此类是无状态的,可以用作服务。您可以直接调用任何方法
$metadata = $client->getMetadata(['referenceId' => 123457, 'nodeId' => 'jolicode']); $search = $client->searchDetailedAgenda(['query' => '{"searchQuery": "vélo"}']); $search = $client->searchObject(['query' => '{"searchQuery": "vélo"}']); $object = $client->getObjectById(['id' => 163512]);
结果总是解码后的PHP数组。
选项
apiKey
:项目API密钥;projectId
:对应的projectId;baseUrl
:非必需,如果您想访问预生产环境,则很有用;OAuthClientId
:仅用于元数据,有效的OAuth客户端ID;OAuthSecret
:仅用于元数据,相应的密钥;exportDir
:存储和提取ZIP导出的目录;timeout
:浮点数,描述请求的超时时间(以秒为单位);connectTimeout
:浮点数,描述尝试连接到服务器时要等待的秒数;proxy
:指定HTTP代理的字符串或数组(如http://username:password@192.168.16.1:42
);verify
:布尔值或字符串,描述请求的SSL证书验证行为;responseFields
:允许全局过滤所有相关对象查询返回的字段(文档);locales
:允许全局过滤所有相关对象查询返回的本地化(文档);count
:允许全局更改所有相关对象查询的结果数量;ssoBaseUrl
: SSO认证的基本URL(《[SSO认证技术文档](https://dev.apidae-tourisme.com/fr/documentation-technique/v2/oauth/single-sign-on)》);ssoRedirectUrl
: SSO用户将被重定向到您的应用程序中的URL;ssoClientId
: SSO OAuth客户端ID;ssoSecret
: SSO OAuth客户端密钥。
错误处理
我们建议所有API调用都在try块中执行。
API错误
API错误被封装在Apidae\ApiClient\Exception\ApidaeException
中。
try { $cities = $client->getReferenceCity(['query' => '{"codesInsee": ["38534", "69388", "74140"]}']); } catch (\Apidae\ApiClient\Exception\ApidaeException $e) { echo $e->getMessage(); }
异常消息不适合公开显示,因为它可能包含凭据。
验证错误
验证错误发生在查询之前,假设您未遵守方法定义的架构。
它们由GuzzleHttp\Command\Exception\CommandException
表示。
元数据错误
用于元数据编辑的JSON复杂,并带有其自己的异常Apidae\ApiClient\Exception\InvalidMetadataFormatException
。
API方法
读取旅游对象
按ID获取
$object = $client->getObjectById(['id' => 163512]);
按标识符获取
$object = $client->getObjectByIdentifier(['identifier' => 'sitraSKI275809']);
搜索旅游对象
搜索查询接受一个JSON格式的搜索对象,该对象必须包含您的API凭据;使用此客户端,您可以在JSON中仅发送与搜索相关的字段,如果缺失,我们将自动添加相应的字段。
列出搜索结果
您可以通过几种方式发送搜索
// As JSON string $search = $client->searchObject(['query' => '{"searchQuery": "vélo"}']); // As PHP Array $search = $client->searchObject(['query' => [ "searchQuery" => "vélo", "count" => 20, "first" => 10, ]]); // With the credentials it works too (but we handle them for you) $search = $client->searchObject(['query' => [ "searchQuery" => "vélo" "apiKey" => 'XXX', "projetId" => 1, ]]);
使用标识符搜索
当您只需要对象ID时
$client->searchObjectIdentifier(['query' => '{"searchQuery": "vélo"}']);
日程表
与正常搜索一样,您不需要提供API凭据即可使用这些方法。
列出搜索日程表结果
$client->searchAgenda(['query' => '{"searchQuery": "vélo"}']); $client->searchAgenda(['query' => '{"searchQuery": "vélo", "count": 88, "responseFields": ["nom"]}']);
使用标识符搜索日程表
$client->searchAgendaIdentifier(['query' => '{"searchQuery": "vélo"}']);
以详细视图列出搜索日程表结果
$client->searchDetailedAgenda(['query' => '{"searchQuery": "vélo"}']);
使用标识符和详细视图搜索日程表
$client->searchDetailedAgendaIdentifier(['query' => '{"searchQuery": "vélo"}']);
元数据
列出元数据
您可以这样请求元数据
// Only with the mandatory fields $metadata = $client->getMetadata([ 'referenceId' => 123457, 'nodeId' => 'jolicode' ]); // More detailed search $metadata = $client->getMetadata([ 'referenceId' => 123457, 'nodeId' => 'jolicode', 'targetType' => 'membre' ]); $metadata = $client->getMetadata([ 'referenceId' => 123457, 'nodeId' => 'jolicode', 'targetType' => 'membre', 'targetId' => 21 ]);
删除元数据
同样,您可以删除元数据
$client->deleteMetadata([ 'referenceId' => 123457, 'nodeId' => 'jolicode', 'targetType' => 'membre', 'targetId' => 21 ]); // Remove them all $client->deleteMetadata([ 'referenceId' => 123457, 'nodeId' => 'jolicode' ]);
插入和更新元数据
元数据API接受大量格式,此客户端都支持。
// Simple way on "general" target $client->putMetadata([ 'referenceId' => 123457, 'nodeId' => 'jolicode', 'metadata' => [ 'general' => '{"MyInfos": "Nice weather"}', ] ]); // Simple, with a targetId of 21 on "membres" target $client->putMetadata([ 'referenceId' => 123457, 'nodeId' => 'jolicode', 'metadata' => [ 'membres.membre_21' => '{"MyInfos": "Nice weather"}', ] ]); // Multiple (notice the double JSON encoding) $client->putMetadata([ 'referenceId' => 123457, 'nodeId' => 'jolicode', 'metadata' => [ 'node' => json_encode([ 'general' => json_encode(['toto' => true, 'foo' => 'bar']), 'membres' => ([ ['targetId' => 111, 'jsonData' => json_encode(['foo' => 'barbar'])] ]), ]) ] ]);
参考
与正常搜索一样,您不需要提供API凭据即可使用这些方法。
城市
$cities = $client->getReferenceCity([ 'query' => '{"codesInsee": ["38534", "69388", "74140"]}' ]);
元素
$elements = $client->getReferenceElement([ 'query' => '{"elementReferenceIds": [2, 118, 2338]}' ]);
内部标准
$criteria = $client->getReferenceInternalCriteria([ 'query' => '{"critereInterneIds":[1068, 2168]}' ]);
选择
$selections = $client->getReferenceSelection([ 'query' => '{"selectionIds":[64, 5896]}' ]);
导出
此功能需要PHP Zip扩展和文件系统上的写入权限。
导出是Apidae的一个异步功能,允许您在不进行大量API调用的情况下检索大量数据。当通过Apidae完成新的导出并准备好处理时,您的应用程序将收到一条类似以下的通知
$exportNotification = $_POST; // What Apidae sends: array( "statut" => "SUCCESS", "reinitialisation" => "false", "projetId" => "672", "urlConfirmation" => "https://api.apidae-tourisme.com/api/v002/export/confirmation?hash=XXX", "ponctuel" => "true", "urlRecuperation" => "http://export.fm5z.com/exports/XXX.zip", );
您必须存储这些信息,并尽快以成功响应的形式向Apidae响应。
然后,要处理此导出,您需要
- 以内存高效的方式下载导出;
- 本地提取文件;
- 执行您自己的逻辑;
- 如果一切正常,您必须调用“urlConfirmation”。
库将为您处理前两点和最后一点!
下载和提取导出
只需调用getExportFiles
方法并提供urlRecuperation
$exportFiles = $client->getExportFiles([ 'url' => $exportNotification['urlRecuperation'] ]);
$exportFiles
然后是一个您可以迭代的Finder
对象
// Get all the files and display their content foreach ($exportFiles->files() as $file) { echo $file->getRealpath(); echo '<br>'; echo $file->getContents(); echo '<br>'; } // Filter files by name... foreach ($exportFiles->name('objets_lies_modifies-14*') as $file) { echo $file->getRealpath(); } // Decode file contents (XML or JSON, see your Apidae settings) foreach ($exportFiles->files() as $file) { // $xml = simplexml_load_string($file->getContents()); // print_r($xml); $json = \GuzzleHttp\Utils::jsonDecode($file->getContents(), true); print_r($json); }
确认
当您完成您的任务后,您必须向Apidae确认一切顺利。
// With the export hash $client->confirmExport(['hash' => 'XXX']); // Or, with the full URL given in the notification $client->confirmExport(['hash' => $exportNotification['urlConfirmation']]);
清理文件
所有文件都下载并提取到exportDir
目录中(见选项)。
我们在您使用完文件后提供了一种清理此目录的方法
$client->cleanExportFiles();
使用SSO
您必须使用SSO选项(至少包括'ssoRedirectUrl'、'ssoClientId'和'ssoSecret')配置您的客户端,然后将您的用户重定向到Apidae授权URL。然后,用户可以授予您的应用程序访问其数据的权限,并将带有代码的重定向到您的应用程序。此代码用于获取访问令牌。
$client = new \Apidae\ApiClient\Client([ 'ssoRedirectUrl' => 'http://example.com/TODO', 'ssoClientId' => 'XXX', 'ssoSecret' => 'XXX', ]); <a href="<?php echo $client->getSsoUrl() ?>">Ask for auth code</a>
您的重定向页面必须监听“code”GET参数
if (isset($_GET['code']) && !empty($_GET['code'])) { // The redirect URL get a "code", we use it to ask for a token $token = $client->getSsoToken(['code' => $_GET['code'], 'redirect_uri' => 'http://example.com/TODO']); // Store the new token in the client, will be used automatically! $client->setAccessToken($token['scope'], $token['access_token']); }
您可以在您的应用程序会话中持久化“scope”和“access_token”,并在客户端使用$client->setAccessToken($token['scope'], $token['access_token']);
行将其设置回来。
然后,您可以使用与用户相关的API(sso
范围)。
获取配置文件信息
$profile = $client->getUserProfile();
获取旅游对象用户权限
$permissions = $client->getUserPermissionOnObject(['id' => 123457]);
食谱
让它在没有CURL的情况下也能工作
如果您无法在服务器上安装CURL,请阅读这个Guzzle常见问题解答并放心。
Guzzle提供了一个基于PHP HTTP包装器的StreamHandler
,如果CURL扩展没有被加载,它将自动使用。
待办事项
- SSO集成:确保作用域没有混淆
- 标记第一个稳定版本1.0的发布
可选 / 偏好
- Raml或swagger导出?
- 强大的配置验证器(Config组件)