envato.php
envato.php copied to clipboard
🍂 Composer package for the Envato API.
Envato.php
An API client for Envato in PHP, with simplified OAuth, token storage, and request sending.
- Notes
- Installation
- Authentication
- Personal Token
- OAuth
- Persistent OAuth
- Sending Requests
- Getting Request Time
- Rate Limiting
- Custom Requests
- Catalog
- Look up a public collection
- Look up a single item
- Look up a single WordPress theme/plugin version
- Search for items
- Search for comments
- Popular items by site
- Categories by site
- Prices for a particular item
- New items by site and category
- Find featured items
- Random new items
- Profile
- List all of current user's collections
- Look up a collection by ID
- Get a user's profile details
- List a user's badges
- Get a user's items by site
- Get a user's newest items
- User
- List an author's sales
- Look up a sale by purchase code
- List a buyer's purchases
- Look up a buyer's purchase by code
- Download a buyer's purchase
- Get private account details
- Get the current user's username
- Get the current user's email
- Get the user's sales by month
- Get the user's statement
- Market
- Get total number of users
- Get total number of items
- Get total number of items by site
- Other Endpoints
- Get the client's identity
- Handling Errors & Exceptions
- Authorization Errors
- Request Errors
- Examples
- Verifying Purchase Codes
- Contributors
Notes
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.
Installation
Include this into your project using Composer. It will be autoloaded.
composer require baileyherbert/envato
Authentication
Personal Token
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);
OAuth
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
OAuthobject contains methods to generate an authorization URI. - To make this example work, the
redirect_urishould point back to the current file. - Calling
$oauth->tokenwill automatically recognize thecodesent back by Envato and will return something truthy that you can pass intoEnvatoClient().
Persistent OAuth
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->sessionmember 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
EnvatoClientafter 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.
Sending Requests
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'
]);
Getting Request Time
To determine how long a request took to execute (in seconds), you can reference the $response->time property.
Rate Limiting
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();
}
Custom Requests
If there is a new endpoint which is not yet available in this package, you may use the $request property on the
client to manually send the request until it is added.
There are methods available for each request type (get, post, etc). Pass the path as the first parameter. Pass your
POST body variables as the second parameter, these will also replace variables in the path denoted by {}.
$client->request->get('/v1/market/user:{username}.json', [
'username' => 'collis'
]);
Catalog
Look up a public collection
$client->catalog->collection(['id' => 12345]);
Look up a single item
$client->catalog->item(['id' => 12345]);
Look up a single WordPress theme/plugin version
$client->catalog->item_version(['id' => 12345]);
Search for items
$client->catalog->items(['site' => 'codecanyon.net', 'term' => '']);
Search for comments
$client->catalog->comments(['item_id' => 12345]);
Popular items by site
$client->catalog->popular(['site' => 'codecanyon']);
Categories by site
$client->catalog->categories(['site' => 'codecanyon']);
Prices for a particular item
$client->catalog->prices(['item_id' => 12345]);
New items by site and category
$client->catalog->newest(['site' => 'codecanyon', 'category' => 'php-scripts']);
Find featured items
$client->catalog->featured(['site' => 'codecanyon']);
Random new items
$client->catalog->random(['site' => 'codecanyon']);
Profile
The profile category represents a public Envato user.
List all of current user's collections
$client->profile->collections();
Look up a collection by ID
$client->profile->collection(['id' => 12345]);
Get a user's profile details
$client->profile->details(['username' => 'baileyherbert']);
List a user's badges
$client->profile->badges(['username' => 'baileyherbert']);
Get a user's items by site
$client->profile->portfolio(['username' => 'baileyherbert']);
Get a user's newest items
$client->profile->newest(['username' => 'baileyherbert', 'site' => 'codecanyon']);
User
The user category represents the currently-authenticated user.
List an author's sales
$client->user->sales();
Look up a sale by purchase code
$client->user->sale(['code' => '*****']);
List a buyer's purchases
$client->user->purchases();
Look up a buyer's purchase by code
$client->user->purchase(['code' => '*****']);
Download a buyer's purchase
$client->user->download(['purchase_code' => '*****']);
$client->user->download(['item_id' => '123456']);
Get private account details
$client->user->details();
Get the current user's username
$client->user->username();
Get the current user's email
$client->user->email();
Get the user's sales by month
$client->user->sales();
Get the user's statement
$client->user->statement([
'page' => 1,
'from_date' => '2021-02-01',
'to_date' => '2022-06-21',
'type' => 'Sale',
'site' => 'codecanyon.net'
]);
Market
Get total number of users
$client->market->users();
Get total number of items
$client->market->items();
Get total number of items by site
$client->market->site(['site' => 'codecanyon']);
Other Endpoints
Get the client's identity
$identity = $client->getIdentity();
The identity will be an object that looks like this:
object(stdClass)#1 (4) {
["clientId"]=> NULL
["userId"]=> int(1908998)
["scopes"]=> array(18) {
[0]=> string(7) "default"
[1]=> string(13) "user:username"
[2]=> string(10) "user:email"
[3]=> string(12) "user:account"
[4]=> string(14) "user:financial"
[5]=> string(17) "purchase:download"
[6]=> string(12) "sale:history"
[7]=> string(11) "sale:verify"
}
["ttl"]=> int(315360000)
}
If you only care about the userId property, you can retrieve it more easily:
$userId = $client->getUserId(); // int(1908998)
Handling Errors & Exceptions
All exceptions in this libary are under the Herbert\Envato\Exceptions namespace.
Authorization Errors
When performing OAuth authorization, you may encounter one of these exceptions:
InvalidTokenExceptionif the token provided is not a string.MissingPropertyExceptionif OAuth is missing one of the constructor parameters (client_id, client_secret, redirect_uri).NotAuthenticatedExceptionif you try to construct anEnvatoClientbefore being authenticated.
Request Errors
When performing a request, there are four possible exceptions that can be thrown.
BadRequestExceptionif required arguments are missing or are invalid.UnauthorizedExceptionif the current authorization is invalid.TooManyRequestsExceptionif requests are being throttled for high activity.EndpointExceptionif 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).
Examples
Verifying Purchase Codes
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;
}
Contributors
Special thanks to the following contributors for their help in maintaining this package: