Skip to content

betterworldcollective/canva-php-sdk

Repository files navigation

Canva PHP SDK

A work-in-progress PHP Canva API SDK powered by Saloon.

Installation

composer require betterworldcollective/canva-php-sdk

Authentication

Canva uses OAuth 2.0 for authenticating access to Canva Connect API. Here's how to set up and use the authentication flow using the SDK:

To begin the OAuth flow, you'll need to redirect your user to an authorization URL where they can grant your application access.

use Canva\Canva;

$config = [
  "client_id" => "YOUR_CLIENT_ID",
  "client_secret" => "YOUR_CLIENT_SECRET",
  "redirect_uri" => "YOUR_REDIRECT_URI",
];

// Generate the Canva OAuth login URL
$canva = new Canva(
  clientId: $config["client_id"],
  clientSecret: $config["client_secret"],
  redirectUri: $config["redirect_uri"]
);

$canva->setCodeVerifier($codeVerifier); 

$authorizationUrl = $canva->getAuthUrl();

You'll need to handle your own code verifier. The $codeVerifier is a random string that you generate and store securely. It is used to verify the integrity of the authorization request.

Example of generating a code verifier:

function generateCodeVerifier()
{
  $randomBytes = random_bytes(32);

  return rtrim(strtr(base64_encode($randomBytes), "+/", "-_"), "=");
}

After the user grants access, they will be redirected back to your specified redirect URI with a code parameter. You can then exchange this code for an access token.

$canva = new Canva(
  clientId: $config["client_id"],
  clientSecret: $config["client_secret"],
  redirectUri: $config["redirect_uri"],
);

$canva->setCodeVerifier($codeVerifier); // Use the same code verifier you generated earlier

// `code` and `state` are parameters returned by Canva after the user grants access
$authenticator = $canva->getAccessToken($request["code"], $request["state"]); // Store values securely

Using Access Tokens

Once you have the access token, you can use it to make authenticated requests to the Canva API. The SDK provides a convenient way to include the access token in your requests.

// Create a Canva instance and authenticate with your access token
$canva = new Canva($clientId, $clientSecret, $redirectUri);
$canva->authenticateWithToken($accessToken);

// Now you can make authenticated API requests
$userProfile = $canva->user()->profile();

Token Management

Revoking Access Tokens

The SDK provides functionality to revoke access tokens when they're no longer needed or when you want to invalidate user access. This is useful for:

  • Logging users out of your application
  • Revoking access when users remove your integration
  • Cleaning up expired or compromised tokens
  • Implementing security measures
use Canva\Requests\OAuth\RevokeAccessToken;
use Saloon\Helpers\OAuth2\OAuthConfig;

// Create OAuth config (you can reuse the same config from authentication)
$oauthConfig = new OAuthConfig(
    clientId: $config["client_id"],
    clientSecret: $config["client_secret"],
    redirectUri: $config["redirect_uri"]
);

// Revoke a specific access token
$revokeRequest = new RevokeAccessToken(
    accessToken: $userAccessToken, // The token you want to revoke
    oauthConfig: $oauthConfig
);

// Send the request using Saloon
$response = $revokeRequest->send();

Note: You can also delete the access token from your database, this will prompt the user to re-authenticate and Canva handles the revocation of existing tokens automatically.

Verifying JWT Tokens

The SDK provides functionality to verify JWT tokens using Canva's public keys. This is useful for:

  • Verifying the authenticity of tokens received from Canva
  • Validating token claims and app ID
  • Implementing secure webhook handling
// Get Canva's public keys (unauthenticated endpoint — no connector needed)
$keys = Canva::getPublicKeys();

// Verify a JWT token
$decodedToken = $canva->verifyToken(
    correlationJwt: $jwtToken, // The JWT token to verify (eg. correlation jwt param from return URL)
    keys: $keys->keys, // Array of public keys from Canva
    appId: 'YOUR_APP_ID' // Your app's client ID for validation
);

// The method returns the decoded token payload
echo $decodedToken->sub; // User ID
echo $decodedToken->aud; // App ID

The correlation_jwt parameter is a URL-safe, Base64-encoded JSON Web Token (JWT). The JWT contains the following claims:

aud: Your integration's Client ID.
exp: The token expiry. This is 1 day after the design is opened in the Canva editor.
sub: The User ID of the user who initiated the return navigation workflow.
team_id: The Team ID of the user who initiated the return navigation workflow.
type: Set as rti.
jti: The token's unique identifier (JWT ID).
design_id: The design's ID.
correlation_state: Your original correlation_state string passed to Canva in your prepared edit or view URL.

Getting User Profile Information

The SDK allows you to retrieve user profile information using the access token obtained during OAuth authentication. This is useful for:

  • Displaying user information in your application
  • Personalizing the user experience
  • Storing user details in your database
  • Building user dashboards
$canva = new Canva($clientId, $clientSecret, $redirectUri);
$canva->authenticateWithToken($accessToken);
$canva->user()->profile();

Note: Currently, this endpoint returns the display name of the user account associated with the provided access token. More user information is expected to be included in future API updates.

Designs

Creating a Design

To create a design using the Canva API, you can use the CreateDesign request. This request allows you to specify the design type, dimensions, and other parameters.

// Create a new design
// Refer to the Canva API documentation for available design types and parameters
// https://www.canva.dev/docs/connect/api-reference/designs/create-design/
$canva = new Canva($clientId, $clientSecret, $redirectUri);
$canva->authenticateWithToken($accessToken);
$canva->design()->create([
    "design_type" => [
        "type" => "custom",
        "height" => 1080,
        "width" => 1920,
    ],
    "title" => "My New Design"
]);

Create Design Export Job

To create an export job for a design, you can use the CreateExportJob request. This allows you to specify the design ID and the desired export format.

// Create an export job for a design
// Refer to the Canva API documentation https://www.canva.dev/docs/connect/api-reference/exports/create-design-export-job/
$canva = new Canva($clientId, $clientSecret, $redirectUri);
$canva->authenticateWithToken($accessToken);
$canva->designExportJob()->create([
    "design_id" => "YOUR_DESIGN_ID",
    "format" => [
        "type" => "jpg", // See ExportFormatType enum
        "quality" => 80, // Optional
    ]
]);

Get Design Export Job

To check the status of an export job, you can use the GetDesignExportJob

$canva = new Canva($clientId, $clientSecret, $redirectUri);
$canva->authenticateWithToken($accessToken);
$canva->designExportJob()->get(
    exportId: "YOUR_EXPORT_JOB_ID" // Replace with your export job ID
)

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

Packages

Used by

Contributors

Languages