cedricziel/canva-extension-helper
Composer 安装命令:
composer require cedricziel/canva-extension-helper
包简介
Canva.com extension helpers
README 文档
README
Some utilities for building canva extensions.
Usage
Installation
Via composer:
composer require cedricziel/canva-extension-helper
With Symfony
Symfony projects usually come with a fully configured serializer and a configured http server layer.
The following Symfony controller is enough for a "Publish" extension with the basic layout:
<?php namespace App\Controller\Canva; use Canva\Error; use Canva\HttpHelper; use Canva\Publish\ErrorResponse; use Canva\Publish\UploadRequest; use Canva\Publish\UploadResponse; use Canva\Request as CanvaRequest; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Event\ControllerEvent; use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\KernelEvents; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Serializer\Exception\InvalidArgumentException; use Symfony\Component\Serializer\SerializerInterface; use Symfony\Contracts\HttpClient\HttpClientInterface; /** * @Route(path="/canva/extensions/publish", name="canva_publish") */ class PublishExtensionController extends AbstractController implements EventSubscriberInterface { private string $canvaSecret; public function __construct(string $canvaSecret) { $this->canvaSecret = $canvaSecret; } public static function getSubscribedEvents() { return [ KernelEvents::CONTROLLER => 'onKernelController', ]; } /** * @Route("/configuration", name="_configuration", methods={"POST"}) */ public function configuration(): Response { return $this->json(new ErrorResponse(Error::CODE_INVALID_REQUEST)); } /** * @Route("/resources/find", name="_resources_find", methods={"POST"}) */ public function resourcesFind(): Response { return $this->json(new ErrorResponse(Error::CODE_INVALID_REQUEST)); } /** * @Route("/resources/get", name="_resources_get", methods={"POST"}) */ public function resourcesGet(): Response { return $this->json(new ErrorResponse(Error::CODE_INVALID_REQUEST)); } /** * @Route("/resources/upload", name="_resources_upload") */ public function resourcesUpload(Request $request, HttpClientInterface $httpClient, SerializerInterface $serializer): Response { try { /** @var UploadRequest $uploadRequest */ $uploadRequest = $serializer->deserialize($request->getContent(), UploadRequest::class, 'json'); foreach ($uploadRequest->getAssets() as $asset) { // do something with the result $httpClient->request('GET', $asset->getUrl()); } return $this->json(new UploadResponse()); } catch (InvalidArgumentException $exception) { return $this->json(new ErrorResponse(Error::CODE_INVALID_REQUEST)); } } public function onKernelController(ControllerEvent $event) { $controller = $event->getController(); $request = $event->getRequest(); // when a controller class defines multiple action methods, the controller // is returned as [$controllerInstance, 'methodName'] if (is_array($controller)) { $controller = $controller[0]; } /** * Every publish extension endpoint is invoked via POST and needs * signature AND timestamp checking. */ if ($controller instanceof self) { $timestampHeader = $request->headers->get(CanvaRequest::HEADER_TIMESTAMP); if ($timestampHeader === null || !HttpHelper::verifyTimestamp($timestampHeader, time())) { throw new HttpException(401, 'Timestamp skew is too large.'); } $path = parse_url($request->getUri(), PHP_URL_PATH); $operation = ''; switch (true) { case str_ends_with($path, '/configuration'): $operation = '/configuration'; break; case str_ends_with($path, '/publish/resources/find'): $operation = '/publish/resources/find'; break; case str_ends_with($path, '/publish/resources/get'): $operation = '/publish/resources/get'; break; case str_ends_with($path, '/publish/resources/upload'): $operation = '/publish/resources/upload'; break; default: throw new HttpException(401, 'Unknown operation'); } $signature = HttpHelper::calculatePostSignature( $timestampHeader, $operation, $request->getContent(), $this->canvaSecret ); $signatureHeader = $request->headers->get(CanvaRequest::HEADER_SIGNATURES); if ($signatureHeader === null || !in_array($signature, explode(',', $signatureHeader), true)) { throw new HttpException(401, 'Signatures do not match'); } } } }
You can then "bind" the $canvaSecret constructor argument to your Canva.com secret in services.yaml:
services: _defaults: # .. other defaults bind: $canvaSecret: 'my-secret'
Serialization
Note: This project provides model classes. De-/Serialization must be done by means of your application.
Example using the Symfony Serializer component:
use Canva\Publish\GetResourceRequest; use Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor; use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor; use Symfony\Component\PropertyInfo\PropertyInfoExtractor; use Symfony\Component\Serializer\Encoder\JsonEncoder; use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer; use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer; use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; use Symfony\Component\Serializer\Normalizer\PropertyNormalizer; use Symfony\Component\Serializer\Serializer; // the json chunk extracted from the request body $request = '...'; $encoders = [new JsonEncoder()]; $extractor = new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()]); $normalizers = [new ArrayDenormalizer(), new ObjectNormalizer(null, null, null, $extractor), new PropertyNormalizer(), new GetSetMethodNormalizer()]; /** @var GetResourceRequest $getResourceRequest */ $getResourceRequest = $serializer->deserialize($request, GetResourceRequest::class, 'json');
Checking incoming requests
Canva requires extensions to check incoming requests for a timestamp skew and a matching HMAC signature. This packages provides helpers to cope with that easily.
Checking the timestamp:
// allow a skew of 300 seconds $leniency = 300; // the timestamp at which the request was received $localTimestamp = time(); // the timestamp at which the request was sent $sentTimestamp = $_SERVER['HTTP_X_CANVA_TIMESTAMP']; // returns a boolean whether the timestamps are close enough together $timestampIsOkay = \Canva\HttpHelper::verifyTimestamp($sentTimestamp, $localTimestamp, $leniency)
For examples on how to check the signatures, please check the middleware section.
Middlewares
Canva requires you to check requests coming from their end. You can do so by manually verifying the timestamp headers
with the Canva\HttpHelper class, or opt for a middleware you have to mount on the paths that canva will be talking to.
Canva\MiddlewareTimestampMiddleware - Checks the time skew
Canva\Middleware\PostHMACMiddleware - Checks the signature on POST requests
Canva\Middleware\GetHMACMiddleware - Checks the signature on GET requests
Disclaimer
This project is not affiliated with Canva.com
License
MIT
cedricziel/canva-extension-helper 适用场景与选型建议
cedricziel/canva-extension-helper 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 246 次下载、GitHub Stars 达 7, 最近一次更新时间为 2020 年 08 月 15 日, 在 PHP 生态内属于活跃度较高的组件。
我们在过去多个企业项目中使用过 cedricziel/canva-extension-helper 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 cedricziel/canva-extension-helper 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
统计信息
- 总下载量: 246
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 7
- 点击次数: 0
- 依赖项目数: 1
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2020-08-15