keith-vo-macusa/oauth2canva
最新稳定版本:v1.0.1
Composer 安装命令:
composer require keith-vo-macusa/oauth2canva
包简介
This is my package oauth2canva
README 文档
README
Laravel package for integrating OAuth 2.0 with Canva Connect API. This package provides full support for OAuth 2.0 Authorization Code flow with PKCE (SHA-256) according to Canva's official documentation.
Features
- OAuth 2.0 Authorization Code flow with PKCE - Full OAuth 2.0 compliance with PKCE (SHA-256) according to Canva standards
- Generate authorization URL - Automatically generate authorization URL with PKCE parameters
- Exchange authorization code - Exchange authorization code for access token and refresh token
- Refresh access token - Automatically refresh token when expired
- Introspect token - Verify token validity on the server
- Revoke token - Revoke token when no longer needed
- Helper methods - Convenient methods for calling Canva API
- CanvaToken Model - Eloquent model for managing tokens with helper methods
- Custom Exceptions - Clear error handling with custom exceptions
- Auto-refresh - Automatically refresh token when about to expire
Requirements
- PHP >= 8.2
- Laravel >= 11.0 or >= 12.0
Installation
Install the package via Composer:
composer require mac/oauth2canva
Publish and run the migrations:
php artisan vendor:publish --tag="oauth2canva-migrations"
php artisan migrate
Publish the config file:
php artisan vendor:publish --tag="oauth2canva-config"
Add the following environment variables to your .env file:
CANVA_CLIENT_ID=your_client_id CANVA_CLIENT_SECRET=your_client_secret CANVA_REDIRECT_URI=https://your-app.com/canva/callback CANVA_SCOPES=asset:read asset:write design:meta:read
The config file (config/oauth2canva.php) contents:
return [ 'client_id' => env('CANVA_CLIENT_ID'), 'client_secret' => env('CANVA_CLIENT_SECRET'), 'redirect_uri' => env('CANVA_REDIRECT_URI'), 'scopes' => env('CANVA_SCOPES', ''), 'api_base_url' => env('CANVA_API_BASE_URL', 'https://api.canva.com'), 'authorization_url' => env('CANVA_AUTHORIZATION_URL', 'https://www.canva.com/api/oauth/authorize'), 'token_url' => env('CANVA_TOKEN_URL', 'https://api.canva.com/rest/v1/oauth/token'), ];
Optionally, you can publish the views using:
php artisan vendor:publish --tag="oauth2canva-views"
Documentation
See USAGE.md for detailed usage instructions with complete examples.
Usage
Step 1: Generate Authorization URL
use Macoauth2canva\OAuth2Canva\Facades\OAuth2Canva; // Generate authorization URL $authData = OAuth2Canva::getAuthorizationUrl(); // Store code_verifier and state in session for later use session([ 'canva_code_verifier' => $authData['code_verifier'], 'canva_state' => $authData['state'], ]); // Redirect user to authorization URL return redirect($authData['url']);
Step 2: Handle Callback
use Macoauth2canva\OAuth2Canva\Facades\OAuth2Canva; use Macoauth2canva\OAuth2Canva\Models\CanvaToken; // In your callback route public function handleCallback(Request $request) { // Verify state to prevent CSRF attacks $state = $request->query('state'); if ($state !== session('canva_state')) { abort(403, 'Invalid state parameter'); } // Get authorization code $code = $request->query('code'); $codeVerifier = session('canva_code_verifier'); // Exchange code for access token $tokenData = OAuth2Canva::exchangeCodeForToken($code, $codeVerifier); // Save token to database CanvaToken::create([ 'user_id' => auth()->id(), 'access_token' => $tokenData['access_token'], 'refresh_token' => $tokenData['refresh_token'], 'expires_at' => now()->addSeconds($tokenData['expires_in']), 'scopes' => $request->query('scope'), ]); // Clear session data session()->forget(['canva_code_verifier', 'canva_state']); return redirect()->route('dashboard')->with('success', 'Successfully connected to Canva!'); }
Step 3: Use Access Token to Call API
use Macoauth2canva\OAuth2Canva\Facades\OAuth2Canva; use Macoauth2canva\OAuth2Canva\Models\CanvaToken; // Get user's token $token = CanvaToken::forUser(auth()->id())->first(); // Automatically refresh if needed (less than 5 minutes remaining) $accessToken = $token->getValidAccessToken(); // Call Canva API $response = OAuth2Canva::makeApiRequest( 'GET', '/rest/v1/users/me', $accessToken ); $userData = $response->json();
Additional Methods
// Introspect token to check validity $tokenInfo = OAuth2Canva::introspectToken($accessToken); if ($tokenInfo['active']) { // Token is still active } // Revoke token OAuth2Canva::revokeToken($accessToken); // Or use model method $token->revoke(); // Revoke and delete from database // Check token validity if ($token->isValid()) { // Token is still valid } if ($token->isActive()) { // Token is active on server } // Generate PKCE values (if you need to create them manually) $codeVerifier = OAuth2Canva::generateCodeVerifier(); $codeChallenge = OAuth2Canva::generateCodeChallenge($codeVerifier); $state = OAuth2Canva::generateState();
API Reference
OAuth2Canva Facade
getAuthorizationUrl(?string $codeVerifier, ?string $state, ?string $scopes, ?string $redirectUri): Generate authorization URL with PKCEexchangeCodeForToken(string $authorizationCode, string $codeVerifier, ?string $redirectUri): Exchange code for tokenrefreshAccessToken(string $refreshToken): Refresh access tokenintrospectToken(string $token): Check token validity on serverrevokeToken(string $token): Revoke tokenmakeApiRequest(string $method, string $endpoint, string $accessToken, array $data = []): Make Canva API requestgenerateCodeVerifier(): Generate code verifier for PKCEgenerateCodeChallenge(string $codeVerifier): Generate code challenge from code verifiergenerateState(): Generate state parameter for CSRF protection
CanvaToken Model
isValid(): Check if token is still valid (based on expires_at)needsRefresh(): Check if token needs to be refreshedrefreshIfNeeded(): Automatically refresh if neededgetValidAccessToken(): Get access token, automatically refresh if neededrevoke(): Revoke token and delete from databaseisActive(): Check if token is active on serverscopeForUser($query, string $userId): Query scopescopeValid($query): Query scope for valid tokens
Testing
Run the test suite:
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Contributions are welcome from the community. Please see CONTRIBUTING for details.
Security Vulnerabilities
If you discover a security vulnerability, please send an email directly to the maintainer instead of using the issue tracker. All security vulnerabilities will be promptly addressed.
Credits
License
The MIT License (MIT). Please see LICENSE for more information.
统计信息
- 总下载量: 18
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 0
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-12-12