An API client for Envato in PHP, with simplified OAuth, token storage, and request sending.
- Notes
- Installation
- Authentication
- Sending Requests
- Catalog
- Profile
- User
- Market
- Handling Errors & Exceptions
- Examples
- Contributors
This API client is fully working though not necessarily completed. Of course, any updates that aren't backwards-compatible will be bumped up a major version. Other than that, here's some info you'll probably want to know.
- This client does not disable SSL. It ships with a Certificate Authority bundle and uses this bundle to verify the Envato API's SSL certificate, instead of relying on the system's often-unavailable certificate.
Include this into your project using Composer. It will be autoloaded.
composer require baileyherbert/envato
Start a new client with a personal token (create one at build.envato.com).
$token = new Herbert\Envato\Auth\Token('Your Personal Token');
$client = new Herbert\EnvatoClient($token);
This is a bit more complicated. Using OAuth means you'll need to redirect your users. In general, the below code will work fine. If you wish to store the OAuth session (for example, in a database or cookie) to be able to load it later, see Persistent OAuth.
// Generate the OAuth object
$oauth = new Herbert\Envato\Auth\OAuth([
'client_id' => 'Your client id',
'client_secret' => 'Your client secret',
'redirect_uri' => 'https://your-redirect-uri.com/'
]);
// Get the token (returns null if unavailable)
$token = $oauth->auth;
// Redirect the user if they're not authorized yet
if (!$token) {
header("Location: " . $oauth->getAuthorizationUri());
die;
}
// Create the client
$client = new Herbert\EnvatoClient($token);
- The
OAuth
object contains methods to generate an authorization URI. - To make this example work, the
redirect_uri
should point back to the current file. - Calling
$oauth->token
will automatically recognize thecode
sent back by Envato and will return something truthy that you can pass intoEnvatoClient()
.
In the example above, we authenticated using OAuth. This redirected the user to the Envato API for authorization, and generated a new set of access and refresh tokens.
However, in many cases, we will want to save this information for future use. Fortunately, this is easy to do.
$oauth = new Herbert\Envato\Auth\OAuth([
'client_id' => 'Your client id',
'client_secret' => 'Your client secret',
'redirect_uri' => 'https://your-redirect-uri.com/'
]);
// Load an OAuth session
if (isset($_SESSION['oauth_session'])) {
$oauth->load($_SESSION['oauth_session']);
}
// No saved session, so let's start a new one
else {
if ($oauth->auth) {
// Save the OAuth session
$_SESSION['oauth_session'] = $oauth->session;
}
else {
// User is not logged in, so redirect them
header("Location: " . $oauth->getAuthorizationUri());
die;
}
}
// Create the client
$client = new Herbert\EnvatoClient($oauth->auth);
- The
$oauth->session
member will contain a JSON string with data for the current authorization. - The
$oauth->load()
method accepts that JSON string and uses it to load the authorization. - You can create a new
EnvatoClient
after this, like normal. - When the access token provided by Envato expires, the client will be able to automatically create a new access token using the saved session data.
Here's an example request to get the current user's username. Currently, it returns a ResultSet
object; this object exposes a results
property which is an array of the raw API response.
$response = $client->user->username();
if (!$response->error) {
$username = $response->results['username'];
echo "Logged in as {$username}";
}
else {
echo "Error: {$response->error}";
}
For an endpoint which has variables, you can pass them as an array. This works for all endpoint versions, including legacy v1 and the new v3.
$response = $client->profile->portfolio([
'username' => 'baileyherbert'
]);
To determine how long a request took to execute (in seconds), you can reference the $response->time
property.
If you're being rate limited, the client will throw a TooManyRequestsException
exception. The exception instance has
methods to help work with the rate limit.
use Herbert\Envato\Exceptions\TooManyRequestsException;
try {
$item = $client->catalog->item(['id' => 1234567]);
}
catch (TooManyRequestsException $e) {
// Get the number of seconds remaining (float)
$secondsRemaining = $e->getSecondsRemaining();
// Get the timestamp for when we can make our next request
$timestamp = $e->getRetryTime();
// Sleep until the rate limiting has ended
$e->wait();
}
$client->catalog->collection(['id' => 12345]);
$client->catalog->item(['id' => 12345]);
$client->catalog->item_version(['id' => 12345]);
$client->catalog->items(['site' => 'codecanyon.net', 'term' => '']);
$client->catalog->comments(['item_id' => 12345]);
$client->catalog->popular(['site' => 'codecanyon']);
$client->catalog->categories(['site' => 'codecanyon']);
$client->catalog->prices(['item_id' => 12345]);
$client->catalog->newest(['site' => 'codecanyon', 'category' => 'php-scripts']);
$client->catalog->featured(['site' => 'codecanyon']);
$client->catalog->random(['site' => 'codecanyon']);
The profile
category represents a public Envato user.
$client->profile->collections();
$client->profile->collection(['id' => 12345]);
$client->profile->details(['username' => 'baileyherbert']);
$client->profile->badges(['username' => 'baileyherbert']);
$client->profile->portfolio(['username' => 'baileyherbert']);
$client->profile->portfolio(['username' => 'baileyherbert', 'site' => 'codecanyon']);
The user
category represents the currently-authenticated user.
$client->user->sales();
$client->user->sale(['code' => '*****']);
$client->user->purchases();
$client->user->purchase(['code' => '*****']);
$client->user->details();
$client->user->username();
$client->user->email();
$client->user->sales();
$client->market->users();
$client->market->items();
$client->market->site(['site' => 'codecanyon']);
All exceptions in this libary are under the Herbert\Envato\Exceptions
namespace.
When performing OAuth authorization, you may encounter one of these exceptions:
InvalidTokenException
if the token provided is not a string.MissingPropertyException
if OAuth is missing one of the constructor parameters (client_id, client_secret, redirect_uri).NotAuthenticatedException
if you try to construct anEnvatoClient
before being authenticated.
When performing a request, there are four possible exceptions that can be thrown.
BadRequestException
if required arguments are missing or are invalid.UnauthorizedException
if the current authorization is invalid.TooManyRequestsException
if requests are being throttled for high activity.EndpointException
if there was a major error (API down, no internet connection, etc).
Otherwise, if an error occurs in the request, it will be accessible in detail using the $response->error
property (which is null
when successful or a string
with error details otherwise).
If you're an author and want to check a purchase code provided to you from a buyer, this is an example for you. To make this work, you'll want to use Personal Token authentication.
$purchase_code = 'purchase code here';
$token = new Herbert\Envato\Auth\Token('Your Personal Token');
$client = new Herbert\EnvatoClient($token);
$response = $client->user->sale(['code' => $purchase_code]);
if (!$response->error) {
$sale = $response->results;
$sold_at = $sale['sold_at']; // "2013-04-16T01:59:35+10:00"
$license = $sale['license']; // "Regular License"
$supported_until = $sale['supported_until']; // "2013-10-16T00:00:00+10:00"
$item_id = $sale['item']['id']; // 1252984
$item_name = $sale['item']['name']; // "Item Name"
$author_username = $sale['item']['author_username']; // "baileyherbert"
$num_licenses = $sale['purchase_count']; // 3
$buyer_username = $sale['buyer']; // "bestbuyerever"
echo "I got information!";
}
else {
echo "The code produced an error:\n";
echo $response->error;
}
Special thanks to the following people for contributing to this package: